diff --git a/src/BMS/Makefile.DANA b/src/BMS/Makefile.DANA index 652c2150fa..f13848d031 100644 --- a/src/BMS/Makefile.DANA +++ b/src/BMS/Makefile.DANA @@ -6,4 +6,4 @@ include $(HALLD_HOME)/src/BMS/Makefile.CURL ADDITIONAL_MODULES += DANA ANALYSIS PID TAGGER TRACKING START_COUNTER ADDITIONAL_MODULES += CERE DIRC CDC TRIGGER -ADDITIONAL_MODULES += FDC TOF BCAL FCAL CCAL HDGEOMETRY HDDM JANA +ADDITIONAL_MODULES += FDC TOF BCAL FCAL ECAL CCAL HDGEOMETRY HDDM JANA diff --git a/src/SBMS/SConstruct.plugin b/src/SBMS/SConstruct.plugin index ee01bfab6d..90d289d861 100644 --- a/src/SBMS/SConstruct.plugin +++ b/src/SBMS/SConstruct.plugin @@ -24,6 +24,18 @@ # diligent of building for multiple platforms using the same source. # +from __future__ import division +from __future__ import absolute_import +from __future__ import print_function +from __future__ import unicode_literals + +from builtins import map +from builtins import str +from builtins import open +from builtins import int +from future import standard_library +standard_library.install_aliases() + import os import sys import subprocess @@ -32,7 +44,7 @@ import glob # Get HALLD_RECON_HOME environment variable, verifying it is set halld_home = os.getenv('HALLD_RECON_HOME') if(halld_home == None): - print 'HALLD_RECON_HOME environment variable not set!' + print('HALLD_RECON_HOME environment variable not set!') exit(-1) # Get HALLD_MY if it exists. Otherwise use HALLD_RECON_HOME @@ -51,7 +63,8 @@ SHOWBUILD = ARGUMENTS.get('SHOWBUILD', 0) osname = os.getenv('BMS_OSNAME', 'build') # Get architecture name -arch = subprocess.Popen(["uname"], stdout=subprocess.PIPE).communicate()[0].strip() +arch_out = ROOT_CFLAGS = subprocess.Popen(["uname"], stdout=subprocess.PIPE).communicate()[0].strip() +arch = str(arch_out, 'utf-8') # Setup initial environment installdir = "%s/%s" %(halld_my, osname) diff --git a/src/SBMS/sbms.py b/src/SBMS/sbms.py index d9bd93c1be..a47b94f5b0 100644 --- a/src/SBMS/sbms.py +++ b/src/SBMS/sbms.py @@ -641,7 +641,7 @@ def AddDANA(env): AddTensorflowLite(env) # optional. Used for CPP pi/mu classification DANA_LIBS = "DANA ANALYSIS KINFITTER PID TAGGER TRACKING START_COUNTER" DANA_LIBS += " CERE DIRC CDC TRIGGER PAIR_SPECTROMETER RF TRD" - DANA_LIBS += " FDC TOF BCAL FCAL CCAL TPOL HDGEOMETRY TTAB FMWPC TAC" + DANA_LIBS += " FDC TOF BCAL FCAL ECAL CCAL TPOL HDGEOMETRY TTAB FMWPC TAC" DANA_LIBS += " DAQ JANA EVENTSTORE" DANA_LIBS += " expat gfortran" env.PrependUnique(LIBS = DANA_LIBS.split()) diff --git a/src/SBMS/sbms_setenv.py b/src/SBMS/sbms_setenv.py index 5c80910bdf..142368cc31 100644 --- a/src/SBMS/sbms_setenv.py +++ b/src/SBMS/sbms_setenv.py @@ -86,6 +86,13 @@ def mk_setenv_csh(env): str += 'setenv HDDS_HOME %s\n' % os.getenv('HDDS_HOME', '$HOME/hdds') str += '\n' + # HDDM + str += '# HDDM\n' + str += 'setenv HDDM_HOME %s\n' % os.getenv('HDDM_HOME', '$HOME/hddm') + str += 'setenv PATH ${HDDM_HOME}/bin:${PATH}\n' + str += 'setenv HDDM_DIR $HDDM_HOME\n' + str += '\n' + # JANA str += '# JANA\n' str += 'setenv JANA_HOME %s\n' % os.getenv('JANA_HOME', '$HOME/jana') @@ -259,6 +266,13 @@ def mk_setenv_bash(env): str += 'export HDDS_HOME=%s\n' % os.getenv('HDDS_HOME', '$HOME/hdds') str += '\n' + # HDDM + str += '# HDDM\n' + str += 'export HDDM_HOME=%s\n' % os.getenv('HDDM_HOME', '$HOME/hddm') + str += 'export PATH=${HDDM_HOME}/bin:${PATH}\n' + str += 'export HDDM_DIR=$HDDM_HOME\n' + str += '\n' + # JANA str += '# JANA\n' str += 'export JANA_HOME=%s\n' % os.getenv('JANA_HOME', '$HOME/jana') diff --git a/src/libraries/ANALYSIS/DAnalysisUtilities.cc b/src/libraries/ANALYSIS/DAnalysisUtilities.cc index a06b05001e..a85db422c5 100644 --- a/src/libraries/ANALYSIS/DAnalysisUtilities.cc +++ b/src/libraries/ANALYSIS/DAnalysisUtilities.cc @@ -626,6 +626,35 @@ void DAnalysisUtilities::Get_UnusedNeutralParticles(JEventLoop* locEventLoop, co } } +void DAnalysisUtilities::Get_UnusedTOFPoints(JEventLoop* locEventLoop, const DParticleCombo* locParticleCombo, vector& locUnusedTOFPoints) const +{ + locUnusedTOFPoints.clear(); + locEventLoop->Get(locUnusedTOFPoints); + + vector locParticleComboSteps = locParticleCombo->Get_ParticleComboSteps(); + for(size_t loc_icombo = 0; loc_icombo < locParticleComboSteps.size(); ++loc_icombo) { + const DParticleComboStep* locParticleComboStep = locParticleCombo->Get_ParticleComboStep(loc_icombo); + for(size_t loc_ipart = 0; loc_ipart < locParticleComboStep->Get_NumFinalParticles(); ++loc_ipart) { + + auto locParticle = locParticleComboStep->Get_FinalParticle_Measured(loc_ipart); + if(locParticle == nullptr || locParticle->charge() == 0) continue; + + const DChargedTrack* locChargedTrack = static_cast(locParticleComboStep->Get_FinalParticle_SourceObject(loc_ipart)); + const DChargedTrackHypothesis* locChargedTrackHypothesis = locChargedTrack->Get_Hypothesis(locParticle->PID()); + + if(locChargedTrackHypothesis->Get_TOFHitMatchParams() == nullptr) continue; + const DTOFPoint *locTOFPoint = locChargedTrackHypothesis->Get_TOFHitMatchParams()->dTOFPoint; + + for(auto locIterator = locUnusedTOFPoints.begin(); locIterator != locUnusedTOFPoints.end();) { + if(locTOFPoint != *locIterator) + ++locIterator; + else + locIterator = locUnusedTOFPoints.erase(locIterator); + } + } + } +} + void DAnalysisUtilities::Get_ThrownParticleSteps(JEventLoop* locEventLoop, deque > >& locThrownSteps) const { vector locMCThrowns; diff --git a/src/libraries/ANALYSIS/DAnalysisUtilities.h b/src/libraries/ANALYSIS/DAnalysisUtilities.h index 169d7414cb..9daeadd7c1 100644 --- a/src/libraries/ANALYSIS/DAnalysisUtilities.h +++ b/src/libraries/ANALYSIS/DAnalysisUtilities.h @@ -72,6 +72,7 @@ class DAnalysisUtilities : public JObject void Get_UnusedNeutralShowers(JEventLoop* locEventLoop, const DParticleCombo* locParticleCombo, vector& locUnusedNeutralShowers) const; void Get_UnusedNeutralParticles(JEventLoop* locEventLoop, const DParticleCombo* locParticleCombo, vector& locUnusedNeutralParticles) const; + void Get_UnusedTOFPoints(JEventLoop* locEventLoop, const DParticleCombo* locParticleCombo, vector& locUnusedTOFPoints) const; void Get_ThrownParticleSteps(JEventLoop* locEventLoop, deque > >& locThrownSteps) const; bool Are_ThrownPIDsSameAsDesired(JEventLoop* locEventLoop, const deque& locDesiredPIDs, Particle_t locMissingPID = Unknown) const; diff --git a/src/libraries/ANALYSIS/DEventWriterROOT.cc b/src/libraries/ANALYSIS/DEventWriterROOT.cc index 62e30d3761..33440341f7 100644 --- a/src/libraries/ANALYSIS/DEventWriterROOT.cc +++ b/src/libraries/ANALYSIS/DEventWriterROOT.cc @@ -167,6 +167,8 @@ void DEventWriterROOT::Create_DataTree(const DReaction* locReaction, JEventLoop* locBranchRegister.Register_Single("RunNumber"); locBranchRegister.Register_Single("EventNumber"); locBranchRegister.Register_Single("L1TriggerBits"); + locBranchRegister.Register_Single("L1BCALEnergy"); + locBranchRegister.Register_Single("L1FCALEnergy"); //create X4_Production locBranchRegister.Register_Single("X4_Production"); @@ -1344,6 +1346,9 @@ void DEventWriterROOT::Fill_DataTree(JEventLoop* locEventLoop, const DReaction* locTreeFillData->Fill_Single("RunNumber", locEventLoop->GetJEvent().GetRunNumber()); locTreeFillData->Fill_Single("EventNumber", locEventLoop->GetJEvent().GetEventNumber()); locTreeFillData->Fill_Single("L1TriggerBits", locTrigger->Get_L1TriggerBits()); + locTreeFillData->Fill_Single("L1BCALEnergy", locTrigger->Get_GTP_BCALEnergy()); + locTreeFillData->Fill_Single("L1FCALEnergy", locTrigger->Get_GTP_FCALEnergy()); + //PRODUCTION X4 DLorentzVector locProductionX4 = locVertex->dSpacetimeVertex; @@ -2409,7 +2414,7 @@ void DEventWriterROOT::Fill_KinFitData(DTreeFillData* locTreeFillData, JEventLoo //Look at the decay products: //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ vector finalParticlesMeasured = locParticleCombos.at(iPC)->Get_FinalParticles_Measured(locReaction, d_AllCharges); - vector finalParticles = locParticleCombos.at(iPC)->Get_FinalParticles(locReaction, d_AllCharges); + vector finalParticles = locParticleCombos.at(iPC)->Get_FinalParticles(locReaction); //, d_AllCharges); vector finalParticleObjects = locParticleCombos.at(iPC)->Get_FinalParticle_SourceObjects(d_AllCharges); nMeasuredFinalParticles = finalParticlesMeasured.size(); diff --git a/src/libraries/ANALYSIS/DHistogramActions_Independent.cc b/src/libraries/ANALYSIS/DHistogramActions_Independent.cc index b645ef145f..10217a8361 100644 --- a/src/libraries/ANALYSIS/DHistogramActions_Independent.cc +++ b/src/libraries/ANALYSIS/DHistogramActions_Independent.cc @@ -4032,7 +4032,19 @@ bool DHistogramAction_TriggerStudies::Perform_Action(JEventLoop* locEventLoop, c locEventLoop->GetSingle(locTrigger); if(locTrigger == nullptr) return true; + + // allow for this histogram to be called for a particular reaction, and then only plot it for + // events that pass some reasonable kinematic fit cut + if(dKinFitCLCut >= 0.) { + const DKinFitResults* locKinFitResults = locParticleCombo->Get_KinFitResults(); + if(locKinFitResults == NULL) + return true; + double locConfidenceLevel = locKinFitResults->Get_ConfidenceLevel(); + if(locConfidenceLevel < dKinFitCLCut) + return true; + } + //FILL HISTOGRAMS //Since we are filling histograms local to this action, it will not interfere with other ROOT operations: can use action-wide ROOT lock diff --git a/src/libraries/ANALYSIS/DHistogramActions_Independent.h b/src/libraries/ANALYSIS/DHistogramActions_Independent.h index 8d4e35d349..48e275601d 100644 --- a/src/libraries/ANALYSIS/DHistogramActions_Independent.h +++ b/src/libraries/ANALYSIS/DHistogramActions_Independent.h @@ -993,21 +993,23 @@ class DHistogramAction_TrackMultiplicity : public DAnalysisAction class DHistogramAction_TriggerStudies : public DAnalysisAction { public: - DHistogramAction_TriggerStudies(const DReaction* locReaction, string locActionUniqueString = "") : + DHistogramAction_TriggerStudies(const DReaction* locReaction, string locActionUniqueString = "", double locKinFitCLCut=-1.) : DAnalysisAction(locReaction, "Hist_TriggerStudies", false, locActionUniqueString), - dBCALBins(240), dFCALBins(240), dMaxBCALEnergy(12.), dMaxFCALEnergy(12.) { } + dBCALBins(240), dFCALBins(240), dMaxBCALEnergy(12.), dMaxFCALEnergy(12.), dKinFitCLCut(locKinFitCLCut) { } DHistogramAction_TriggerStudies(string locActionUniqueString) : DAnalysisAction(NULL, "Hist_TriggerStudies", false, ""), - dBCALBins(240), dFCALBins(240), dMaxBCALEnergy(12.), dMaxFCALEnergy(12.) { } + dBCALBins(240), dFCALBins(240), dMaxBCALEnergy(12.), dMaxFCALEnergy(12.), dKinFitCLCut(-1.) { } DHistogramAction_TriggerStudies(void) : DAnalysisAction(NULL, "Hist_TriggerStudies", false, ""), - dBCALBins(240), dFCALBins(240), dMaxBCALEnergy(12.), dMaxFCALEnergy(12.) { } + dBCALBins(240), dFCALBins(240), dMaxBCALEnergy(12.), dMaxFCALEnergy(12.), dKinFitCLCut(-1.) { } int dBCALBins, dFCALBins; double dMaxBCALEnergy; double dMaxFCALEnergy; + + double dKinFitCLCut; void Initialize(JEventLoop* locEventLoop); void Run_Update(JEventLoop* locEventLoop){} diff --git a/src/libraries/ANALYSIS/DSourceComboP4Handler.cc b/src/libraries/ANALYSIS/DSourceComboP4Handler.cc index 65bf085468..54b30e21e9 100644 --- a/src/libraries/ANALYSIS/DSourceComboP4Handler.cc +++ b/src/libraries/ANALYSIS/DSourceComboP4Handler.cc @@ -134,13 +134,13 @@ void DSourceComboP4Handler::Define_DefaultCuts(void) dInvariantMassCuts.emplace(omega, std::make_pair(0.4, 1.2)); dInvariantMassCuts.emplace(EtaPrime, std::make_pair(0.6, 1.3)); dInvariantMassCuts.emplace(phiMeson, std::make_pair(0.8, 1.2)); - dInvariantMassCuts.emplace(D0, std::make_pair(1.8, 1.92)); - dInvariantMassCuts.emplace(AntiD0, std::make_pair(1.8, 1.92)); - dInvariantMassCuts.emplace(DPlus, std::make_pair(1.8, 1.92)); - dInvariantMassCuts.emplace(DMinus, std::make_pair(1.8, 1.92)); - dInvariantMassCuts.emplace(Dstar0, std::make_pair(1.9, 2.1)); - dInvariantMassCuts.emplace(DstarPlus, std::make_pair(1.9, 2.1)); - dInvariantMassCuts.emplace(DstarMinus, std::make_pair(1.9, 2.1)); + dInvariantMassCuts.emplace(D0, std::make_pair(1.7, 2.0)); + dInvariantMassCuts.emplace(AntiD0, std::make_pair(1.7, 2.0)); + dInvariantMassCuts.emplace(DPlus, std::make_pair(1.7, 2.0)); + dInvariantMassCuts.emplace(DMinus, std::make_pair(1.7, 2.0)); + dInvariantMassCuts.emplace(Dstar0, std::make_pair(1.8, 2.2)); + dInvariantMassCuts.emplace(DstarPlus, std::make_pair(1.8, 2.2)); + dInvariantMassCuts.emplace(DstarMinus, std::make_pair(1.8, 2.2)); // dInvariantMassCuts.emplace(Jpsi, std::make_pair(2.7, 3.5)); //INVARIANT MASS CUTS: BARYONS @@ -157,7 +157,8 @@ void DSourceComboP4Handler::Define_DefaultCuts(void) dInvariantMassCuts.emplace(AntiXi0, dInvariantMassCuts[XiMinus]); dInvariantMassCuts.emplace(AntiXiPlus, dInvariantMassCuts[XiMinus]); dInvariantMassCuts.emplace(OmegaMinus, std::make_pair(1.32, 2.22)); - dInvariantMassCuts.emplace(Lambda_c, std::make_pair(2.0, 2.6)); + dInvariantMassCuts.emplace(Lambda_c, std::make_pair(2.1, 2.5)); + dInvariantMassCuts.emplace(Sigma_cPlusPlus, std::make_pair(2.2, 2.7)); //DEFAULT MISSING MASS SQUARED CUT FUNCTION diff --git a/src/libraries/ANALYSIS/DTreeInterface.h b/src/libraries/ANALYSIS/DTreeInterface.h index 76e63bded2..264891124b 100644 --- a/src/libraries/ANALYSIS/DTreeInterface.h +++ b/src/libraries/ANALYSIS/DTreeInterface.h @@ -213,7 +213,9 @@ template inline void DTreeInterface::Create_Branch_TObject(stri return; //already created dMemoryMap_TObject[locBranchName] = (TObject*)(new DType()); - dTree->Branch(locBranchName.c_str(), (DType**)&(dMemoryMap_TObject[locBranchName]), 32000, 0); //0: don't split + TObject **objptr = new TObject*; + *objptr = dMemoryMap_TObject[locBranchName]; + dTree->Branch(locBranchName.c_str(), objptr, 32000, 0); //0: don't split } template inline void DTreeInterface::Create_Branch_FundamentalArray(string locBranchName, string locArraySizeString, unsigned int locInitialSize) @@ -232,7 +234,9 @@ template inline void DTreeInterface::Create_Branch_ClonesArray( return; //already created dMemoryMap_ClonesArray[locBranchName] = new TClonesArray(DType::Class()->GetName(), locInitialSize); - dTree->Branch(locBranchName.c_str(), &(dMemoryMap_ClonesArray[locBranchName]), 32000, 0); //0: don't split + TClonesArray **arrptr = new TClonesArray*; + *arrptr = dMemoryMap_ClonesArray[locBranchName]; + dTree->Branch(locBranchName.c_str(), arrptr, 32000, 0); //0: don't split } /************************************************************** TEMPLATE SPECIALIZATIONS **************************************************************/ diff --git a/src/libraries/BCAL/DBCALHit_factory.cc b/src/libraries/BCAL/DBCALHit_factory.cc index 351cfb96ba..60e816e05c 100644 --- a/src/libraries/BCAL/DBCALHit_factory.cc +++ b/src/libraries/BCAL/DBCALHit_factory.cc @@ -61,6 +61,7 @@ jerror_t DBCALHit_factory::brun(jana::JEventLoop *eventLoop, int32_t runnumber) vector raw_ADC_timing_offsets; vector raw_channel_global_offset; vector raw_tdiff_u_d; + vector raw_bad_channels; if(print_messages) jout << "In DBCALHit_factory, loading constants..." << endl; @@ -105,6 +106,8 @@ jerror_t DBCALHit_factory::brun(jana::JEventLoop *eventLoop, int32_t runnumber) jout << "Error loading /BCAL/channel_global_offset !" << endl; if(eventLoop->GetCalib("/BCAL/tdiff_u_d", raw_tdiff_u_d)) jout << "Error loading /BCAL/tdiff_u_d !" << endl; + if(eventLoop->GetCalib("/BCAL/bad_channels", raw_bad_channels)) + jout << "Error loading /BCAL/bad_channels !" << endl; if (PRINTCALIBRATION) jout << "DBCALHit_factory >> raw_gains" << endl; FillCalibTable(gains, raw_gains); @@ -116,6 +119,8 @@ jerror_t DBCALHit_factory::brun(jana::JEventLoop *eventLoop, int32_t runnumber) FillCalibTableShort(channel_global_offset, raw_channel_global_offset); if (PRINTCALIBRATION) jout << "DBCALHit_factory >> raw_tdiff_u_d" << endl; FillCalibTableShort(tdiff_u_d, raw_tdiff_u_d); + if (PRINTCALIBRATION) jout << "DBCALHit_factory >> raw_bad_channels" << endl; + FillCalibTable(bad_channels, raw_bad_channels); std::vector > saturation_ADC_pars; if(eventLoop->GetCalib("/BCAL/ADC_saturation", saturation_ADC_pars)) @@ -167,6 +172,10 @@ jerror_t DBCALHit_factory::evnt(JEventLoop *loop, uint64_t eventnumber) for(unsigned int i=0; i 0 ) continue; + // Error checking for pre-Fall 2016 firmware if(digihit->datasource == 1) { // There is a slight difference between Mode 7 and 8 data diff --git a/src/libraries/BCAL/DBCALHit_factory.h b/src/libraries/BCAL/DBCALHit_factory.h index f1761f201b..f802a4a590 100644 --- a/src/libraries/BCAL/DBCALHit_factory.h +++ b/src/libraries/BCAL/DBCALHit_factory.h @@ -58,6 +58,7 @@ class DBCALHit_factory:public jana::JFactory{ bcal_digi_constants_t ADC_timing_offsets; bcal_digi_constants_t channel_global_offset; bcal_digi_constants_t tdiff_u_d; + bcal_digi_constants_t bad_channels; const int GetCalibIndex( int module, int layer, int sector ) const { return BCAL_NUM_LAYERS*BCAL_NUM_SECTORS*(module-1) + BCAL_NUM_SECTORS*(layer-1) + (sector-1); diff --git a/src/libraries/CCAL/CCAL_init.cc b/src/libraries/CCAL/CCAL_init.cc index 4854da861c..bd1460d29f 100644 --- a/src/libraries/CCAL/CCAL_init.cc +++ b/src/libraries/CCAL/CCAL_init.cc @@ -15,13 +15,13 @@ using namespace jana; jerror_t CCAL_init(JEventLoop *loop) { /// Create and register CCAL data factories - loop->AddFactory(new JFactory()); - loop->AddFactory(new JFactory()); + loop->AddFactory(new JFactory()); + loop->AddFactory(new JFactory()); loop->AddFactory(new DCCALHit_factory()); loop->AddFactory(new DCCALShower_factory()); loop->AddFactory(new JFactory("TRUTH")); loop->AddFactory(new DCCALTruthShower_factory()); loop->AddFactory(new DCCALGeometry_factory()); - + return NOERROR; } diff --git a/src/libraries/CCAL/DCCALGeometry.cc b/src/libraries/CCAL/DCCALGeometry.cc index e00d592c85..42ecbcfb94 100644 --- a/src/libraries/CCAL/DCCALGeometry.cc +++ b/src/libraries/CCAL/DCCALGeometry.cc @@ -18,23 +18,23 @@ using namespace std; DCCALGeometry::DCCALGeometry() : m_numActiveBlocks( 0 ){ - for( int row = 0; row < kCCALBlocksTall; row++ ){ - for( int col = 0; col < kCCALBlocksWide; col++ ){ - - // transform to beam axis - m_positionOnFace[row][col] = - DVector2( ( (double)col - kCCALMidBlock + 0.5 ) * blockSize(), - ( (double)row - kCCALMidBlock + 0.5 ) * blockSize() ); - - m_activeBlock[row][col] = true; - - // build the "channel map" - m_channelNumber[row][col] = m_numActiveBlocks; - m_row[m_numActiveBlocks] = row; - m_column[m_numActiveBlocks] = col; - - m_numActiveBlocks++; - } + for( int row = 0; row < kCCALBlocksTall; row++ ){ + for( int col = 0; col < kCCALBlocksWide; col++ ){ + + // transform to beam axis + m_positionOnFace[row][col] = + DVector2( ( (double)col - kCCALMidBlock + 0.5 ) * blockSize(), + ( (double)row - kCCALMidBlock + 0.5 ) * blockSize() ); + + m_activeBlock[row][col] = true; + + // build the "channel map" + m_channelNumber[row][col] = m_numActiveBlocks; + m_row[m_numActiveBlocks] = row; + m_column[m_numActiveBlocks] = col; + + m_numActiveBlocks++; + } } } @@ -49,7 +49,7 @@ DCCALGeometry::isBlockActive( int row, int column ) const // 12/13/05 DL if( row < 0 || row >= kCCALBlocksTall )return false; if( column < 0 || column >= kCCALBlocksWide )return false; - + assert( row >= 0 && row < kCCALBlocksTall ); assert( column >= 0 && column < kCCALBlocksWide ); diff --git a/src/libraries/CCAL/DCCALGeometry_factory.h b/src/libraries/CCAL/DCCALGeometry_factory.h index 1ed85bb5c0..6303f775fe 100644 --- a/src/libraries/CCAL/DCCALGeometry_factory.h +++ b/src/libraries/CCAL/DCCALGeometry_factory.h @@ -37,13 +37,13 @@ class DCCALGeometry_factory:public jana::JFactory{ //------------------ // evnt //------------------ - jerror_t evnt(JEventLoop *loop, uint64_t eventnumber) - { + jerror_t evnt(JEventLoop *loop, uint64_t eventnumber) + { // Reuse existing DBCALGeometry object. if( ccalgeometry ) _data.push_back( ccalgeometry ); - return NOERROR; - } + return NOERROR; + } //------------------ // erun diff --git a/src/libraries/CCAL/DCCALHit.h b/src/libraries/CCAL/DCCALHit.h index 5208c4e621..8f33e75b09 100644 --- a/src/libraries/CCAL/DCCALHit.h +++ b/src/libraries/CCAL/DCCALHit.h @@ -14,8 +14,8 @@ using namespace jana; class DCCALHit:public jana::JObject{ public: - - JOBJECT_PUBLIC(DCCALHit); + + JOBJECT_PUBLIC(DCCALHit); DCCALHit(){} @@ -27,9 +27,9 @@ class DCCALHit:public jana::JObject{ float t; float intOverPeak; - + void toStrings(vector > &items)const{ - AddString(items, "row", "%4d", row); + AddString(items, "row", "%4d", row); AddString(items, "column", "%4d", column); AddString(items, "x(cm)", "%3.1f", x); AddString(items, "y(cm)", "%3.1f", y); diff --git a/src/libraries/CCAL/DCCALHit_factory.cc b/src/libraries/CCAL/DCCALHit_factory.cc index a052f58580..8d61637262 100644 --- a/src/libraries/CCAL/DCCALHit_factory.cc +++ b/src/libraries/CCAL/DCCALHit_factory.cc @@ -24,14 +24,14 @@ using namespace jana; // Constructor //---------------- DCCALHit_factory::DCCALHit_factory(){ - - HIT_DEBUG = 0; - DB_PEDESTAL = 1; // 1 - take from DB - // 0 - event-by-event pedestal subtraction - - gPARMS->SetDefaultParameter("CCAL:HIT_DEBUG", HIT_DEBUG); - gPARMS->SetDefaultParameter("CCAL:DB_PEDESTAL", DB_PEDESTAL); - + + HIT_DEBUG = 0; + DB_PEDESTAL = 1; + // 1 - take from DB + // 0 - event-by-event pedestal subtraction + + gPARMS->SetDefaultParameter("CCAL:HIT_DEBUG", HIT_DEBUG); + gPARMS->SetDefaultParameter("CCAL:DB_PEDESTAL", DB_PEDESTAL); } @@ -40,30 +40,28 @@ DCCALHit_factory::DCCALHit_factory(){ //------------------ jerror_t DCCALHit_factory::init(void) { - // initialize calibration tables - vector< vector > gains_tmp(DCCALGeometry::kCCALBlocksTall, - vector(DCCALGeometry::kCCALBlocksWide)); - vector< vector > pedestals_tmp(DCCALGeometry::kCCALBlocksTall, - vector(DCCALGeometry::kCCALBlocksWide)); - - vector< vector > time_offsets_tmp(DCCALGeometry::kCCALBlocksTall, - vector(DCCALGeometry::kCCALBlocksWide)); - vector< vector > adc_offsets_tmp(DCCALGeometry::kCCALBlocksTall, - vector(DCCALGeometry::kCCALBlocksWide)); - - gains = gains_tmp; - pedestals = pedestals_tmp; - time_offsets = time_offsets_tmp; - adc_offsets = adc_offsets_tmp; - - - adc_en_scale = 0; - adc_time_scale = 0; - - base_time = 0; - - - return NOERROR; + // initialize calibration tables + vector< vector > gains_tmp(DCCALGeometry::kCCALBlocksTall, + vector(DCCALGeometry::kCCALBlocksWide)); + vector< vector > pedestals_tmp(DCCALGeometry::kCCALBlocksTall, + vector(DCCALGeometry::kCCALBlocksWide)); + + vector< vector > time_offsets_tmp(DCCALGeometry::kCCALBlocksTall, + vector(DCCALGeometry::kCCALBlocksWide)); + vector< vector > adc_offsets_tmp(DCCALGeometry::kCCALBlocksTall, + vector(DCCALGeometry::kCCALBlocksWide)); + + gains = gains_tmp; + pedestals = pedestals_tmp; + time_offsets = time_offsets_tmp; + adc_offsets = adc_offsets_tmp; + + adc_en_scale = 0; + adc_time_scale = 0; + + base_time = 0; + + return NOERROR; } //------------------ @@ -71,127 +69,126 @@ jerror_t DCCALHit_factory::init(void) //------------------ jerror_t DCCALHit_factory::brun(jana::JEventLoop *eventLoop, int32_t runnumber) { - - // Only print messages for one thread whenever run number change - static pthread_mutex_t print_mutex = PTHREAD_MUTEX_INITIALIZER; - static set runs_announced; - pthread_mutex_lock(&print_mutex); - // bool print_messages = false; - if(runs_announced.find(runnumber) == runs_announced.end()){ - // print_messages = true; - runs_announced.insert(runnumber); - } - pthread_mutex_unlock(&print_mutex); - - // extract the CCAL Geometry - vector ccalGeomVect; - eventLoop->Get( ccalGeomVect ); - if (ccalGeomVect.size() < 1) - return OBJECT_NOT_AVAILABLE; - const DCCALGeometry& ccalGeom = *(ccalGeomVect[0]); - - - vector< double > ccal_gains_ch; - vector< double > ccal_pedestals_ch; - vector< double > time_offsets_ch; - vector< double > adc_offsets_ch; - - // load scale factors - map scale_factors; - - if (eventLoop->GetCalib("/CCAL/digi_scales", scale_factors)) - jout << "Error loading /CCAL/digi_scales !" << endl; - if (scale_factors.find("ADC_EN_SCALE") != scale_factors.end()) - adc_en_scale = scale_factors["ADC_EN_SCALE"]; - else - jerr << "Unable to get ADC_EN_SCALE from /CCAL/digi_scales !" << endl; - if (scale_factors.find("ADC_TIME_SCALE") != scale_factors.end()) - adc_time_scale = scale_factors["ADC_TIME_SCALE"]; - else - jerr << "Unable to get ADC_TIME_SCALE from /CCAL/digi_scales !" << endl; - - map base_time_offset; - if (eventLoop->GetCalib("/CCAL/base_time_offset",base_time_offset)) - jout << "Error loading /CCAL/base_time_offset !" << endl; - if (base_time_offset.find("BASE_TIME") != base_time_offset.end()) - base_time = base_time_offset["BASE_TIME"]; - else - jerr << "Unable to get BASE_TIME from /CCAL/base_time_offset !" << endl; - - - if (eventLoop->GetCalib("/CCAL/gains", ccal_gains_ch)) - jout << "DCCALHit_factory: Error loading /CCAL/gains !" << endl; - if (eventLoop->GetCalib("/CCAL/pedestals", ccal_pedestals_ch)) - jout << "DCCALHit_factory: Error loading /CCAL/pedestals !" << endl; - - if (eventLoop->GetCalib("/CCAL/timing_offsets", time_offsets_ch)) - jout << "Error loading /CCAL/timing_offsets !" << endl; - if (eventLoop->GetCalib("/CCAL/adc_offsets", adc_offsets_ch)) - jout << "Error loading /CCAL/adc_offsets !" << endl; - - - LoadCCALConst(gains, ccal_gains_ch, ccalGeom); - LoadCCALConst(pedestals, ccal_pedestals_ch, ccalGeom); - LoadCCALConst(time_offsets, time_offsets_ch, ccalGeom); - LoadCCALConst(adc_offsets, adc_offsets_ch, ccalGeom); - - - if(HIT_DEBUG == 1){ - - - cout << endl; - cout << " ------- Gains -----------" << endl; - - for(int ii = 0; ii < 12; ii++){ - for(int jj = 0; jj < 12; jj++){ - cout << " " << gains[ii][jj]; - } - cout << endl; - } - - cout << endl; - cout << " ------- Pedestals -----------" << endl; - - for(int ii = 0; ii < 12; ii++){ - for(int jj = 0; jj < 12; jj++){ - cout << " " << pedestals[ii][jj]; - } - cout << endl; - } - - cout << endl; - cout << " ------- Timing offsets -----------" << endl; - - for(int ii = 0; ii < 12; ii++){ - for(int jj = 0; jj < 12; jj++){ - cout << " " << time_offsets[ii][jj]; + + // Only print messages for one thread whenever run number change + static pthread_mutex_t print_mutex = PTHREAD_MUTEX_INITIALIZER; + static set runs_announced; + pthread_mutex_lock(&print_mutex); + // bool print_messages = false; + if(runs_announced.find(runnumber) == runs_announced.end()){ + // print_messages = true; + runs_announced.insert(runnumber); } - cout << endl; - } - - cout << endl; - cout << " ------- ADC offsets -----------" << endl; - - for(int ii = 0; ii < 12; ii++){ - for(int jj = 0; jj < 12; jj++){ - cout << " " << adc_offsets[ii][jj]; + pthread_mutex_unlock(&print_mutex); + + // extract the CCAL Geometry + vector ccalGeomVect; + eventLoop->Get( ccalGeomVect ); + if (ccalGeomVect.size() < 1) + return OBJECT_NOT_AVAILABLE; + const DCCALGeometry& ccalGeom = *(ccalGeomVect[0]); + + + vector< double > ccal_gains_ch; + vector< double > ccal_pedestals_ch; + vector< double > time_offsets_ch; + vector< double > adc_offsets_ch; + + // load scale factors + map scale_factors; + + if (eventLoop->GetCalib("/CCAL/digi_scales", scale_factors)) + jout << "Error loading /CCAL/digi_scales !" << endl; + if (scale_factors.find("ADC_EN_SCALE") != scale_factors.end()) + adc_en_scale = scale_factors["ADC_EN_SCALE"]; + else + jerr << "Unable to get ADC_EN_SCALE from /CCAL/digi_scales !" << endl; + if (scale_factors.find("ADC_TIME_SCALE") != scale_factors.end()) + adc_time_scale = scale_factors["ADC_TIME_SCALE"]; + else + jerr << "Unable to get ADC_TIME_SCALE from /CCAL/digi_scales !" << endl; + + map base_time_offset; + if (eventLoop->GetCalib("/CCAL/base_time_offset",base_time_offset)) + jout << "Error loading /CCAL/base_time_offset !" << endl; + if (base_time_offset.find("BASE_TIME") != base_time_offset.end()) + base_time = base_time_offset["BASE_TIME"]; + else + jerr << "Unable to get BASE_TIME from /CCAL/base_time_offset !" << endl; + + + if (eventLoop->GetCalib("/CCAL/gains", ccal_gains_ch)) + jout << "DCCALHit_factory: Error loading /CCAL/gains !" << endl; + if (eventLoop->GetCalib("/CCAL/pedestals", ccal_pedestals_ch)) + jout << "DCCALHit_factory: Error loading /CCAL/pedestals !" << endl; + + if (eventLoop->GetCalib("/CCAL/timing_offsets", time_offsets_ch)) + jout << "Error loading /CCAL/timing_offsets !" << endl; + if (eventLoop->GetCalib("/CCAL/adc_offsets", adc_offsets_ch)) + jout << "Error loading /CCAL/adc_offsets !" << endl; + + + LoadCCALConst(gains, ccal_gains_ch, ccalGeom); + LoadCCALConst(pedestals, ccal_pedestals_ch, ccalGeom); + LoadCCALConst(time_offsets, time_offsets_ch, ccalGeom); + LoadCCALConst(adc_offsets, adc_offsets_ch, ccalGeom); + + + if(HIT_DEBUG == 1){ + + cout << endl; + cout << " ------- Gains -----------" << endl; + + for(int ii = 0; ii < 12; ii++){ + for(int jj = 0; jj < 12; jj++){ + cout << " " << gains[ii][jj]; + } + cout << endl; + } + + cout << endl; + cout << " ------- Pedestals -----------" << endl; + + for(int ii = 0; ii < 12; ii++){ + for(int jj = 0; jj < 12; jj++){ + cout << " " << pedestals[ii][jj]; + } + cout << endl; + } + + cout << endl; + cout << " ------- Timing offsets -----------" << endl; + + for(int ii = 0; ii < 12; ii++){ + for(int jj = 0; jj < 12; jj++){ + cout << " " << time_offsets[ii][jj]; + } + cout << endl; + } + + cout << endl; + cout << " ------- ADC offsets -----------" << endl; + + for(int ii = 0; ii < 12; ii++){ + for(int jj = 0; jj < 12; jj++){ + cout << " " << adc_offsets[ii][jj]; + } + cout << endl; + } + + cout << endl; + cout << "ADC_EN_SCALE = " << adc_en_scale << endl; + cout << "ADC_TIME_SCALE = " << adc_time_scale << endl; + + cout << endl; + + cout << "BASE_TIME_OFFSET = " << base_time << endl; + + cout << endl; + } - cout << endl; - } - - cout << endl; - cout << "ADC_EN_SCALE = " << adc_en_scale << endl; - cout << "ADC_TIME_SCALE = " << adc_time_scale << endl; - - cout << endl; - - cout << "BASE_TIME_OFFSET = " << base_time << endl; - - cout << endl; - - } - - return NOERROR; + + return NOERROR; } //------------------ @@ -199,95 +196,94 @@ jerror_t DCCALHit_factory::brun(jana::JEventLoop *eventLoop, int32_t runnumber) //------------------ jerror_t DCCALHit_factory::evnt(JEventLoop *loop, uint64_t eventnumber) { - /// Generate DCCALHit object for each DCCALDigiHit object. - /// This is where the first set of calibration constants - /// is applied to convert from digitzed units into natural - /// units. - /// - /// Note that this code does NOT get called for simulated - /// data in HDDM format. The HDDM event source will copy - /// the precalibrated values directly into the _data vector. - - - // extract the CCAL Geometry - vector ccalGeomVect; - eventLoop->Get( ccalGeomVect ); - if (ccalGeomVect.size() < 1) - return OBJECT_NOT_AVAILABLE; - const DCCALGeometry& ccalGeom = *(ccalGeomVect[0]); - - - vector digihits; - - loop->Get(digihits); - - for (unsigned int i = 0; i < digihits.size(); i++) { - - const DCCALDigiHit *digihit = digihits[i]; - - double nsamples_integral = digihit->nsamples_integral; - double nsamples_pedestal = digihit->nsamples_pedestal; - - - // Currently use pedestals from the DB. We'll switch to the - // event-by-event pedestal subtraction later - - double pedestal = 0; + /// Generate DCCALHit object for each DCCALDigiHit object. + /// This is where the first set of calibration constants + /// is applied to convert from digitzed units into natural + /// units. + /// + /// Note that this code does NOT get called for simulated + /// data in HDDM format. The HDDM event source will copy + /// the precalibrated values directly into the _data vector. + + + // extract the CCAL Geometry + vector ccalGeomVect; + eventLoop->Get( ccalGeomVect ); + if (ccalGeomVect.size() < 1) + return OBJECT_NOT_AVAILABLE; + const DCCALGeometry& ccalGeom = *(ccalGeomVect[0]); + + vector digihits; - if(DB_PEDESTAL == 1) - pedestal = pedestals[digihit->row][digihit->column]; - else { - pedestal = (double)digihit->pedestal/nsamples_pedestal; + loop->Get(digihits); + + for (unsigned int i = 0; i < digihits.size(); i++) { + + const DCCALDigiHit *digihit = digihits[i]; + + double nsamples_integral = digihit->nsamples_integral; + double nsamples_pedestal = digihit->nsamples_pedestal; + + // Currently use pedestals from the DB. We'll switch to the + // event-by-event pedestal subtraction later + + double pedestal = 0; + + if(DB_PEDESTAL == 1) + pedestal = pedestals[digihit->row][digihit->column]; + else { + pedestal = (double)digihit->pedestal/nsamples_pedestal; + } + + double integratedPedestal = pedestal * nsamples_integral; + double pulse_amplitude = digihit->pulse_peak - pedestal; + + double pulse_int = (double)digihit->pulse_integral; + double pulse_time = (double)digihit->pulse_time; + + + if(HIT_DEBUG == 1) { + cout << "Row = " << digihit->row << "Column = " << digihit->column << + " pulse_int = " << pulse_int << " integratedPedestal = " << + integratedPedestal << " Pedestal = " << pedestal << endl; + } + + double pulse_int_ped_subt = adc_en_scale * gains[digihit->row][digihit->column] + * (pulse_int - integratedPedestal); + double pulse_time_correct = adc_time_scale * pulse_time + base_time + - time_offsets[digihit->row][digihit->column] + + adc_offsets[digihit->row][digihit->column]; + + if(pulse_int_ped_subt > 0 && pulse_time > 0){ + + // Build hit object + DCCALHit *hit = new DCCALHit; + + hit->row = digihit->row; + hit->column = digihit->column; + + hit->E = pulse_int_ped_subt; + hit->t = pulse_time_correct; + + // Get position of blocks on front face. (This should really come from + // hdgeant directly so the poisitions can be shifted in mcsmear.) + DVector2 pos = ccalGeom.positionOnFace(hit->row, hit->column); + hit->x = pos.X(); + hit->y = pos.Y(); + + if(pulse_amplitude > 0){ + hit->intOverPeak = (pulse_int - integratedPedestal)/pulse_amplitude; + } else + hit->intOverPeak = 0; + + hit->AddAssociatedObject(digihit); + _data.push_back(hit); + + } // Good hit + } - - - double integratedPedestal = pedestal * nsamples_integral; - double pulse_amplitude = digihit->pulse_peak - pedestal; - - double pulse_int = (double)digihit->pulse_integral; - double pulse_time = (double)digihit->pulse_time; - - - if(HIT_DEBUG == 1) - cout << "Row = " << digihit->row << "Column = " << digihit->column << - " pulse_int = " << pulse_int << " integratedPedestal = " << integratedPedestal << - " Pedestal = " << pedestal << endl; - - double pulse_int_ped_subt = adc_en_scale * gains[digihit->row][digihit->column] * (pulse_int - integratedPedestal); - double pulse_time_correct = adc_time_scale * pulse_time + base_time - time_offsets[digihit->row][digihit->column] + - adc_offsets[digihit->row][digihit->column]; - - - if(pulse_int_ped_subt > 0 && pulse_time > 0){ - - // Build hit object - DCCALHit *hit = new DCCALHit; - - hit->row = digihit->row; - hit->column = digihit->column; - - hit->E = pulse_int_ped_subt; - hit->t = pulse_time_correct; - - // Get position of blocks on front face. (This should really come from - // hdgeant directly so the poisitions can be shifted in mcsmear.) - DVector2 pos = ccalGeom.positionOnFace(hit->row, hit->column); - hit->x = pos.X(); - hit->y = pos.Y(); - - if(pulse_amplitude > 0){ - hit->intOverPeak = (pulse_int - integratedPedestal)/pulse_amplitude; - } else - hit->intOverPeak = 0; - - hit->AddAssociatedObject(digihit); - _data.push_back(hit); - - } // Good hit - - } - - return NOERROR; + + return NOERROR; } //------------------ @@ -295,7 +291,7 @@ jerror_t DCCALHit_factory::evnt(JEventLoop *loop, uint64_t eventnumber) //------------------ jerror_t DCCALHit_factory::erun(void) { - return NOERROR; + return NOERROR; } //------------------ @@ -303,44 +299,41 @@ jerror_t DCCALHit_factory::erun(void) //------------------ jerror_t DCCALHit_factory::fini(void) { - return NOERROR; + return NOERROR; } -void DCCALHit_factory::LoadCCALConst(ccal_constants_t &table, const vector &ccal_const_ch, - const DCCALGeometry &ccalGeom){ - - char str[256]; - - // if (ccalGeom.numActiveBlocks() != CCAL_MAX_CHANNELS) { - // sprintf(str, "CCAL geometry is wrong size! channels=%d (should be %d)", - // ccalGeom.numActiveBlocks(), CCAL_MAX_CHANNELS); - // throw JException(str); - // } - - - for (int ch = 0; ch < static_cast(ccal_const_ch.size()); ch++) { - - // make sure that we don't try to load info for channels that don't exist - if (ch == ccalGeom.numActiveBlocks()) - break; - - int row = ccalGeom.row(ch); - int col = ccalGeom.column(ch); - - // results from DCCALGeometry should be self consistent, but add in some - // sanity checking just to be sure - - if (ccalGeom.isBlockActive(row,col) == false) { - sprintf(str, "DCCALHit: Loading CCAL constant for inactive channel! " - "row=%d, col=%d", row, col); - throw JException(str); - } - - table[row][col] = ccal_const_ch[ch]; - } - +void DCCALHit_factory::LoadCCALConst(ccal_constants_t &table, + const vector &ccal_const_ch, const DCCALGeometry &ccalGeom){ + + char str[256]; + + //if (ccalGeom.numActiveBlocks() != CCAL_MAX_CHANNELS) { + // sprintf(str, "CCAL geometry is wrong size! channels=%d (should be %d)", + // ccalGeom.numActiveBlocks(), CCAL_MAX_CHANNELS); + // throw JException(str); + //} + + + for (int ch = 0; ch < static_cast(ccal_const_ch.size()); ch++) { + + // make sure that we don't try to load info for channels that don't exist + if (ch == ccalGeom.numActiveBlocks()) + break; + + int row = ccalGeom.row(ch); + int col = ccalGeom.column(ch); + + // results from DCCALGeometry should be self consistent, but add in some + // sanity checking just to be sure + + if (ccalGeom.isBlockActive(row,col) == false) { + sprintf(str, "DCCALHit: Loading CCAL constant for inactive channel! " + "row=%d, col=%d", row, col); + throw JException(str); + } + + table[row][col] = ccal_const_ch[ch]; + } + } - - - diff --git a/src/libraries/CCAL/DCCALHit_factory.h b/src/libraries/CCAL/DCCALHit_factory.h index c303d85b68..eb3d6ef61b 100644 --- a/src/libraries/CCAL/DCCALHit_factory.h +++ b/src/libraries/CCAL/DCCALHit_factory.h @@ -21,34 +21,33 @@ typedef vector< vector > ccal_constants_t; class DCCALHit_factory:public jana::JFactory{ public: - DCCALHit_factory(); + DCCALHit_factory(); ~DCCALHit_factory(){}; - + ccal_constants_t gains; ccal_constants_t pedestals; ccal_constants_t time_offsets; ccal_constants_t adc_offsets; - + double adc_en_scale; double adc_time_scale; double base_time; - - private: - jerror_t init(void); ///< Called once at program start.2 - jerror_t brun(jana::JEventLoop *eventLoop, int32_t runnumber); ///< Called everytime a new run number is detected. - jerror_t evnt(jana::JEventLoop *eventLoop, uint64_t eventnumber); ///< Called every event. - jerror_t erun(void); ///< Called everytime run number changes, provided brun has been called. - jerror_t fini(void); ///< Called after last event of last event source has been processed. - + + private: + jerror_t init(void); + jerror_t brun(jana::JEventLoop *eventLoop, int32_t runnumber); + jerror_t evnt(jana::JEventLoop *eventLoop, uint64_t eventnumber); + jerror_t erun(void); + jerror_t fini(void); + void LoadCCALConst( ccal_constants_t &table, - const vector &ccal_const_ch, - const DCCALGeometry &ccalGeom); - - + const vector &ccal_const_ch, + const DCCALGeometry &ccalGeom); + unsigned int DB_PEDESTAL; unsigned int HIT_DEBUG; - + }; #endif // _DCCALHit_factory_ diff --git a/src/libraries/CCAL/DCCALRefDigiHit.h b/src/libraries/CCAL/DCCALRefDigiHit.h index aca62ac29c..24003df56a 100644 --- a/src/libraries/CCAL/DCCALRefDigiHit.h +++ b/src/libraries/CCAL/DCCALRefDigiHit.h @@ -14,7 +14,7 @@ class DCCALRefDigiHit:public jana::JObject{ public: JOBJECT_PUBLIC(DCCALRefDigiHit); - + int id; /// Reference counter number uint32_t pulse_integral; ///< identified pulse integral as returned by FPGA algorithm diff --git a/src/libraries/CCAL/DCCALShower.cc b/src/libraries/CCAL/DCCALShower.cc index 159cf6541c..ca2ec37b91 100644 --- a/src/libraries/CCAL/DCCALShower.cc +++ b/src/libraries/CCAL/DCCALShower.cc @@ -12,30 +12,28 @@ DCCALShower::DCCALShower():ExyztCovariance(5) { - - E = 0.; - Esum = 0.; - - x = 0.; - y = 0.; - x1 = 0.; - y1 = 0.; - z = 0.; - - chi2 = 0.; - sigma_E = 0.; - Emax = 0.; - time = 0.; - sigma_t = 0.; - - dime = 0; - idmax = 0; - id = 0; - type = 0; - + E = 0.; + Esum = 0.; + + x = 0.; + y = 0.; + x1 = 0.; + y1 = 0.; + z = 0.; + + chi2 = 0.; + sigma_E = 0.; + Emax = 0.; + time = 0.; + sigma_t = 0.; + + dime = 0; + idmax = 0; + id = 0; + type = 0; } DCCALShower::~DCCALShower() { - + } diff --git a/src/libraries/CCAL/DCCALShower.h b/src/libraries/CCAL/DCCALShower.h index 48b1e94df6..c57bdc4e5b 100644 --- a/src/libraries/CCAL/DCCALShower.h +++ b/src/libraries/CCAL/DCCALShower.h @@ -26,73 +26,71 @@ using namespace jana; #define CCAL_USER_HITS_MAX 1000 - class DCCALShower : public JObject { - + public: - JOBJECT_PUBLIC(DCCALShower); - - DCCALShower(); - ~DCCALShower(); - - /*----------------------------------------// - - Description of DCCALShower variables: - - - E: Energy of shower as reconstructed from island algorithm - - Esum: Energy of shower calculated as simple sum of block energies - - - x , y : Shower position reported from island algorithm - - x1, y1: Shower position calculated using logarithmic weights - - z: Z-Position of CCAL Face - - - dime: Number of hits contributing to shower - - idmax: The channel number of cell with maximum energy deposition - - id: Only non-zero for showers that share a single peak - - - chi2: The chi2-value reported from island - - sigma_E: Energy resolution (needs work) - - Emax: Energy of maximum cell - - time: Energy-weighted average of shower's constituent times - (with time-walk correction) - - - ClusterType (enum): - - SinglePeak - shower is in a single-peak cluster - MultiPeak - shower is in a multi-peak cluster - - - PeakType (enum) : - - OneGamma - The peak this shower belongs to has just one gamma reconstructed - TwoGammas - The peak this shower belongs to has two gammas reconstructed - - - - //----------------------------------------*/ - - double E; - double Esum; - - double x; - double y; - double x1; - double y1; - double z; - - double chi2; - double sigma_E; - double Emax; - double time; - double sigma_t; - - int dime; - int idmax; - int id; - int type; + JOBJECT_PUBLIC(DCCALShower); + + DCCALShower(); + ~DCCALShower(); + + /*---------------------------------------- + + Description of DCCALShower variables: + + - E: Energy of shower as reconstructed from island algorithm + - Esum: Energy of shower calculated as simple sum of block energies + + - x , y : Shower position reported from island algorithm + - x1, y1: Shower position calculated using logarithmic weights + - z: Z-Position of CCAL Face + + - dime: Number of hits contributing to shower + - idmax: The channel number of cell with maximum energy deposition + - id: Only non-zero for showers that share a single peak + + - chi2: The chi2-value reported from island + - sigma_E: Energy resolution (needs work) + - Emax: Energy of maximum cell + - time: Energy-weighted average of shower's constituent times + (with time-walk correction) + + - ClusterType (enum): + + SinglePeak - shower is in a single-peak cluster + MultiPeak - shower is in a multi-peak cluster + + - PeakType (enum) : + + OneGamma - The peak this shower belongs to has just one gamma reconstructed + TwoGammas - The peak this shower belongs to has two gammas reconstructed + + ----------------------------------------*/ + + double E; + double Esum; + + double x; + double y; + double x1; + double y1; + double z; + + double chi2; + double sigma_E; + double Emax; + double time; + double sigma_t; + + int dime; + int idmax; + int id; + int type; ClusterType_t ClusterType; PeakType_t PeakType; - + + vectorhitsInCluster; TMatrixFSym ExyztCovariance; @@ -102,80 +100,77 @@ class DCCALShower : public JObject { float zErr() const { return sqrt(ExyztCovariance(3,3)); } float tErr() const { return sqrt(ExyztCovariance(4,4)); } float XYcorr() const { - if (xErr()>0 && yErr()>0) return ExyztCovariance(1,2)/xErr()/yErr(); - else return 0; + if (xErr()>0 && yErr()>0) return ExyztCovariance(1,2)/xErr()/yErr(); + else return 0; } float XZcorr() const { - if (xErr()>0 && zErr()>0) return ExyztCovariance(1,3)/xErr()/zErr(); - else return 0; + if (xErr()>0 && zErr()>0) return ExyztCovariance(1,3)/xErr()/zErr(); + else return 0; } float YZcorr() const { - if (yErr()>0 && zErr()>0) return ExyztCovariance(2,3)/yErr()/zErr(); - else return 0; + if (yErr()>0 && zErr()>0) return ExyztCovariance(2,3)/yErr()/zErr(); + else return 0; } float EXcorr() const { - if (EErr()>0 && xErr()>0) return ExyztCovariance(0,1)/EErr()/xErr(); - else return 0; + if (EErr()>0 && xErr()>0) return ExyztCovariance(0,1)/EErr()/xErr(); + else return 0; } float EYcorr() const { - if (EErr()>0 && yErr()>0) return ExyztCovariance(0,2)/EErr()/yErr(); - else return 0; + if (EErr()>0 && yErr()>0) return ExyztCovariance(0,2)/EErr()/yErr(); + else return 0; } float EZcorr() const { - if (EErr()>0 && zErr()>0) return ExyztCovariance(0,3)/EErr()/zErr(); - else return 0; + if (EErr()>0 && zErr()>0) return ExyztCovariance(0,3)/EErr()/zErr(); + else return 0; } float XTcorr() const { - if (xErr()>0 && tErr()>0) return ExyztCovariance(1,4)/xErr()/tErr(); - else return 0; + if (xErr()>0 && tErr()>0) return ExyztCovariance(1,4)/xErr()/tErr(); + else return 0; } float YTcorr() const { - if (yErr()>0 && tErr()>0) return ExyztCovariance(2,4)/yErr()/tErr(); - else return 0; + if (yErr()>0 && tErr()>0) return ExyztCovariance(2,4)/yErr()/tErr(); + else return 0; } float ZTcorr() const { - if (zErr()>0 && tErr()>0) return ExyztCovariance(3,4)/zErr()/tErr(); - else return 0; + if (zErr()>0 && tErr()>0) return ExyztCovariance(3,4)/zErr()/tErr(); + else return 0; } float ETcorr() const { - if (EErr()>0 && tErr()>0) return ExyztCovariance(0,4)/EErr()/tErr(); - else return 0; + if (EErr()>0 && tErr()>0) return ExyztCovariance(0,4)/EErr()/tErr(); + else return 0; } - - void toStrings(vector > &items) const { - AddString(items, "E(GeV)", "%2.3f", E); - AddString(items, "Emax(GeV)", "%2.3f", Emax); - AddString(items, "x(cm)", "%3.3f", x); - AddString(items, "y(cm)", "%3.3f", y); - AddString(items, "x1(cm)", "%3.3f", x1); - AddString(items, "y1(cm)", "%3.3f", y1); - AddString(items, "z(cm)", "%3.3f", z); - AddString(items, "chi2", "%3.3f", chi2); - AddString(items, "dime", "%3d", dime); - AddString(items, "idmax", "%3d", idmax); - AddString(items, "id", "%3d", id); - AddString(items, "sigma_E", "%3.1f", sigma_E); - AddString(items, "t(ns)", "%2.3f", time); - AddString(items, "ClusterType", "%d", (int)ClusterType); - AddString(items, "PeakType", "%d", (int)PeakType); - - AddString(items, "EXcorr", "%5.3f", EXcorr()); - AddString(items, "EYcorr", "%5.3f", EYcorr()); - AddString(items, "EZcorr", "%5.3f", EZcorr()); - AddString(items, "ETcorr", "%5.3f", ETcorr()); - AddString(items, "XYcorr", "%5.3f", XYcorr()); - AddString(items, "XZcorr", "%5.3f", XZcorr()); - AddString(items, "XTcorr", "%5.3f", XTcorr()); - AddString(items, "YZcorr", "%5.3f", YZcorr()); - AddString(items, "YTcorr", "%5.3f", YTcorr()); - AddString(items, "ZTcorr", "%5.3f", ZTcorr()); - } - - private: - - + + void toStrings(vector > &items) const { + AddString(items, "E(GeV)", "%2.3f", E); + AddString(items, "Emax(GeV)", "%2.3f", Emax); + AddString(items, "x(cm)", "%3.3f", x); + AddString(items, "y(cm)", "%3.3f", y); + AddString(items, "x1(cm)", "%3.3f", x1); + AddString(items, "y1(cm)", "%3.3f", y1); + AddString(items, "z(cm)", "%3.3f", z); + AddString(items, "chi2", "%3.3f", chi2); + AddString(items, "dime", "%3d", dime); + AddString(items, "idmax", "%3d", idmax); + AddString(items, "id", "%3d", id); + AddString(items, "sigma_E", "%3.1f", sigma_E); + AddString(items, "t(ns)", "%2.3f", time); + AddString(items, "ClusterType", "%d", (int)ClusterType); + AddString(items, "PeakType", "%d", (int)PeakType); + + AddString(items, "EXcorr", "%5.3f", EXcorr()); + AddString(items, "EYcorr", "%5.3f", EYcorr()); + AddString(items, "EZcorr", "%5.3f", EZcorr()); + AddString(items, "ETcorr", "%5.3f", ETcorr()); + AddString(items, "XYcorr", "%5.3f", XYcorr()); + AddString(items, "XZcorr", "%5.3f", XZcorr()); + AddString(items, "XTcorr", "%5.3f", XTcorr()); + AddString(items, "YZcorr", "%5.3f", YZcorr()); + AddString(items, "YTcorr", "%5.3f", YTcorr()); + AddString(items, "ZTcorr", "%5.3f", ZTcorr()); + } + + private: + }; - #endif // _DCCALShower_ - diff --git a/src/libraries/CCAL/DCCALShower_factory.cc b/src/libraries/CCAL/DCCALShower_factory.cc index d283590409..4d81e75cb3 100644 --- a/src/libraries/CCAL/DCCALShower_factory.cc +++ b/src/libraries/CCAL/DCCALShower_factory.cc @@ -8,11 +8,9 @@ #include "CCAL/DCCALShower_factory.h" - static mutex CCAL_MUTEX; //static bool CCAL_PROFILE_LOADED = false; - //========================================================== // // Constructor @@ -23,48 +21,52 @@ DCCALShower_factory::DCCALShower_factory() { // Set defaults: - MIN_CLUSTER_BLOCK_COUNT = 2; + MIN_CLUSTER_BLOCK_COUNT = 2; MAX_HITS_FOR_CLUSTERING = 80; - MIN_CLUSTER_SEED_ENERGY = 0.035; /* [GeV] */ + MIN_CLUSTER_SEED_ENERGY = 0.035; /* [GeV] */ MIN_CLUSTER_ENERGY = 0.05; /* [GeV] */ MAX_CLUSTER_ENERGY = 15.9; /* [GeV] */ TIME_CUT = 15.0; /* [ns] */ SHOWER_DEBUG = 0; DO_NONLINEAR_CORRECTION = 1; + DO_TIMEWALK_CORRECTION = 1; CCAL_RADIATION_LENGTH = 0.86; CCAL_CRITICAL_ENERGY = 1.1e-3; LOG_POS_CONST = 4.2; + CCAL_C_EFFECTIVE = 13.6; gPARMS->SetDefaultParameter( "CCAL:SHOWER_DEBUG", SHOWER_DEBUG ); gPARMS->SetDefaultParameter( "CCAL:MIN_CLUSTER_BLOCK_COUNT", MIN_CLUSTER_BLOCK_COUNT, - "minimum number of blocks to form a cluster" ); + "minimum number of blocks to form a cluster" ); gPARMS->SetDefaultParameter( "CCAL:MIN_CLUSTER_SEED_ENERGY", MIN_CLUSTER_SEED_ENERGY, - "minimum energy for a block to be considered as a seed for a cluster" ); + "minimum energy for a block to be considered as a seed for a cluster" ); gPARMS->SetDefaultParameter( "CCAL:MIN_CLUSTER_ENERGY", MIN_CLUSTER_ENERGY, - "minimum allowed cluster energy" ); + "minimum allowed cluster energy" ); gPARMS->SetDefaultParameter( "CCAL:MAX_CLUSTER_ENERGY", MAX_CLUSTER_ENERGY, - "maximum allowed cluster energy" ); + "maximum allowed cluster energy" ); gPARMS->SetDefaultParameter( "CCAL:MAX_HITS_FOR_CLUSTERING", MAX_HITS_FOR_CLUSTERING, - "maximum hits allowed to call clustering algorithm" ); + "maximum hits allowed to call clustering algorithm" ); gPARMS->SetDefaultParameter( "CCAL:TIME_CUT", TIME_CUT, - "time cut for associating CCAL hits together into a cluster" ); + "time cut for associating CCAL hits together into a cluster" ); gPARMS->SetDefaultParameter( "CCAL:DO_NONLINEAR_CORRECTION", DO_NONLINEAR_CORRECTION, - "set this to zero when no nonlinear correction is desired" ); + "set this to zero when no nonlinear correction is desired" ); + gPARMS->SetDefaultParameter( "CCAL:DO_TIMEWALK_CORRECTION", DO_TIMEWALK_CORRECTION, + "set this to zero when no timewalk correction is desired" ); gPARMS->SetDefaultParameter( "CCAL:CCAL_RADIATION_LENGTH", CCAL_RADIATION_LENGTH ); gPARMS->SetDefaultParameter( "CCAL:CCAL_CRITICAL_ENERGY", CCAL_CRITICAL_ENERGY ); gPARMS->SetDefaultParameter( "CCAL:LOG_POS_CONST", LOG_POS_CONST ); - + gPARMS->SetDefaultParameter( "CCAL:CCAL_C_EFFECTIVE", CCAL_C_EFFECTIVE ); + VERBOSE = 0; ///< >0 once off info ; >2 event by event ; >3 everything - gPARMS->SetDefaultParameter("DFCALShower:VERBOSE", VERBOSE, "Verbosity level for DFCALShower objects and factories"); + gPARMS->SetDefaultParameter("DFCALShower:VERBOSE", VERBOSE, + "Verbosity level for DFCALShower objects and factories"); } - - //========================================================== // // brun @@ -73,30 +75,29 @@ DCCALShower_factory::DCCALShower_factory() jerror_t DCCALShower_factory::brun(JEventLoop *locEventLoop, int32_t runnumber) { - // Only print messages for one thread whenever run number change - static pthread_mutex_t print_mutex = PTHREAD_MUTEX_INITIALIZER; - static set runs_announced; - pthread_mutex_lock(&print_mutex); - bool print_messages = false; - if(runs_announced.find(runnumber) == runs_announced.end()){ - print_messages = true; - runs_announced.insert(runnumber); - } - pthread_mutex_unlock(&print_mutex); - - + // Only print messages for one thread whenever run number change + static pthread_mutex_t print_mutex = PTHREAD_MUTEX_INITIALIZER; + static set runs_announced; + pthread_mutex_lock(&print_mutex); + bool print_messages = false; + if(runs_announced.find(runnumber) == runs_announced.end()){ + print_messages = true; + runs_announced.insert(runnumber); + } + pthread_mutex_unlock(&print_mutex); + DApplication *dapp = dynamic_cast(eventLoop->GetJApplication()); - const DGeometry *geom = dapp->GetDGeometry(runnumber); + const DGeometry *geom = dapp->GetDGeometry(runnumber); - if (geom) { - geom->GetTargetZ(m_zTarget); - geom->GetCCALPosition(m_CCALdX,m_CCALdY,m_CCALfront); - } - else{ - jerr << "No geometry accessible." << endl; - return RESOURCE_UNAVAILABLE; - } + if(geom) { + geom->GetCCALPosition(m_CCALdX,m_CCALdY,m_CCALfront); + } + else{ + jerr << "No geometry accessible." << endl; + return RESOURCE_UNAVAILABLE; + } + JCalibration *jcalib = dapp->GetJCalibration(runnumber); //------------------------------------------------------// //----------- Read in shower profile data -----------// @@ -109,40 +110,38 @@ jerror_t DCCALShower_factory::brun(JEventLoop *locEventLoop, int32_t runnumber) // follow similar procedure as other resources (DMagneticFieldMapFineMesh) - map< string,string > profile_file_name; - JCalibration *jcalib = dapp->GetJCalibration(runnumber); + map profile_file_name; - if( jcalib->GetCalib("/CCAL/profile_data/profile_data_map", profile_file_name) ) + if(jcalib->GetCalib("/CCAL/profile_data/profile_data_map", profile_file_name)) { - jout << "Can't find requested /CCAL/profile_data/profile_data_map in CCDB for this run!" - << endl; - - } else if( profile_file_name.find("map_name") != profile_file_name.end() - && profile_file_name["map_name"] != "None" ) + jout << "Can't find requested /CCAL/profile_data/profile_data_map in CCDB for this run!" + << endl; + } else if(profile_file_name.find("map_name") != profile_file_name.end() + && profile_file_name["map_name"] != "None") { - JResourceManager *jresman = dapp->GetJResourceManager(runnumber); - ccal_profile_file = jresman->GetResource(profile_file_name["map_name"]); + JResourceManager *jresman = dapp->GetJResourceManager(runnumber); + ccal_profile_file = jresman->GetResource(profile_file_name["map_name"]); } if(print_messages) jout<<"Reading CCAL profile data from "<> id1 >> id2 >> fcell_hyc >> fd2c; - + acell[id1][id2] = fcell_hyc; acell[id2][id1] = fcell_hyc; ad2c[id1][id2] = fd2c; @@ -153,107 +152,96 @@ jerror_t DCCALShower_factory::brun(JEventLoop *locEventLoop, int32_t runnumber) lck.unlock(); - - - //------------------------------------------------------// //---------- Initialize channel status array ----------// for(int icol = 0; icol < MCOL; ++icol) { - for(int irow = 0; irow < MROW; ++irow) { - if(icol>=5 && icol<=6 && irow>=5 && irow<=6) { stat_ch[irow][icol] = -1; } - else { stat_ch[irow][icol] = 0; } - } + for(int irow = 0; irow < MROW; ++irow) { + if(icol>=5 && icol<=6 && irow>=5 && irow<=6) { stat_ch[irow][icol] = -1; } + else { stat_ch[irow][icol] = 0; } + } } - - - //------------------------------------------------------// //---------- Read shower timewalk parameters ----------// - vector< vector > timewalk_params; - if( eventLoop->GetCalib("/CCAL/shower_timewalk_correction",timewalk_params) ) - jout << "Error loading /CCAL/shower_timewalk_correction !" << endl; + vector> timewalk_params; + if(eventLoop->GetCalib("/CCAL/shower_timewalk_correction",timewalk_params)) + jout << "Error loading /CCAL/shower_timewalk_correction !" << endl; else { - if( (int)timewalk_params.size() != 2 ) { - cout << "DCCALShower_factory: Wrong number of entries to timewalk correction table (should be 144)." << endl; - for( int ii = 0; ii < 2; ++ii ) { - timewalk_p0.push_back(0.0); - timewalk_p1.push_back(0.0); - timewalk_p2.push_back(0.0); - timewalk_p3.push_back(0.0); - } - } else { - for( vector< vector >::const_iterator iter = timewalk_params.begin(); - iter != timewalk_params.end(); ++iter ) { - if( iter->size() != 4 ) { - cout << "DCCALShower_factory: Wrong number of values in timewalk correction table (should be 4)" << endl; - continue; - } - - timewalk_p0.push_back( (*iter)[0] ); - timewalk_p1.push_back( (*iter)[1] ); - timewalk_p2.push_back( (*iter)[2] ); - timewalk_p3.push_back( (*iter)[3] ); - - } - } + if((int)timewalk_params.size() != 2) { + cout << "DCCALShower_factory: " + "Wrong number of entries to timewalk correction table (should be 144)."<< endl; + for(int ii = 0; ii < 2; ++ii) { + timewalk_p0.push_back(0.0); + timewalk_p1.push_back(0.0); + timewalk_p2.push_back(0.0); + timewalk_p3.push_back(0.0); + } + } else { + for(vector>::const_iterator iter = timewalk_params.begin(); + iter != timewalk_params.end(); ++iter) { + if(iter->size() != 4) { + cout << "DCCALShower_factory: " + "Wrong number of values in timewalk correction table (should be 4)" + << endl; + continue; + } + timewalk_p0.push_back((*iter)[0]); + timewalk_p1.push_back((*iter)[1]); + timewalk_p2.push_back((*iter)[2]); + timewalk_p3.push_back((*iter)[3]); + } + } } - - - //------------------------------------------------------// //--------- Read in non-linearity parameters ----------// - vector< vector > nonlin_params; - if( eventLoop->GetCalib("/CCAL/nonlinear_energy_correction",nonlin_params) ) - jout << "Error loading /CCAL/nonlinear_energy_correction !" << endl; + vector> nonlin_params; + if(eventLoop->GetCalib("/CCAL/nonlinear_energy_correction",nonlin_params)) + jout << "Error loading /CCAL/nonlinear_energy_correction !" << endl; else { - if( (int)nonlin_params.size() != CCAL_CHANS ) { - cout << "DCCALShower_factory: Wrong number of entries to nonlinear energy correction table (should be 144)." << endl; - for( int ii = 0; ii < CCAL_CHANS; ++ii ) { - Nonlin_p0.push_back(0.0); - Nonlin_p1.push_back(0.0); - Nonlin_p2.push_back(0.0); - Nonlin_p3.push_back(0.0); - } - } else { - for( vector< vector >::const_iterator iter = nonlin_params.begin(); - iter != nonlin_params.end(); ++iter ) { - if( iter->size() != 4 ) { - cout << "DCCALShower_factory: Wrong number of values in nonlinear energy correction table (should be 4)" << endl; - continue; - } - - Nonlin_p0.push_back( (*iter)[0] ); - Nonlin_p1.push_back( (*iter)[1] ); - Nonlin_p2.push_back( (*iter)[2] ); - Nonlin_p3.push_back( (*iter)[3] ); - - } - } + if((int)nonlin_params.size() != CCAL_CHANS) { + cout << "DCCALShower_factory: " + "Wrong number of entries to nonlinear energy correction table (should be 144)." + << endl; + for( int ii = 0; ii < CCAL_CHANS; ++ii ) { + Nonlin_p0.push_back(0.0); + Nonlin_p1.push_back(0.0); + Nonlin_p2.push_back(0.0); + Nonlin_p3.push_back(0.0); + } + } else { + for(vector>::const_iterator iter = nonlin_params.begin(); + iter != nonlin_params.end(); ++iter) { + if(iter->size() != 4) { + cout << "DCCALShower_factory: " + "Wrong number of values in nonlinear energy correction table (should be 4)" + << endl; + continue; + } + Nonlin_p0.push_back( (*iter)[0] ); + Nonlin_p1.push_back( (*iter)[1] ); + Nonlin_p2.push_back( (*iter)[2] ); + Nonlin_p3.push_back( (*iter)[3] ); + } + } } - if( SHOWER_DEBUG ) { - cout << "\n\nNONLIN_P0 NONLIN_P1 NONLIN_P2 NONLIN_P3" << endl; - for(int ii = 0; ii < (int)Nonlin_p0.size(); ii++) { - cout << Nonlin_p0[ii] << " " << Nonlin_p1[ii] << " " << Nonlin_p2[ii] << " " << - Nonlin_p3[ii] << endl; - } - cout << "\n\n"; + if(SHOWER_DEBUG) { + cout << "\n\nNONLIN_P0 NONLIN_P1 NONLIN_P2 NONLIN_P3" << endl; + for(int ii = 0; ii < (int)Nonlin_p0.size(); ii++) { + cout << Nonlin_p0[ii] << " " << Nonlin_p1[ii] << " " << Nonlin_p2[ii] << " " << + Nonlin_p3[ii] << endl; + } + cout << "\n\n"; } - - - return NOERROR; } - - //========================================================== // // evnt @@ -262,183 +250,159 @@ jerror_t DCCALShower_factory::brun(JEventLoop *locEventLoop, int32_t runnumber) jerror_t DCCALShower_factory::evnt(JEventLoop *locEventLoop, uint64_t eventnumber) { - - vector< const DCCALGeometry* > ccalGeomVect; - locEventLoop->Get( ccalGeomVect ); - if (ccalGeomVect.size() < 1) - return OBJECT_NOT_AVAILABLE; - const DCCALGeometry& ccalGeom = *(ccalGeomVect[0]); - - - + locEventLoop->Get(ccalGeomVect); + if(ccalGeomVect.size() < 1) + return OBJECT_NOT_AVAILABLE; + const DCCALGeometry& ccalGeom = *(ccalGeomVect[0]); //------- Get the CCALHits and organize hit pattern -------// - vector< const DCCALHit* > ccalhits; - locEventLoop->Get( ccalhits ); + locEventLoop->Get(ccalhits); - int n_hits = static_cast( ccalhits.size() ); - if( n_hits < 1 || n_hits > MAX_HITS_FOR_CLUSTERING ) return NOERROR; + int n_hits = static_cast(ccalhits.size()); + if( n_hits < 1 || n_hits > MAX_HITS_FOR_CLUSTERING) return NOERROR; + vector> hitPatterns; + getHitPatterns(ccalhits, hitPatterns); - vector< vector< const DCCALHit* > > hitPatterns; - getHitPatterns( ccalhits, hitPatterns ); - - int n_patterns = static_cast( hitPatterns.size() ); + int n_patterns = static_cast(hitPatterns.size()); if( n_patterns < 1 ) return NOERROR; - vector< ccalcluster_t > ccalClusters; // will hold all clusters - vector< cluster_t > clusterStorage; // will hold the constituents of every cluster - - - + vector ccalClusters; // will hold all clusters + vector clusterStorage; // will hold the constituents of every cluster //------- Call island clusterizer on each pattern -------// - - for( int ipat = 0; ipat < n_patterns; ipat++ ) + for(int ipat = 0; ipat < n_patterns; ipat++) { - - - /*----- prepare data in dimensionless format -----*/ - - vector< const DCCALHit* > rawHitPattern = hitPatterns[ipat]; - vector< const DCCALHit* > locHitPattern; - cleanHitPattern( rawHitPattern, locHitPattern ); - - int n_hits = static_cast( locHitPattern.size() ); - - vector< int > ia; - vector< int > id; - - for( int ih = 0; ih < n_hits; ih++ ) { - const DCCALHit *ccalhit = locHitPattern[ih]; - int row = 12 - ccalhit->row; - int col = 12 - ccalhit->column; - int ie = static_cast( ccalhit->E*10. + 0.5 ); - if( ie > 0 ) { - int address = 100*col + row; - ia.push_back( address ); - id.push_back( ie ); - } - } - - - /*------------- call to island -------------*/ - - vector< gamma_t > gammas; gammas.clear();// Output of main_island (holds reconstructed photons) - main_island( ia, id, gammas ); - - - /*------------ post-island processing ------------*/ - - int init_clusters = static_cast( gammas.size() ); - if( !init_clusters ) continue; - - processShowers( gammas, ccalGeom, locHitPattern, eventnumber, - ccalClusters, clusterStorage ); - - + /*----- prepare data in dimensionless format -----*/ + + vector rawHitPattern = hitPatterns[ipat]; + vector locHitPattern; + cleanHitPattern(rawHitPattern, locHitPattern); + + int n_hits = static_cast(locHitPattern.size()); + + vector ia; + vector id; + + for(int ih = 0; ih < n_hits; ih++) { + const DCCALHit *ccalhit = locHitPattern[ih]; + int row = 12 - ccalhit->row; + int col = 12 - ccalhit->column; + int ie = static_cast(ccalhit->E*10. + 0.5); + if( ie > 0 ) { + int address = 100*col + row; + ia.push_back(address); + id.push_back(ie); + } + } + + /*------------- call to island -------------*/ + + vector gammas; gammas.clear(); + main_island(ia, id, gammas); + + /*------------ post-island processing ------------*/ + + int init_clusters = static_cast(gammas.size()); + if(!init_clusters) continue; + + processShowers(gammas, ccalGeom, locHitPattern, eventnumber, + ccalClusters, clusterStorage); + } // end looping over hit patterns - - - //-------------- Fill DCCALShower Object --------------// - int n_clusters = static_cast( ccalClusters.size() ); - - for( int k = 0; k < n_clusters; k++ ) { - - DCCALShower *shower = new DCCALShower; - - shower->E = ccalClusters[k].E; - shower->Esum = ccalClusters[k].Esum; - - shower->x = ccalClusters[k].x+m_CCALdX; - shower->y = ccalClusters[k].y+m_CCALdY; - shower->x1 = ccalClusters[k].x1+m_CCALdX; - shower->y1 = ccalClusters[k].y1+m_CCALdY; - shower->z = m_CCALfront; - - shower->chi2 = ccalClusters[k].chi2; - shower->sigma_E = ccalClusters[k].sigma_E; - shower->Emax = ccalClusters[k].emax; - shower->time = ccalClusters[k].time; - - shower->dime = ccalClusters[k].nhits; - shower->idmax = ccalClusters[k].idmax; - shower->id = ccalClusters[k].id; - - shower->type = ccalClusters[k].type; - - int showTypeVal = (ccalClusters[k].type)/10; - shower->ClusterType = static_cast( showTypeVal/2 ); - shower->PeakType = static_cast( showTypeVal%2 ); - //shower->ExyztCovariance(i, j) - float xerr = 0.1016;// / sqrt(ccalClusters[k].E) + 0.2219; // HARD CODED VALUE!!!! - float yerr = 0.1016;// / sqrt(ccalClusters[k].E) + 0.2219; // HARD CODED VALUE!!!! - float zerr = 2.5; // HARD CODED VALUE!!!! - float terr = 0.2; // HARD CODED VALUE!!!! - float eerr = 0.5;//pow(ccalClusters[k].E, 2) * (0.01586 / ccalClusters[k].E + 0.0002342 / pow(ccalClusters[k].E, 2) + 1.696e-6); // HARD CODED VALUE!!!! - //copy xyz errors into covariance matrix - shower->ExyztCovariance.ResizeTo(5,5); - for (int col = 0; col < 5; col ++) { - for (int row = 0; row < 5; row ++) { - if (col != row) shower->ExyztCovariance[col][row] = 0; - } - } - shower->ExyztCovariance[0][0] = pow(xerr, 2); - shower->ExyztCovariance[1][1] = pow(yerr, 2); - shower->ExyztCovariance[2][2] = pow(zerr, 2); - shower->ExyztCovariance[3][3] = pow(terr, 2); - shower->ExyztCovariance[4][4] = pow(eerr, 2); - - if (VERBOSE>2) {printf("(E,x,y,z,t) "); shower->ExyztCovariance.Print(); } - - for( int icell = 0; icell < ccalClusters[k].nhits; icell++ ) { - - int hitID = clusterStorage[k].id[icell]; - float hitX = ccalGeom.positionOnFace( hitID ).X(); - float hitY = ccalGeom.positionOnFace( hitID ).Y(); - int hitROW = ccalGeom.row( hitY ); - int hitCOL = ccalGeom.column( hitX ); - - DCCALHit *clusHit = new DCCALHit; - clusHit->row = hitROW; - clusHit->column = hitCOL; - clusHit->x = hitX; - clusHit->y = hitY; - clusHit->E = static_cast( 1000.*clusterStorage[k].E[icell] ); - clusHit->t = static_cast( clusterStorage[k].t[icell] ); - - shower->AddAssociatedObject( clusHit ); - - } - - _data.push_back( shower ); + int n_clusters = static_cast(ccalClusters.size()); + + for(int k = 0; k < n_clusters; k++) { + + DCCALShower *shower = new DCCALShower; + + shower->E = ccalClusters[k].E; + shower->Esum = ccalClusters[k].Esum; + + shower->x = ccalClusters[k].x+m_CCALdX; + shower->y = ccalClusters[k].y+m_CCALdY; + shower->x1 = ccalClusters[k].x1+m_CCALdX; + shower->y1 = ccalClusters[k].y1+m_CCALdY; + shower->z = ccalClusters[k].z; + + shower->chi2 = ccalClusters[k].chi2; + shower->sigma_E = ccalClusters[k].sigma_E; + shower->Emax = ccalClusters[k].emax; + shower->time = ccalClusters[k].time; + + shower->dime = ccalClusters[k].nhits; + shower->idmax = ccalClusters[k].idmax; + shower->id = ccalClusters[k].id; + shower->type = ccalClusters[k].type; + + int showTypeVal = (ccalClusters[k].type)/10; + shower->ClusterType = static_cast(showTypeVal/2); + shower->PeakType = static_cast(showTypeVal%2); + + //shower->ExyztCovariance(i, j) + float xerr = 0.1016;// / sqrt(ccalClusters[k].E) + 0.2219; // HARD CODED VALUE!!!! + float yerr = 0.1016;// / sqrt(ccalClusters[k].E) + 0.2219; // HARD CODED VALUE!!!! + float zerr = 2.5; // HARD CODED VALUE!!!! + float terr = 0.2; // HARD CODED VALUE!!!! + float eerr = 0.5;//pow(ccalClusters[k].E, 2) * (0.01586 / ccalClusters[k].E + 0.0002342 / pow(ccalClusters[k].E, 2) + 1.696e-6); // HARD CODED VALUE!!!! + + //copy xyz errors into covariance matrix + shower->ExyztCovariance.ResizeTo(5,5); + for (int col = 0; col < 5; col ++) { + for (int row = 0; row < 5; row ++) { + if (col != row) shower->ExyztCovariance[col][row] = 0; + } + } + shower->ExyztCovariance[0][0] = pow(xerr, 2); + shower->ExyztCovariance[1][1] = pow(yerr, 2); + shower->ExyztCovariance[2][2] = pow(zerr, 2); + shower->ExyztCovariance[3][3] = pow(terr, 2); + shower->ExyztCovariance[4][4] = pow(eerr, 2); + + if (VERBOSE>2) {printf("(E,x,y,z,t) "); shower->ExyztCovariance.Print(); } + + shower->hitsInCluster.clear(); + for( int icell = 0; icell < ccalClusters[k].nhits; icell++ ) { + + int hitID = clusterStorage[k].id[icell]; + float hitX = ccalGeom.positionOnFace( hitID ).X(); + float hitY = ccalGeom.positionOnFace( hitID ).Y(); + int hitROW = ccalGeom.row( hitY ); + int hitCOL = ccalGeom.column( hitX ); + + DCCALHit clusHit; + clusHit.row = hitROW; + clusHit.column = hitCOL; + clusHit.x = hitX; + clusHit.y = hitY; + clusHit.E = static_cast( 1000.*clusterStorage[k].E[icell] ); + clusHit.t = static_cast( clusterStorage[k].t[icell] ); + + shower->hitsInCluster.push_back( clusHit ); + } + _data.push_back( shower ); } - - - return NOERROR; + return NOERROR; } - - //========================================================== // // getHitPatterns // //========================================================== -void DCCALShower_factory::getHitPatterns( vector< const DCCALHit* > hitarray, - vector< vector< const DCCALHit* > > &hitPatterns ) +void DCCALShower_factory::getHitPatterns(vector hitarray, + vector> &hitPatterns) { - /*------------------------------ Method for sorting hit patterns: @@ -447,516 +411,448 @@ void DCCALShower_factory::getHitPatterns( vector< const DCCALHit* > hitarray, 2. Sort hit vector in order of increasing time-difference from this hit 3. Push all hits within 15 ns of max hit to a new vector (first few elements of sorted vec) 4. Erase the elements that were moved from the previous vector - - maybe steps 3&4 can be done simultaneously? + - maybe steps 3&4 can be done simultaneously? 5. Push the new vector back to the hitPatterns vector 6. Repeat steps 1-5 until no hits remain in original hitarray --------------------------------*/ - - int n_hits = static_cast( hitarray.size() ); + int n_hits = static_cast(hitarray.size()); - if( n_hits < 1 ) return; - if( n_hits < 2 ) { - vector< const DCCALHit* > hitVec; - hitVec.push_back( hitarray[0] ); - hitPatterns.push_back( hitVec ); - return; + if(n_hits < 1) return; + if(n_hits < 2) { + vector hitVec; + hitVec.push_back(hitarray[0]); + hitPatterns.push_back(hitVec); + return; } + vector clonedHitArray = hitarray; - vector< const DCCALHit* > clonedHitArray = hitarray; - - while( clonedHitArray.size() ) + while(clonedHitArray.size()) { - - vector< const DCCALHit* > locHitVec; - - float maxE = -1.; - float maxT = 1.e6; - - for( unsigned int ih = 0; ih < clonedHitArray.size(); ih++ ) { - float trialE = clonedHitArray[ih]->E; - if( trialE > maxE ) { maxE = trialE; maxT = clonedHitArray[ih]->t; } - } - - if( maxE < 0. ) break; - - - sortByTime( clonedHitArray, maxT ); - - - n_hits = static_cast( clonedHitArray.size() ); - - int n_good_hits = 0; - for( int ih = 0; ih < n_hits; ih++ ) { - - const DCCALHit *locHit = clonedHitArray[ih]; - float timeDiff = fabs( locHit->t - maxT ); - - if( timeDiff < TIME_CUT ) { - locHitVec.push_back( locHit ); - n_good_hits++; - } else { break; } - - } - - if( locHitVec.size() ) hitPatterns.push_back( locHitVec ); - - clonedHitArray.erase( clonedHitArray.begin(), clonedHitArray.begin() + n_good_hits ); - + vector locHitVec; + + float maxE = -1.; + float maxT = 1.e6; + + for(unsigned int ih = 0; ih < clonedHitArray.size(); ih++) { + float trialE = clonedHitArray[ih]->E; + if(trialE > maxE) { maxE = trialE; maxT = clonedHitArray[ih]->t; } + } + + if(maxE < 0.) break; + + sortByTime(clonedHitArray, maxT); + + n_hits = static_cast(clonedHitArray.size()); + + int n_good_hits = 0; + for(int ih = 0; ih < n_hits; ih++) { + + const DCCALHit *locHit = clonedHitArray[ih]; + float timeDiff = fabs( locHit->t - maxT ); + + if(timeDiff < TIME_CUT) { + locHitVec.push_back(locHit); + n_good_hits++; + } else { break; } + + } + + if(locHitVec.size()) hitPatterns.push_back(locHitVec); + + clonedHitArray.erase(clonedHitArray.begin(), clonedHitArray.begin() + n_good_hits); } - return; - } - - //========================================================== // // sortByTime // //========================================================== -void DCCALShower_factory::sortByTime( vector< const DCCALHit* > &hitarray, float hitTime ) +void DCCALShower_factory::sortByTime(vector &hitarray, float hitTime) { + int nhits = static_cast(hitarray.size()); - int nhits = static_cast( hitarray.size() ); + if(nhits < 2) return; // nothing to sort - if( nhits < 2 ) return; // nothing to sort - - for( int ih = 1; ih < nhits; ih++ ) + for(int ih = 1; ih < nhits; ih++) { - - float timeDiff = fabs( hitarray[ih]->t - hitTime ); - float lastTimeDiff = fabs( hitarray[ih-1]->t - hitTime ); - - if( timeDiff <= lastTimeDiff ) - { - - const DCCALHit *Hit = hitarray[ih]; - - for( int ii = ih-1; ii >= -1; ii-- ) { - - if( ii >= 0 ) { - - const DCCALHit *locHit = hitarray[ii]; - float locTimeDiff = fabs( locHit->t - hitTime ); - - if( timeDiff < locTimeDiff ) { - hitarray[ii+1] = locHit; - } else { - hitarray[ii+1] = Hit; - break; - } - } else { - hitarray[0] = Hit; - } - } - - } // end if statement - + float timeDiff = fabs(hitarray[ih]->t - hitTime); + float lastTimeDiff = fabs(hitarray[ih-1]->t - hitTime); + + if(timeDiff <= lastTimeDiff) + { + const DCCALHit *Hit = hitarray[ih]; + + for(int ii = ih-1; ii >= -1; ii--) + { + if(ii >= 0) { + const DCCALHit *locHit = hitarray[ii]; + float locTimeDiff = fabs(locHit->t - hitTime); + + if(timeDiff < locTimeDiff) { + hitarray[ii+1] = locHit; + } else { + hitarray[ii+1] = Hit; + break; + } + } else { + hitarray[0] = Hit; + } + } + + } // end if statement } // end loop over hits return; } - - //========================================================== // // cleanHitPattern // //========================================================== -void DCCALShower_factory::cleanHitPattern( vector< const DCCALHit* > hitarray, - vector< const DCCALHit* > &hitarrayClean ) +void DCCALShower_factory::cleanHitPattern(vector hitarray, + vector &hitarrayClean) { - - for( vector< const DCCALHit* >::const_iterator iHit = hitarray.begin(); - iHit != hitarray.end(); ++iHit ) { - - int id12 = ((*iHit)->row)*12 + (*iHit)->column; - int findVal = -1; - for( vector::size_type ii = 0; ii != hitarrayClean.size(); ++ii ) { - int id = 12*(hitarrayClean[ii]->row) + hitarrayClean[ii]->column; - if( id == id12 ) { findVal = (int)ii; break; } - } - if( findVal >= 0 ) { - if( (*iHit)->E > hitarrayClean[findVal]->E ) { - hitarrayClean.erase( hitarrayClean.begin()+findVal ); - hitarrayClean.push_back( (*iHit) ); - } - } else { - hitarrayClean.push_back( (*iHit) ); - } - - } - + for(vector< const DCCALHit* >::const_iterator iHit = hitarray.begin(); + iHit != hitarray.end(); ++iHit) { + + int id12 = ((*iHit)->row)*12 + (*iHit)->column; + int findVal = -1; + for(vector::size_type ii = 0; ii != hitarrayClean.size(); ++ii) { + int id = 12*(hitarrayClean[ii]->row) + hitarrayClean[ii]->column; + if(id == id12) { findVal = (int)ii; break; } + } + if(findVal >= 0) { + if((*iHit)->E > hitarrayClean[findVal]->E) { + hitarrayClean.erase(hitarrayClean.begin()+findVal); + hitarrayClean.push_back((*iHit)); + } + } else { + hitarrayClean.push_back((*iHit)); + } + } + return; - } - - //========================================================== // // processShowers // //========================================================== -void DCCALShower_factory::processShowers( vector< gamma_t > gammas, DCCALGeometry ccalGeom, - vector< const DCCALHit* > locHitPattern, int eventnumber, - vector< ccalcluster_t > &ccalClusters, vector< cluster_t > &clusterStorage ) +void DCCALShower_factory::processShowers(vector gammas, DCCALGeometry ccalGeom, + vector locHitPattern, int eventnumber, + vector &ccalClusters, + vector &clusterStorage) { - - //------------- Do some post-island processing -------------// - int n_clusters = 0; - int n_hits = static_cast( locHitPattern.size() ); - - int init_clusters = static_cast( gammas.size() ); - for( int k = 0; k < init_clusters; k++ ) { - - ccalcluster_t locCluster; // stores cluster parameters - cluster_t locClusterStorage; // stores hit information of cluster cells - - int type = gammas[k].type; - int dime = gammas[k].dime; - int id = gammas[k].id; - double chi2 = gammas[k].chi2; - double e = gammas[k].energy; - double x = gammas[k].x; - double y = gammas[k].y; - double xc = gammas[k].xc; - double yc = gammas[k].yc; - - - // check that shower is not just a single module and that energy is reasonable: - - if( dime < MIN_CLUSTER_BLOCK_COUNT ) { continue; } - if( e < MIN_CLUSTER_ENERGY || e > MAX_CLUSTER_ENERGY ) { continue; } - - n_clusters++; - - - //------------ Find cell with max energy ------------// - - double ecellmax = -1; int idmax = -1; - double e1 = 0.0; - for( int j = 0; j < (dime>MAX_CC ? MAX_CC : dime); j++ ) { - - - double ecell = 1.e-4*static_cast( gammas[k].icl_en[j] ); - - int ccal_id = gammas[k].icl_in[j]; - int kx = 12 - (ccal_id/100), ky = 12 - (ccal_id%100); - - ccal_id = ky*12 + kx; - - e1 += ecell; - if( ecell > ecellmax ) { - ecellmax = ecell; - idmax = ccal_id; - } - - } - - double xmax = ccalGeom.positionOnFace(idmax).X(); - double ymax = ccalGeom.positionOnFace(idmax).Y(); - - - //----------- Loop over constituent hits ------------// - - double sW = 0.0; - double xpos = 0.0; - double ypos = 0.0; - double W; - - for( int j = 0; j < (dime>MAX_CC ? MAX_CC : dime); j++ ) { - - int ccal_id = gammas[k].icl_in[j]; - int kx = 12 - (ccal_id/100), ky = 12 - (ccal_id%100); - ccal_id = ky*12 + kx; - - double ecell = 1.e-4*static_cast( gammas[k].icl_en[j] ); - double xcell = ccalGeom.positionOnFace( ccal_id ).X(); - double ycell = ccalGeom.positionOnFace( ccal_id ).Y(); - - if(id%10 == 1 || id%10 == 2) { - xcell += xc; - ycell += yc; - } - - double hittime = 0.; - for( int ihit = 0; ihit < n_hits; ihit++ ) { - int trialid = 12*( locHitPattern[ihit]->row) + locHitPattern[ihit]->column; - if( trialid == ccal_id ) { - hittime = locHitPattern[ihit]->t; - break; - } - } - - locClusterStorage.id[j] = ccal_id; - locClusterStorage.E[j] = ecell; - locClusterStorage.x[j] = xcell; - locClusterStorage.y[j] = ycell; - locClusterStorage.t[j] = hittime; - - - // The shower position is calculated using logarithmic weighting: - - if( ecell > 0.009 && fabs(xcell-xmax) < 6. && fabs(ycell-ymax) < 6.) { - W = LOG_POS_CONST + log(ecell/e); - if( W > 0 ) { - sW += W; - xpos += xcell*W; - ypos += ycell*W; - } - } - - } - - for( int j = dime; j < MAX_CC; j++ ) // zero the rest - locClusterStorage.id[j] = -1; - - double weightedTime = getEnergyWeightedTime( locClusterStorage, dime ); - double showerTime = getCorrectedTime( weightedTime, e ); - - - - //------- Get position at surface of Calorimeter -------// - - DVector3 vertex(0.0, 0.0, m_zTarget); // for now, use center of target as vertex - - double x1, y1; - double zV = vertex.Z(); - double z0 = m_CCALfront - zV; - if(sW) { - double dz = getShowerDepth( e ); - double zk = 1. / (1. + dz/z0); - x1 = zk*xpos/sW; - y1 = zk*ypos/sW; - } else { - printf("WRN bad cluster log. coord at event %i: center id = %i, energy = %f\n", - eventnumber, idmax, e); - x1 = 0.0; - y1 = 0.0; - } - - - - - //-------- Calculate nonlinear-corrected energy --------// - - - if( idmax < 0 ) { - printf("WRN negative idmax recorded at event %i; energy = %f\n", eventnumber, e); - } - - double ecorr = e; - if( DO_NONLINEAR_CORRECTION ) ecorr = getCorrectedEnergy( e, idmax ); - - if( SHOWER_DEBUG ) { - cout << "\n\nShower energy before correction: " << e << " GeV" << endl; - cout << "Shower energy after correction: " << ecorr << " GeV\n\n" << endl; - } - - - - - //-------- Get energy resolution (needs updating) --------// - - double se = sqrt( 0.9*0.9*ecorr*ecorr + 2.5*2.5*ecorr + 1.0 ); - // from HYCAL reconstruction, need to tune - se /= 100.; - - if( (type%10)==1 ) - se *= 1.5; - else if( (type%10)==2 ) - se *= 1.25; - - - - //----------------- Fill cluster bank -----------------// - - locCluster.type = type; - locCluster.nhits = dime; - locCluster.id = id; - locCluster.idmax = idmax; - - locCluster.E = ecorr; - locCluster.Esum = e1; - locCluster.x = x; - locCluster.y = y; - locCluster.x1 = x1; - locCluster.y1 = y1; - locCluster.chi2 = chi2; - locCluster.time = showerTime; - locCluster.emax = ecellmax; - locCluster.sigma_E = se; - - clusterStorage.push_back( locClusterStorage ); - ccalClusters.push_back( locCluster ); + int n_hits = static_cast(locHitPattern.size()); + int init_clusters = static_cast(gammas.size()); + for(int k = 0; k < init_clusters; k++) { + + ccalcluster_t locCluster; // stores cluster parameters + cluster_t locClusterStorage; // stores hit information of cluster cells + + int type = gammas[k].type; + int dime = gammas[k].dime; + int id = gammas[k].id; + double chi2 = gammas[k].chi2; + double e = gammas[k].energy; + double x = gammas[k].x; + double y = gammas[k].y; + double xc = gammas[k].xc; + double yc = gammas[k].yc; + + // check that shower is not just a single module and that energy is reasonable: + + if( dime < MIN_CLUSTER_BLOCK_COUNT ) { continue; } + if( e < MIN_CLUSTER_ENERGY || e > MAX_CLUSTER_ENERGY ) { continue; } + + if(dime > MAX_CC) dime = MAX_CC; + + n_clusters++; + + //------------ Find cell with max energy ------------// + + double ecellmax = -1; int idmax = -1; + double e1 = 0.0; + for(int j = 0; j < (dime>MAX_CC ? MAX_CC : dime); j++) { + + double ecell = 1.e-4*static_cast(gammas[k].icl_en[j]); + + int ccal_id = gammas[k].icl_in[j]; + int kx = 12 - (ccal_id/100), ky = 12 - (ccal_id%100); + + ccal_id = ky*12 + kx; + + e1 += ecell; + if(ecell > ecellmax) { + ecellmax = ecell; + idmax = ccal_id; + } + } + + double xmax = ccalGeom.positionOnFace(idmax).X(); + double ymax = ccalGeom.positionOnFace(idmax).Y(); + + //----------- Loop over constituent hits ------------// + + double sW = 0.0; + double xpos = 0.0; + double ypos = 0.0; + double W; + + for(int j = 0; j < (dime>MAX_CC ? MAX_CC : dime); j++) { + + int ccal_id = gammas[k].icl_in[j]; + int kx = 12 - (ccal_id/100), ky = 12 - (ccal_id%100); + ccal_id = ky*12 + kx; + + double ecell = 1.e-4*static_cast(gammas[k].icl_en[j]); + double xcell = ccalGeom.positionOnFace(ccal_id).X(); + double ycell = ccalGeom.positionOnFace(ccal_id).Y(); + + if(id%10 == 1 || id%10 == 2) { + xcell += xc; + ycell += yc; + } + + double hittime = 0.; + for( int ihit = 0; ihit < n_hits; ihit++ ) { + int trialid = 12*(locHitPattern[ihit]->row) + locHitPattern[ihit]->column; + if(trialid == ccal_id) { + hittime = locHitPattern[ihit]->t; + break; + } + } + + locClusterStorage.id[j] = ccal_id; + locClusterStorage.E[j] = ecell; + locClusterStorage.x[j] = xcell; + locClusterStorage.y[j] = ycell; + locClusterStorage.t[j] = hittime; + + // The shower position is calculated using logarithmic weighting: + + if(ecell > 0.009 && fabs(xcell-xmax) < 6. && fabs(ycell-ymax) < 6.) { + W = LOG_POS_CONST + log(ecell/e); + if(W > 0) { + sW += W; + xpos += xcell*W; + ypos += ycell*W; + } + } + } + + for(int j = dime; j < MAX_CC; j++) // zero the rest + locClusterStorage.id[j] = -1; + + //------- Get position inside Calorimeter -------// + + double x1, y1; + if(sW) { + x1 = xpos/sW; + y1 = ypos/sW; + } else { + printf("WRN bad cluster log. coord at event %i: center id = %i, energy = %f\n", + eventnumber, idmax, e); + x1 = 0.0; + y1 = 0.0; + } + + double dz = getShowerDepth(e); + double z = m_CCALfront + dz; + + //-------- Get shower time --------// + + double weightedTime = getEnergyWeightedTime(locClusterStorage, dime); + + // correct shower time for the time required + // for the light to collect at the back of the detector: + + double zback = m_CCALfront + ccalGeom.blockLength(); + weightedTime -= (zback - z) / CCAL_C_EFFECTIVE; + + // now apply timewalk correction: + + double showerTime; + if(DO_TIMEWALK_CORRECTION) showerTime = getCorrectedTime(weightedTime, e); + else showerTime = weightedTime; + + //-------- Calculate nonlinear-corrected energy --------// + + if(idmax < 0) { + printf("WRN negative idmax recorded at event %i; energy = %f\n", eventnumber, e); + } + + double ecorr = e; + if(DO_NONLINEAR_CORRECTION) ecorr = getCorrectedEnergy(e, idmax); + + if(SHOWER_DEBUG) { + cout << "\n\nShower energy before correction: " << e << " GeV" << endl; + cout << "Shower energy after correction: " << ecorr << " GeV\n\n" << endl; + } + + //-------- Get energy resolution (needs updating) --------// + + double se = sqrt(0.9*0.9*ecorr*ecorr + 2.5*2.5*ecorr + 1.0); + // from HYCAL reconstruction, need to tune + se /= 100.; + + if((type%10)==1) + se *= 1.5; + else if((type%10)==2) + se *= 1.25; + + //----------------- Fill cluster bank -----------------// + + locCluster.type = type; + locCluster.nhits = dime; + locCluster.id = id; + locCluster.idmax = idmax; + + locCluster.E = ecorr; + locCluster.Esum = e1; + locCluster.x = x; + locCluster.y = y; + locCluster.x1 = x1; + locCluster.y1 = y1; + locCluster.z = z; + locCluster.chi2 = chi2; + locCluster.time = showerTime; + locCluster.emax = ecellmax; + locCluster.sigma_E = se; + + clusterStorage.push_back(locClusterStorage); + ccalClusters.push_back(locCluster); } - - + return; } - - //========================================================== // // getEnergyWeightedTime // //========================================================== -double DCCALShower_factory::getEnergyWeightedTime( cluster_t clusterStorage, int nHits ) +double DCCALShower_factory::getEnergyWeightedTime(cluster_t clusterStorage, int nHits) { - double weightedtime = 0.; double totEn = 0; - for( int j = 0; j < (nHits > MAX_CC ? MAX_CC : nHits); j++ ) { - weightedtime += clusterStorage.t[j]*clusterStorage.E[j]; - totEn += clusterStorage.E[j]; + for(int j = 0; j < (nHits > MAX_CC ? MAX_CC : nHits); j++) { + weightedtime += clusterStorage.t[j]*clusterStorage.E[j]; + totEn += clusterStorage.E[j]; } weightedtime /= totEn; return weightedtime; - } - - //========================================================== // // getCorrectedTime // //========================================================== -double DCCALShower_factory::getCorrectedTime( double time, double energy ) +double DCCALShower_factory::getCorrectedTime(double time, double energy) { // timewalk correction: int iPar; - if( energy < 1.0 ) iPar = 0; + if(energy < 1.0) iPar = 0; else iPar = 1; - double dt = timewalk_p0[iPar]*exp( timewalk_p1[iPar] + timewalk_p2[iPar]*energy ) + timewalk_p3[iPar]; + double dt = timewalk_p0[iPar]*exp(timewalk_p1[iPar] + timewalk_p2[iPar]*energy) + + timewalk_p3[iPar]; double t_cor = time - dt; return t_cor; - } - - //========================================================== // // getShowerDepth // //========================================================== -double DCCALShower_factory::getShowerDepth( double energy ) +double DCCALShower_factory::getShowerDepth(double energy) { - double z0 = CCAL_RADIATION_LENGTH, e0 = CCAL_CRITICAL_ENERGY; double depth = (energy > 0.) ? z0*log(1.+energy/e0) : 0.; return depth; - } - - //========================================================== // // getCorrectedEnergy // //========================================================== -double DCCALShower_factory::getCorrectedEnergy( double energy, int id ) +double DCCALShower_factory::getCorrectedEnergy(double energy, int id) { + if(id < 0) return energy; - if( id < 0 ) return energy; + if(Nonlin_p1[id] == 0. && Nonlin_p2[id] == 0. && Nonlin_p3[id] == 0.) return energy; + if(Nonlin_p0[id] == 0.) return energy; + //if( energy < 0.5 || energy > 12. ) return energy; - if( Nonlin_p1[id] == 0. && Nonlin_p2[id] == 0. && Nonlin_p3[id] == 0.) return energy; - if( Nonlin_p0[id] == 0. ) return energy; - //if( energy < 0.5 || energy > 12. ) return energy; - - double emin = 0., emax = 12.; - double e0 = (emin+emax)/2.; - - double de1 = energy - emin*nonlin_func( emin, id ); - double de2 = energy - emax*nonlin_func( emax, id ); - double de = energy - e0*nonlin_func( e0, id ); - - while( fabs(emin-emax) > 1.e-5 ) { - if( de1*de > 0. && de2*de < 0.) { - emin = e0; - de1 = energy - emin*nonlin_func( emin, id ); - } else { - emax = e0; - de2 = energy - emax*nonlin_func( emax, id ); - } - e0 = (emin+emax)/2.; - de = energy - e0*nonlin_func( e0, id ); - } - - return e0; - + double e0 = (emin+emax)/2.; + + double de1 = energy - emin*nonlin_func(emin,id); + double de2 = energy - emax*nonlin_func(emax,id); + double de = energy - e0*nonlin_func(e0,id); + + while(fabs(emin-emax) > 1.e-5) { + if(de1*de > 0. && de2*de < 0.) { + emin = e0; + de1 = energy - emin*nonlin_func(emin,id); + } else { + emax = e0; + de2 = energy - emax*nonlin_func(emax,id); + } + e0 = (emin+emax)/2.; + de = energy - e0*nonlin_func(e0,id); + } + + return e0; } - - //========================================================== // // nonlin_func // //========================================================== -double DCCALShower_factory::nonlin_func( double e, int id ) +double DCCALShower_factory::nonlin_func(double e, int id) { - - return pow( (e/Nonlin_p0[id]), Nonlin_p1[id] + Nonlin_p2[id]*e + Nonlin_p3[id]*e*e ); - + return pow((e/Nonlin_p0[id]), Nonlin_p1[id] + Nonlin_p2[id]*e + Nonlin_p3[id]*e*e); } - - - - - - - - - - - - - - - - - - @@ -966,33 +862,33 @@ double DCCALShower_factory::nonlin_func( double e, int id ) // //========================================================== -void DCCALShower_factory::main_island( vector &ia, vector &id, vector &gammas ) +void DCCALShower_factory::main_island(vector &ia, vector &id, vector &gammas) { - + //---------------------------------------------- // Initialize some useful variables: - + int nhits; // number of hits in detector - int ncl; // number of clusters + int ncl; // number of clusters vector lencl; // length of a cluster nhits = static_cast(ia.size()); - if( nhits == 0 ) return; + if(nhits == 0) return; /* The vector 'ia' will hold the addresses of modules that were hit. - They're defined as 100*(i+1)+(j+1) where i is column and j is row of the hit module. - Row 0, column 0 is bottom right corner of CCAL (looking upstream). + They're defined as 100*(12-column)+(12-row) where 'row' and 'column' are + defined in the DCCALGeometry. + For example, the top left corner of the CCAL (looking downstream) is address 101. + The bottom right corner is address 1212. The 'id' vector holds the energies of the hit modules (in units of 0.1 MeVs). */ - //------------------ Search for clusters: ------------------// - - ncl = clus_hyc( nhits, ia, id, lencl ); + ncl = clus_hyc(nhits, ia, id, lencl); /* At this point, the vectors ia and id are sorted such that they are grouped @@ -1004,267 +900,242 @@ void DCCALShower_factory::main_island( vector &ia, vector &id, vector< next to each other into one cluster - all simply-connected cells are joined in a cluster. */ - //-------------------- Process Cluster: --------------------// int nadcgam = 0; // number of found clusters - if( ncl <= 0 ) return; + if(ncl <= 0) return; int ipncl = 0; - for( int icl = 0; icl < ncl; icl++ ) { - - int ecl = 0; - for( int ii = 0; ii < lencl[icl]; ii++ ) - ecl += id[ipncl+ii]; - if( ecl > MIN_ENERGY ) { - - vector< int > icl_a; // addresses of current cluster - vector< int > icl_d; // energies of current cluster - - icl_a.insert( icl_a.begin(), ia.begin()+ipncl, ia.begin()+ipncl+lencl[icl] ); - icl_d.insert( icl_d.begin(), id.begin()+ipncl, id.begin()+ipncl+lencl[icl] ); - - - if( SHOWER_DEBUG ) { - - cout << "\n\n======================" << endl; - cout << "Processing Cluster " << icl << ":" << endl; - for( unsigned int ih = 0; ih < icl_a.size(); ih++ ) { - cout << icl_a[ih] << " " << icl_d[ih] << endl; - } - - } - - int before = nadcgam; - gams_hyc( lencl[icl], icl_a, icl_d, nadcgam, gammas ); - int after = nadcgam; - - - if( SHOWER_DEBUG ) { - cout << "Reconstructed " << after-before << " gammas. \n\n" << endl; - } - - - if( nadcgam > MADCGAM ) { - nadcgam = MADCGAM; - break; - } - } - ipncl = ipncl + lencl[icl]; + for(int icl = 0; icl < ncl; icl++) { + + int ecl = 0; + for(int ii = 0; ii < lencl[icl]; ii++) + ecl += id[ipncl+ii]; + + if(ecl > MIN_ENERGY) { + + vector icl_a; // addresses of current cluster + vector icl_d; // energies of current cluster + + icl_a.insert(icl_a.begin(), ia.begin()+ipncl, ia.begin()+ipncl+lencl[icl]); + icl_d.insert(icl_d.begin(), id.begin()+ipncl, id.begin()+ipncl+lencl[icl]); + + if(SHOWER_DEBUG) { + cout << "\n\n======================" << endl; + cout << "Processing Cluster " << icl << ":" << endl; + for(unsigned int ih = 0; ih < icl_a.size(); ih++) { + cout << icl_a[ih] << " " << icl_d[ih] << endl; + } + } + + int before = nadcgam; + gams_hyc(lencl[icl], icl_a, icl_d, nadcgam, gammas); + int after = nadcgam; + + if(SHOWER_DEBUG) { + cout << "Reconstructed " << after-before << " gammas. \n\n" << endl; + } + + if( nadcgam > MADCGAM ) { + nadcgam = MADCGAM; + break; + } + } + ipncl = ipncl + lencl[icl]; } - //-------------------- Prepare gammas for final processing --------------------// - // convert position to units of cm: - for( int ig = 0; ig < nadcgam; ig++ ) { - gammas[ig].energy /= 10000.; - gammas[ig].x = (static_cast(MCOL+1)-2.*gammas[ig].x)*xsize/2.; - gammas[ig].y = (static_cast(MROW+1)-2.*gammas[ig].y)*ysize/2.; - gammas[ig].xc = -gammas[ig].xc*xsize; - gammas[ig].yc = -gammas[ig].yc*ysize; + for(int ig = 0; ig < nadcgam; ig++) { + gammas[ig].energy /= 10000.; + gammas[ig].x = (static_cast(MCOL+1)-2.*gammas[ig].x)*xsize/2.; + gammas[ig].y = (static_cast(MROW+1)-2.*gammas[ig].y)*ysize/2.; + gammas[ig].xc = -gammas[ig].xc*xsize; + gammas[ig].yc = -gammas[ig].yc*ysize; } - - if( nadcgam < 1 ) return; - + if(nadcgam < 1) return; // sort gammas in order of decreasing energy: - for( int ig = 1; ig < nadcgam; ig++ ) + for(int ig = 1; ig < nadcgam; ig++) { - if( gammas[ig].energy > gammas[ig-1].energy ) { - gamma_t ref_gam = gammas[ig]; - - for( int ii = ig-1; ii >= -1; ii-- ) { - if( ii >= 0 ) { - if( ref_gam.energy > gammas[ii].energy ) { - gammas[ii+1] = gammas[ii]; - } else { - gammas[ii+1] = ref_gam; - break; - } - } else { - gammas[0] = ref_gam; - } - } - } + if( gammas[ig].energy > gammas[ig-1].energy ) { + gamma_t ref_gam = gammas[ig]; + + for(int ii = ig-1; ii >= -1; ii--) { + if( ii >= 0 ) { + if(ref_gam.energy > gammas[ii].energy) { + gammas[ii+1] = gammas[ii]; + } else { + gammas[ii+1] = ref_gam; + break; + } + } else { + gammas[0] = ref_gam; + } + } + } } - - return; } - - - //========================================================== // // clus_hyc // //========================================================== -int DCCALShower_factory::clus_hyc( int nw, vector &ia, vector &id, vector &lencl ) +int DCCALShower_factory::clus_hyc(int nw, vector &ia, vector &id, vector &lencl) { - + //---------------- Local Declarations ---------------// int maxcl = 200; // maximumum number of clusters allowed int ncl; // number of clusters - int next, iak; // - int ib, ie; // - int ias, iaf; // - int last, lastcl; // - int leng; // - // + int next, iak; // + int ib, ie; // + int ias, iaf; // + int last, lastcl; // + int leng; // int loclencl[200]; // stores the lengths of clusters locally - //---------------- Event Analysis Code --------------// ncl = 0; - if( nw < 1 ) return ncl; - if( nw < 2 ) { // if only one hit - ncl = 1; - lencl.push_back(1); - return ncl; + if(nw < 1) return ncl; + if(nw < 2) { // if only one hit + ncl = 1; + lencl.push_back(1); + return ncl; } - order_hyc( nw, ia, id ); // sort the addresses (ia) in increasing order + order_hyc(nw, ia, id); // sort the addresses (ia) in increasing order ncl = 0; next = 0; - for( int k = 1; k < (nw+1); k++ ) { - - if( k < nw ) iak = ia[k]; - if( (iak-ia[k-1] <= 1) && (k < nw) ) continue; - - ib = next; - ie = k-1; - next = k; - - if( ncl >= maxcl ) return ncl; - ncl++; - - loclencl[ncl-1] = next-ib; - if(ncl == 1) continue; - - ias = ia[ib]; - iaf = ia[ie]; - last = ib-1; - lastcl = ncl-1; - - for( int icl = lastcl; icl > 0; icl-- ) { - - leng = loclencl[icl-1]; - if( (ias-ia[last]) > 100 ) break; // no subclusters to be glued - - for( int ii = last; ii >= last-leng+1; ii-- ) { - if( ( ias-ia[ii] ) > 100 ) break; - if( ( iaf-ia[ii] ) >= 100 ) { - - if( (icl < (ncl-1)) && (leng <= 10800) ) { - - vector< int > iawork; - ucopy1( ia, iawork, last-leng+1, leng ); - ucopy2( ia, last+1, last+1-leng, ib-last-1 ); - ucopy3( iawork, ia, ib-leng, leng ); - - vector< int > idwork; - ucopy1( id, idwork, last-leng+1, leng ); - ucopy2( id, last+1, last+1-leng, ib-last-1 ); - ucopy3( idwork, id, ib-leng, leng ); - - for( int jj = icl; jj < ncl-1; jj++ ) { - loclencl[jj-1] = loclencl[jj]; - } + for(int k = 1; k < (nw+1); k++) { - } + if(k < nw) iak = ia[k]; + if((iak-ia[k-1] <= 1) && (k < nw)) continue; + + ib = next; + ie = k-1; + next = k; + + if(ncl >= maxcl) return ncl; + ncl++; + + loclencl[ncl-1] = next-ib; + if(ncl == 1) continue; - ib = ib-leng; - loclencl[ncl-2] = loclencl[ncl-1]+leng; - ncl = ncl-1; - break; - } - } - - last = last-leng; - - } // end loop over previous subclusters + ias = ia[ib]; + iaf = ia[ie]; + last = ib-1; + lastcl = ncl-1; + + for(int icl = lastcl; icl > 0; icl--) { + + leng = loclencl[icl-1]; + if((ias-ia[last]) > 100) break; // no subclusters to be glued + + for(int ii = last; ii >= last-leng+1; ii-- ) { + if((ias-ia[ii]) > 100) break; + if((iaf-ia[ii])>= 100) { + + if((icl < (ncl-1)) && (leng <= 10800)) { + + vector iawork; + ucopy1(ia, iawork, last-leng+1, leng); + ucopy2(ia, last+1, last+1-leng, ib-last-1); + ucopy3(iawork, ia, ib-leng, leng); + + vector idwork; + ucopy1(id, idwork, last-leng+1, leng); + ucopy2(id, last+1, last+1-leng, ib-last-1); + ucopy3(idwork, id, ib-leng, leng); + + for(int jj = icl; jj < ncl-1; jj++) { + loclencl[jj-1] = loclencl[jj]; + } + } + + ib = ib-leng; + loclencl[ncl-2] = loclencl[ncl-1]+leng; + ncl = ncl-1; + break; + } + } + + last = last-leng; + + } // end loop over previous subclusters } // end loop over all hits for( int icl = 0; icl < ncl; icl++ ) { - lencl.push_back( loclencl[icl] ); + lencl.push_back( loclencl[icl] ); } - return ncl; } - - - //========================================================== // // order_hyc // //========================================================== -void DCCALShower_factory::order_hyc( int nw, vector &ia, vector &id ) +void DCCALShower_factory::order_hyc(int nw, vector &ia, vector &id) { // sort ia and id in order of increasing address - if( nw < 2 ) return; // only one hit + if(nw < 2) return; // only one hit for( int k = 1; k < nw; k++ ) { // loop over hits - - if( ia[k] <= ia[k-1] ) { // check if address is less than previous entry - int iak = ia[k]; - int idk = id[k]; - - for( int ii = k-1; ii >= -1; ii = ii-1 ) { // loop over the previous entries - - if( ii >= 0 ) { - if( iak < ia[ii] ) { - ia[ii+1] = ia[ii]; - id[ii+1] = id[ii]; - } else { - ia[ii+1] = iak; - id[ii+1] = idk; - break; - } - } else { - ia[0] = iak; - id[0] = idk; - } - - } // end loop over previous entries - } // endif + + if( ia[k] <= ia[k-1] ) { // check if address is less than previous entry + int iak = ia[k]; + int idk = id[k]; + + for( int ii = k-1; ii >= -1; ii = ii-1 ) { // loop over the previous entries + + if( ii >= 0 ) { + if( iak < ia[ii] ) { + ia[ii+1] = ia[ii]; + id[ii+1] = id[ii]; + } else { + ia[ii+1] = iak; + id[ii+1] = idk; + break; + } + } else { + ia[0] = iak; + id[0] = idk; + } + + } // end loop over previous entries + } // endif } // end loop over hits - - + return; } - - - //========================================================== // // gams_hyc // //========================================================== -void DCCALShower_factory::gams_hyc( int nadc, vector &ia, vector &id, - int &nadcgam, vector &gammas ) +void DCCALShower_factory::gams_hyc(int nadc, vector &ia, vector &id, + int &nadcgam, vector &gammas) { //-------------Local Declarations------------// @@ -1311,603 +1182,567 @@ void DCCALShower_factory::gams_hyc( int nadc, vector &ia, vector &id, ngam0 = nadcgam; - vector iwrk[13]; // working array for resolved peaks vector idp[13]; // energy of each cell of the island belonging to each peak vector fwrk[13]; // working array for resolved peaks // allocate memory for each vector: - for( int ii=0; ii<13; ii++ ) { - iwrk[ii].reserve(nadc); - fwrk[ii].reserve(nadc); - idp[ii].reserve(nadc); - for( int ih=0; ih(idsum)) + 0.5; - if( trial > 1 ) minpk = trial; - else minpk = 1; + for(int ic = 0; ic < nadc; ic++) + idsum += id[ic]; + + if(nadc < 3) { + minpk = 1; + } else { + int trial = 7.*log(1. + 0.0001*static_cast(idsum)) + 0.5; + if( trial > 1 ) minpk = trial; + else minpk = 1; } minpk *= 100; - npk = 0; - for( ic = 0; ic < nadc; ic++ ) { - idc = id[ic]; - if( idc < minpk ) continue; - ixy = ia[ic]; - ixymax = ixy + 100 + 1; - ixymin = ixy - 100 - 1; - iyc = ixy - (ixy/100)*100; - - int peakVal = 1; - - in = ic+1; - while( in < nadc && ia[in] <= ixymax ) { - iy = ia[in] - (ia[in]/100)*100; - if( abs(iy-iyc) <= 1 && id[in] >= idc ) peakVal = 0; - in++; - } - - in = ic-1; - while( in >= 0 && ia[in] >= ixymin ) { - iy = ia[in] - (ia[in]/100)*100; - if( abs(iy-iyc) <= 1 && id[in] > idc ) peakVal = 0; - in -= 1; - } - - if( !peakVal ) continue; - - npk += 1; - ipnpk[npk-1] = ic; - if( npk == 10 || npk >= 10000/nadc-3 ) break; - + for(ic = 0; ic < nadc; ic++) { + idc = id[ic]; + if(idc < minpk) continue; + ixy = ia[ic]; + ixymax = ixy + 100 + 1; + ixymin = ixy - 100 - 1; + iyc = ixy - (ixy/100)*100; + + int peakVal = 1; + + in = ic+1; + while(in < nadc && ia[in] <= ixymax) { + iy = ia[in] - (ia[in]/100)*100; + if( abs(iy-iyc) <= 1 && id[in] >= idc ) peakVal = 0; + in++; + } + + in = ic-1; + while(in >= 0 && ia[in] >= ixymin) { + iy = ia[in] - (ia[in]/100)*100; + if( abs(iy-iyc) <= 1 && id[in] > idc ) peakVal = 0; + in -= 1; + } + + if(!peakVal) continue; + + npk += 1; + ipnpk[npk-1] = ic; + if(npk == 10 || npk >= 10000/nadc-3) break; } - if( npk <= 0 ) return; - - if( SHOWER_DEBUG ) cout << "Found " << npk << " peaks. Now processing..." << endl; - - //------------------------------------------ - // gammas search for one peak: - - if( npk == 1 ) { - - if( nadcgam >= MADCGAM-1 ) return; - nadcgam = nadcgam+1; - chisq = chisq2; - - ic = ipnpk[0]; - ix = ia[ic]/100; - iy = ia[ic] - ix*100; - - itype = peak_type( ix, iy ); - - e2 = 0.; - gamma_hyc( nadc, ia, id, chisq, - e1, x1, y1, - e2, x2, y2 ); - - gamma_t gam1; - gamma_t gam2; - - gam1.type = itype; - gam1.dime = nadc; - gam1.id = 0; - - gam1.chi2 = chisq; - gam1.energy = e1; - gam1.x = x1; - gam1.y = y1; - gam1.xc = 0.; - gam1.yc = 0.; - - if( e2 > 0. && nadcgam <= MADCGAM-1 ) { - nadcgam = nadcgam+1; - - gam2.type = itype+10; - gam2.dime = nadc; - gam2.id = 2; - - gam2.chi2 = chisq; - gam2.energy = e2; - gam2.x = x2; - gam2.y = y2; - gam2.xc = 0.5*(x2-x1); - gam2.yc = 0.5*(y2-y1); - - gam1.type = itype+10; - gam1.id = 1; - gam1.xc = 0.5*(x1-x2); - gam1.yc = 0.5*(y1-y2); - - for( int jj = 0; jj < nadc; jj++ ) { - if( jj < MAX_CC ) { - gam1.icl_in[jj] = ia[jj]; - gam2.icl_in[jj] = ia[jj]; - gam1.icl_en[jj] = static_cast(static_cast(id[jj])*e1/(e1+e2) + 0.5); - gam2.icl_en[jj] = static_cast(static_cast(id[jj])*e2/(e1+e2) + 0.5); - } - } - - gammas.push_back( gam1 ); - gammas.push_back( gam2 ); - - } else { - for( int jj = 0; jj < nadc; jj++ ) { - if( jj < MAX_CC ) { - gam1.icl_in[jj] = ia[jj]; - gam1.icl_en[jj] = id[jj]; - } - } - - gammas.push_back( gam1 ); - - } - - - } else { // cluster with more than one peak - - //------------------------------------------ - /* - First step - 1 gamma in each peak. - Do a preliminary estimation of (E,x,y) of each peak, and split each peak into two hits - only if it is badly needed (chi2 improvement is too high). - If this split occurs, it is only for better (E,x,y) estimation, as it will be - rejoined and reanalyzed in the second step. - */ - //------------------------------------------ + if(npk <= 0) return; + if(SHOWER_DEBUG) cout << "Found " << npk << " peaks. Now processing..." << endl; - if( nadcgam >= MADCGAM-1 ) return; - - ratio = 1.; - for( int iter = 0; iter < niter; iter++ ) { - for( int ii = 0; ii < nadc; ii++ ) { - iwrk[0].push_back(0); - fwrk[0].push_back(0.); - } - - for( int ipk = 0; ipk < npk; ipk++ ) { - - ic = ipnpk[ipk]; - if( iter > 0 ) ratio = fwrk[ipk+1][ic]/fwrk[npk+1][ic]; - eg = ratio*static_cast(id[ic]); - ixypk = ia[ic]; - ixpk = ixypk/100; - iypk = ixypk - ixpk*100; - epk[ipk] = eg; - xpk[ipk] = eg*static_cast(ixpk); - ypk[ipk] = eg*static_cast(iypk); - - if( ic < nadc-1 ) { - for( int ii = ic+1; ii < nadc; ii++ ) { - ixy = ia[ii]; - ix = ixy/100; - iy = ixy - ix*100; - if( ixy-ixypk > 100+1 ) break; - if( abs(iy-iypk) <= 1 ) { - if( iter != 0 ) ratio = fwrk[ipk+1][ii]/fwrk[npk+1][ii]; - eg = ratio*static_cast(id[ii]); - epk[ipk] = epk[ipk] + eg; - xpk[ipk] = xpk[ipk] + eg*static_cast(ix); - ypk[ipk] = ypk[ipk] + eg*static_cast(iy); - } - } - } - - if( ic > 0 ) { - for( int ii = ic-1; ii >= 0; ii--) { - ixy = ia[ii]; - ix = ixy/100; - iy = ixy - ix*100; - if( ixypk-ixy > 100+1 ) break; - if( abs(iy-iypk) <= 1 ) { - if( iter != 0 ) ratio = fwrk[ipk+1][ii]/fwrk[npk+1][ii]; - eg = ratio*static_cast(id[ii]); - epk[ipk] = epk[ipk] + eg; - xpk[ipk] = xpk[ipk] + eg*static_cast(ix); - ypk[ipk] = ypk[ipk] + eg*static_cast(iy); - } - } - } - - if( epk[ipk] > 0. ) { - xpk[ipk] = xpk[ipk]/epk[ipk]; - ypk[ipk] = ypk[ipk]/epk[ipk]; - } - - for( int ii = 0; ii < nadc; ii++ ) { - ixy = ia[ii]; - ix = ixy/100; - iy = ixy - ix*100; - dx = fabs( static_cast(ix) - xpk[ipk] ); - dy = fabs( static_cast(iy) - ypk[ipk] ); - - a = epk[ipk]*cell_hyc( dx, dy ); - - fwrk[ipk+1][ii] = a; - fwrk[0][ii] = fwrk[0][ii] + fwrk[ipk+1][ii]; - iwrk[ipk+1][ii] = static_cast(a + 0.5); - iwrk[0][ii] = iwrk[0][ii] + iwrk[ipk+1][ii]; - } - - - } // end loop over peaks - - for( int ii = 0; ii < nadc; ii++ ) { - iwk = iwrk[0][ii]; - if( iwk < 1 ) iwk = 1; - iwrk[npk+1][ii] = iwk; - - if( fwrk[0][ii] > 1.e-2 ) - fwrk[npk+1][ii] = fwrk[0][ii]; - else - fwrk[npk+1][ii] = 1.e-2; - - } - } // end of iterations to separate peaks in a cluster - - - - if( SHOWER_DEBUG ) { - - - cout << "\n\n\nAfter 6 iterations: " << endl; - for( int ipk = 0; ipk < npk; ipk++ ) { - cout << "peak " << ipk+1 << ": " << endl; - for( int jj = 0; jj < nadc; jj++ ) { - cout << ia[jj] <<"; "<< id[jj] <<"; "<< fwrk[ipk+1][jj] << endl; - } - } - - } - - - - - for( int ipk = 0; ipk < npk; ipk++ ) { - - vector iwrk_a; - vector iwrk_d; - - leng = 0; - for( int ii = 0; ii < nadc; ii++ ) { - if( fwrk[0][ii] > 1.e-2 ) { - ixy = ia[ii]; - fe = static_cast(id[ii])*fwrk[ipk+1][ii]/fwrk[0][ii]; - - if( fe > idelta ) { - leng = leng+1; - iwrk_a.push_back( ixy ); - iwrk_d.push_back( static_cast(fe+0.5) ); + //------------------------------------------ + // gammas search for one peak: + + if(npk == 1) { + + if(nadcgam >= MADCGAM-1) return; + nadcgam = nadcgam+1; + chisq = chisq2; + + ic = ipnpk[0]; + ix = ia[ic]/100; + iy = ia[ic] - ix*100; + + itype = peak_type(ix, iy); + + e2 = 0.; + gamma_hyc(nadc, ia, id, chisq, + e1, x1, y1, + e2, x2, y2); + + gamma_t gam1; + gamma_t gam2; + + gam1.type = itype; + gam1.dime = nadc; + gam1.id = 0; + + gam1.chi2 = chisq; + gam1.energy = e1; + gam1.x = x1; + gam1.y = y1; + gam1.xc = 0.; + gam1.yc = 0.; + + if(e2 > 0. && nadcgam <= MADCGAM-1) { + + nadcgam = nadcgam+1; + + gam2.type = itype+10; + gam2.dime = nadc; + gam2.id = 2; + + gam2.chi2 = chisq; + gam2.energy = e2; + gam2.x = x2; + gam2.y = y2; + gam2.xc = 0.5*(x2-x1); + gam2.yc = 0.5*(y2-y1); + + gam1.type = itype+10; + gam1.id = 1; + gam1.xc = 0.5*(x1-x2); + gam1.yc = 0.5*(y1-y2); + + for(int jj = 0; jj < nadc; jj++) { + if( jj < MAX_CC ) { + gam1.icl_in[jj] = ia[jj]; + gam2.icl_in[jj] = ia[jj]; + gam1.icl_en[jj] = static_cast( + static_cast(id[jj])*e1/(e1+e2) + 0.5); + gam2.icl_en[jj] = static_cast( + static_cast(id[jj])*e2/(e1+e2) + 0.5); + } + } + + gammas.push_back(gam1); + gammas.push_back(gam2); + + } else { + + for(int jj = 0; jj < nadc; jj++) { + if(jj < MAX_CC) { + gam1.icl_in[jj] = ia[jj]; + gam1.icl_en[jj] = id[jj]; + } + } + + gammas.push_back(gam1); } - - } - } - - if( nadcgam >= MADCGAM-1 ) return; - - igmpk[1][ipk] = 0; - if( leng == 0 ) continue; - nadcgam = nadcgam + 1; - chisq = chisq1; - - ic = ipnpk[ipk]; - ix = ia[ic]/100; - iy = ia[ic] - ix*100; - - itype = peak_type( ix, iy ); - - e2 = 0.; - gamma_hyc( leng, iwrk_a, iwrk_d, chisq, - e1, x1, y1, e2, x2, y2 ); - - gamma_t gam1; - gamma_t gam2; - - gam1.chi2 = chisq; - gam1.type = itype+40; - gam1.energy = e1; - gam1.x = x1; - gam1.y = y1; - gam1.dime = leng; - - gam1.id = 90; - - igmpk[0][ipk] = nadcgam; - igmpk[1][ipk] = nadcgam; - - if( e2 > 0. && nadcgam <= MADCGAM-1 ) { - nadcgam = nadcgam+1; - - gam2.chi2 = chisq; - gam2.type = itype+50; - gam2.energy = e2; - gam2.x = x2; - gam2.y = y2; - gam2.xc = 0.5*(x2-x1); - gam2.yc = 0.5*(y2-y1); - gam1.xc = 0.5*(x1-x2); - gam1.yc = 0.5*(y1-y2); - - gam2.id = 92; - gam1.id = 91; - - gam2.dime = leng; - igmpk[1][ipk] = nadcgam; - - gammas.push_back( gam1 ); - gammas.push_back( gam2 ); - - } else { gammas.push_back( gam1 ); } - - } // end loop over peaks - - - - /* - This is the second step: ( 1 or 2 gamma in each peak ) - (e,x,y) of hits were preliminarily estimated in the first step. - */ - - for( int ii = 0; ii < nadc; ii++ ) { - iwrk[0][ii] = 0; - fwrk[0][ii] = 0.; - idp[0][ii] = 0; - } - - for( int ipk = 0; ipk < npk; ipk++ ) { - for( int ii = 0; ii < nadc; ii++ ) { - iwrk[ipk+1][ii] = 0; - fwrk[ipk+1][ii] = 0.; - idp[ipk+1][ii] = 0; - - if( igmpk[1][ipk] == 0 ) continue; - - for( int ig = igmpk[0][ipk]; ig <= igmpk[1][ipk]; ig++ ) { - ixy = ia[ii]; - ix = ixy/100; - iy = ixy-(ix*100); - dx = static_cast(ix) - gammas[ig-1].x; - dy = static_cast(iy) - gammas[ig-1].y; - - fia = gammas[ig-1].energy*cell_hyc( dx, dy ); - iia = static_cast(fia+0.5); - - // part of gamma 'ig' energy belonging to cell 'i' from peak 'ipk': - iwrk[ipk+1][ii] += iia; - fwrk[ipk+1][ii] += fia; - idp[ipk+1][ii] += iia; - - iwrk[0][ii] += iia; - fwrk[0][ii] += fia; - - } - - } // end loop over hits - } // end loop over peaks - - - - - // Recover working array and renormalize total sum to the original cell energy: - - for( int ii = 0; ii < nadc; ii++ ) { - - idp[0][ii] = 0; - for( int ipk = 0; ipk < npk; ipk++ ) { - idp[0][ii] += idp[ipk+1][ii]; - } - - ide = id[ii] - idp[0][ii]; - if( ide == 0 ) continue; - if( fwrk[0][ii] == 0. ) continue; - - for( int ipk = 0; ipk < npk; ipk++ ) { - fw[ipk+1] = fwrk[ipk+1][ii]/fwrk[0][ii]; - } - - idecorr = 0; - for( int ipk = 0; ipk < npk; ipk++ ) { - fia = ide*fw[ipk+1]; - if( (fwrk[ipk+1][ii] + fia) > 0. ) { - fwrk[ipk+1][ii] += fia; - fwrk[0][ii] += fia; - } - iia = static_cast(fia+0.5); - if( (iwrk[ipk+1][ii] + iia) > 0 ) { - iwrk[ipk+1][ii] += iia; - iwrk[0][ii] += iia; - idecorr += iia; - } else if( (iwrk[ipk+1][ii] + iia) < 0 ) { - //cout << "WARNING NEGATIVE CORR: ia = " << ia[ii] << "; id = " << id[ii] << endl; - } - } // end loop over peaks - - } // end loop over hits - - - - // erase the gammas found in the previous step: - - nadcgam = ngam0; - gammas.erase( gammas.begin()+nadcgam, gammas.end() ); - - - - - - - for( int ipk = 0; ipk < npk; ipk++ ) { - leng = 0; - - vector iwrk_a; - vector iwrk_d; - - for( int ii = 0; ii < nadc; ii++ ){ - if( iwrk[0][ii] > 0 ) { - fe = id[ii]*fwrk[ipk+1][ii]/fwrk[0][ii]; - if( fe > idelta ) { - leng++; - iwrk_a.push_back( ia[ii] ); - iwrk_d.push_back( static_cast(fe+0.5) ); + + } else { // cluster with more than one peak + + //------------------------------------------ + /* + First step - 1 gamma in each peak. + Do a preliminary estimation of (E,x,y) of each peak, and split each peak into two hits + only if it is badly needed (chi2 improvement is too high). + If this split occurs, it is only for better (E,x,y) estimation, as it will be + rejoined and reanalyzed in the second step. + */ + //------------------------------------------ + + + if(nadcgam >= MADCGAM-1) return; + + ratio = 1.; + for(int iter = 0; iter < niter; iter++) { + for(int ii = 0; ii < nadc; ii++) { + iwrk[0].push_back(0); + fwrk[0].push_back(0.); + } + + for(int ipk = 0; ipk < npk; ipk++) { + + ic = ipnpk[ipk]; + if(iter > 0) ratio = fwrk[ipk+1][ic]/fwrk[npk+1][ic]; + eg = ratio*static_cast(id[ic]); + ixypk = ia[ic]; + ixpk = ixypk/100; + iypk = ixypk - ixpk*100; + epk[ipk] = eg; + xpk[ipk] = eg*static_cast(ixpk); + ypk[ipk] = eg*static_cast(iypk); + + if(ic < nadc-1) { + for(int ii = ic+1; ii < nadc; ii++) { + ixy = ia[ii]; + ix = ixy/100; + iy = ixy - ix*100; + if(ixy-ixypk > 100+1) break; + if(abs(iy-iypk) <= 1) { + if(iter != 0) ratio = fwrk[ipk+1][ii]/fwrk[npk+1][ii]; + eg = ratio*static_cast(id[ii]); + epk[ipk] = epk[ipk] + eg; + xpk[ipk] = xpk[ipk] + eg*static_cast(ix); + ypk[ipk] = ypk[ipk] + eg*static_cast(iy); + } + } + } + + if(ic > 0) { + for(int ii = ic-1; ii >= 0; ii--) { + ixy = ia[ii]; + ix = ixy/100; + iy = ixy - ix*100; + if(ixypk-ixy > 100+1) break; + if(abs(iy-iypk) <= 1) { + if(iter != 0) ratio = fwrk[ipk+1][ii]/fwrk[npk+1][ii]; + eg = ratio*static_cast(id[ii]); + epk[ipk] = epk[ipk] + eg; + xpk[ipk] = xpk[ipk] + eg*static_cast(ix); + ypk[ipk] = ypk[ipk] + eg*static_cast(iy); + } + } + } + + if(epk[ipk] > 0.) { + xpk[ipk] = xpk[ipk]/epk[ipk]; + ypk[ipk] = ypk[ipk]/epk[ipk]; + } + + for(int ii = 0; ii < nadc; ii++) { + ixy = ia[ii]; + ix = ixy/100; + iy = ixy - ix*100; + dx = fabs( static_cast(ix) - xpk[ipk] ); + dy = fabs( static_cast(iy) - ypk[ipk] ); + + a = epk[ipk]*cell_hyc( dx, dy ); + + fwrk[ipk+1][ii] = a; + fwrk[0][ii] = fwrk[0][ii] + fwrk[ipk+1][ii]; + iwrk[ipk+1][ii] = static_cast(a + 0.5); + iwrk[0][ii] = iwrk[0][ii] + iwrk[ipk+1][ii]; + } + + } // end loop over peaks + + for(int ii = 0; ii < nadc; ii++) { + iwk = iwrk[0][ii]; + if( iwk < 1 ) iwk = 1; + iwrk[npk+1][ii] = iwk; + + if( fwrk[0][ii] > 1.e-2 ) + fwrk[npk+1][ii] = fwrk[0][ii]; + else + fwrk[npk+1][ii] = 1.e-2; + + } + } // end of iterations to separate peaks in a cluster + + if(SHOWER_DEBUG) { + cout << "\n\n\nAfter 6 iterations: " << endl; + for(int ipk = 0; ipk < npk; ipk++) { + cout << "peak " << ipk+1 << ": " << endl; + for(int jj = 0; jj < nadc; jj++) { + cout << ia[jj] <<"; "<< id[jj] <<"; "<< fwrk[ipk+1][jj] << endl; + } + } } - } - } - - if( nadcgam >= MADCGAM-1 ) return; - - - if( leng == 0 ) continue; - - nadcgam++; - - chisq = chisq2; - - ic = ipnpk[ipk]; - ix = ia[ic]/100; - iy = ia[ic] - ix*100; - - itype = peak_type( ix, iy ); - - e2 = 0.; - gamma_hyc( leng, iwrk_a, iwrk_d, chisq, - e1, x1, y1, e2, x2, y2 ); - - gamma_t gam1; - gamma_t gam2; - - gam1.type = itype+20; - gam1.dime = leng; - gam1.id = 10; - - gam1.chi2 = chisq; - gam1.energy = e1; - gam1.x = x1; - gam1.y = y1; - gam1.xc = 0.; - gam1.yc = 0.; - - if( e2 > 0. && nadcgam <= MADCGAM-1 ) { - nadcgam = nadcgam+1; - - gam2.type = itype+30; - gam2.dime = leng; - gam2.id = 12; - - gam2.chi2 = chisq; - gam2.energy = e2; - gam2.x = x2; - gam2.y = y2; - gam2.xc = 0.5*(x2-x1); - gam2.yc = 0.5*(y2-y1); - - gam1.type = itype+30; - gam1.id = 11; - gam1.xc = 0.5*(x1-x2); - gam1.yc = 0.5*(x1-x2); - - for( int jj = 0; jj < leng; jj++ ) { - if( jj < MAX_CC ) { - gam1.icl_in[jj] = iwrk_a[jj]; - gam2.icl_in[jj] = iwrk_a[jj]; - gam1.icl_en[jj] = static_cast( - static_cast(iwrk_d[jj])*e1/(e1+e2) + 0.5 ); - gam2.icl_en[jj] = static_cast( - static_cast(iwrk_d[jj])*e2/(e1+e2) + 0.5 ); + + for(int ipk = 0; ipk < npk; ipk++) { + + vector iwrk_a; + vector iwrk_d; + + leng = 0; + for(int ii = 0; ii < nadc; ii++) { + if(fwrk[0][ii] > 1.e-2) { + ixy = ia[ii]; + fe = static_cast(id[ii])*fwrk[ipk+1][ii]/fwrk[0][ii]; + + if(fe > idelta) { + leng = leng+1; + iwrk_a.push_back(ixy); + iwrk_d.push_back(static_cast(fe+0.5)); + } + + } + } + + if(nadcgam >= MADCGAM-1) return; + + igmpk[1][ipk] = 0; + if(leng == 0) continue; + nadcgam = nadcgam + 1; + chisq = chisq1; + + ic = ipnpk[ipk]; + ix = ia[ic]/100; + iy = ia[ic] - ix*100; + + itype = peak_type(ix, iy); + + e2 = 0.; + gamma_hyc(leng, iwrk_a, iwrk_d, chisq, + e1, x1, y1, e2, x2, y2); + + gamma_t gam1; + gamma_t gam2; + + gam1.chi2 = chisq; + gam1.type = itype+40; + gam1.energy = e1; + gam1.x = x1; + gam1.y = y1; + gam1.dime = leng; + + gam1.id = 90; + + igmpk[0][ipk] = nadcgam; + igmpk[1][ipk] = nadcgam; + + if(e2 > 0. && nadcgam <= MADCGAM-1) { + + nadcgam = nadcgam+1; + + gam2.chi2 = chisq; + gam2.type = itype+50; + gam2.energy = e2; + gam2.x = x2; + gam2.y = y2; + gam2.xc = 0.5*(x2-x1); + gam2.yc = 0.5*(y2-y1); + gam1.xc = 0.5*(x1-x2); + gam1.yc = 0.5*(y1-y2); + + gam2.id = 92; + gam1.id = 91; + + gam2.dime = leng; + igmpk[1][ipk] = nadcgam; + + gammas.push_back(gam1); + gammas.push_back(gam2); + + } else { gammas.push_back(gam1); } + + } // end loop over peaks + + + /* + This is the second step: ( 1 or 2 gamma in each peak ) + (e,x,y) of hits were preliminarily estimated in the first step. + */ + + for(int ii = 0; ii < nadc; ii++) { + iwrk[0][ii] = 0; + fwrk[0][ii] = 0.; + idp[0][ii] = 0; } - } - - gammas.push_back( gam1 ); - gammas.push_back( gam2 ); - - } else { - for( int jj = 0; jj < leng; jj++ ) { - if( jj < MAX_CC ) { - gam1.icl_in[jj] = iwrk_a[jj]; - gam1.icl_en[jj] = iwrk_d[jj]; - } - } - - gammas.push_back( gam1 ); - - } - - - } // end loop over peaks - - - + + for(int ipk = 0; ipk < npk; ipk++) { + for(int ii = 0; ii < nadc; ii++) { + iwrk[ipk+1][ii] = 0; + fwrk[ipk+1][ii] = 0.; + idp[ipk+1][ii] = 0; + + if(igmpk[1][ipk] == 0) continue; + + for(int ig = igmpk[0][ipk]; ig <= igmpk[1][ipk]; ig++) { + ixy = ia[ii]; + ix = ixy/100; + iy = ixy-(ix*100); + dx = static_cast(ix) - gammas[ig-1].x; + dy = static_cast(iy) - gammas[ig-1].y; + + fia = gammas[ig-1].energy*cell_hyc( dx, dy ); + iia = static_cast(fia+0.5); + + // part of gamma 'ig' energy belonging to cell 'i' from peak 'ipk': + iwrk[ipk+1][ii] += iia; + fwrk[ipk+1][ii] += fia; + idp[ipk+1][ii] += iia; + + iwrk[0][ii] += iia; + fwrk[0][ii] += fia; + } + + } // end loop over hits + } // end loop over peaks + + // Recover working array and renormalize total sum to the original cell energy: + + for(int ii = 0; ii < nadc; ii++) { + + idp[0][ii] = 0; + for(int ipk = 0; ipk < npk; ipk++) { + idp[0][ii] += idp[ipk+1][ii]; + } + + ide = id[ii] - idp[0][ii]; + if(ide == 0) continue; + if(fwrk[0][ii] == 0.) continue; + + for(int ipk = 0; ipk < npk; ipk++) { + fw[ipk+1] = fwrk[ipk+1][ii]/fwrk[0][ii]; + } + + idecorr = 0; + for(int ipk = 0; ipk < npk; ipk++) { + fia = ide*fw[ipk+1]; + if((fwrk[ipk+1][ii] + fia) > 0.) { + fwrk[ipk+1][ii] += fia; + fwrk[0][ii] += fia; + } + iia = static_cast(fia+0.5); + if((iwrk[ipk+1][ii] + iia) > 0) { + iwrk[ipk+1][ii] += iia; + iwrk[0][ii] += iia; + idecorr += iia; + } else if((iwrk[ipk+1][ii] + iia) < 0) { + //cout << "WARNING NEGATIVE CORR: " + // "ia = " << ia[ii] << "; id = " << id[ii] << endl; + } + } // end loop over peaks + + } // end loop over hits + + + // erase the gammas found in the previous step: + + nadcgam = ngam0; + gammas.erase(gammas.begin()+nadcgam, gammas.end()); + + for(int ipk = 0; ipk < npk; ipk++) { + leng = 0; + + vector iwrk_a; + vector iwrk_d; + + for(int ii = 0; ii < nadc; ii++){ + if(iwrk[0][ii] > 0) { + fe = id[ii]*fwrk[ipk+1][ii]/fwrk[0][ii]; + if(fe > idelta) { + leng++; + iwrk_a.push_back(ia[ii]); + iwrk_d.push_back(static_cast(fe+0.5)); + } + } + } + + if(nadcgam >= MADCGAM-1) return; + + if(leng == 0) continue; + + nadcgam++; + + chisq = chisq2; + + ic = ipnpk[ipk]; + ix = ia[ic]/100; + iy = ia[ic] - ix*100; + + itype = peak_type(ix, iy); + + e2 = 0.; + gamma_hyc(leng, iwrk_a, iwrk_d, chisq, + e1, x1, y1, e2, x2, y2); + + gamma_t gam1; + gamma_t gam2; + + gam1.type = itype+20; + gam1.dime = leng; + gam1.id = 10; + + gam1.chi2 = chisq; + gam1.energy = e1; + gam1.x = x1; + gam1.y = y1; + gam1.xc = 0.; + gam1.yc = 0.; + + if(e2 > 0. && nadcgam <= MADCGAM-1) { + nadcgam = nadcgam+1; + + gam2.type = itype+30; + gam2.dime = leng; + gam2.id = 12; + + gam2.chi2 = chisq; + gam2.energy = e2; + gam2.x = x2; + gam2.y = y2; + gam2.xc = 0.5*(x2-x1); + gam2.yc = 0.5*(y2-y1); + + gam1.type = itype+30; + gam1.id = 11; + gam1.xc = 0.5*(x1-x2); + gam1.yc = 0.5*(x1-x2); + + for(int jj = 0; jj < leng; jj++) { + if( jj < MAX_CC ) { + gam1.icl_in[jj] = iwrk_a[jj]; + gam2.icl_in[jj] = iwrk_a[jj]; + gam1.icl_en[jj] = static_cast( + static_cast(iwrk_d[jj])*e1/(e1+e2) + 0.5); + gam2.icl_en[jj] = static_cast( + static_cast(iwrk_d[jj])*e2/(e1+e2) + 0.5); + } + } + + gammas.push_back(gam1); + gammas.push_back(gam2); + + } else { + + for(int jj = 0; jj < leng; jj++) { + if( jj < MAX_CC ) { + gam1.icl_in[jj] = iwrk_a[jj]; + gam1.icl_en[jj] = iwrk_d[jj]; + } + } + + gammas.push_back(gam1); + } + + } // end loop over peaks + } // end looping over multi-peak cluster - - - - return; } - - - //========================================================== // // peak_type // //========================================================== -int DCCALShower_factory::peak_type( int ix, int iy ) +int DCCALShower_factory::peak_type(int ix, int iy) { /* itype = 2 : if the peak is in the most outer layer itype = 1 : if the peak is in the most inner layer itype = 0 : if the peak is anywhere else */ - + int itype = 0; if( (ix == MCOL/2-1 || ix == MCOL/2+2) && (iy >= MROW/2-1 && iy <= MROW/2+2) ) itype = 1; if( (iy == MROW/2-1 || iy == MROW/2+2) && (ix >= MCOL/2-1 && ix <= MCOL/2+2) ) itype = 1; if( ix == 1 || ix == MCOL || iy == 1 || iy == MROW ) itype = 2; - + return itype; } - - - //========================================================== // // gamma_hyc // //========================================================== -void DCCALShower_factory::gamma_hyc( int nadc, vector ia, vector id, double &chisq, - double &e1, double &x1, double &y1, - double &e2, double &x2, double &y2 ) +void DCCALShower_factory::gamma_hyc(int nadc, vector ia, vector id, double &chisq, + double &e1, double &x1, double &y1, + double &e2, double &x2, double &y2) { //-------------Local Declarations------------// @@ -1938,211 +1773,202 @@ void DCCALShower_factory::gamma_hyc( int nadc, vector ia, vector id, d x2 = 0.; y2 = 0.; + if(nadc <= 0) return; - fill_zeros( nadc, ia, nzero, iaz ); - mom1_pht( nadc, ia, id, nzero, iaz, e1, x1, y1 ); // calculate initial values of (E,x,y) + fill_zeros(nadc, ia, nzero, iaz); + mom1_pht(nadc, ia, id, nzero, iaz, e1, x1, y1); // calculate initial values of (E,x,y) - if( nadc <= 0 ) return; + if(e1 <= 0) return; chimem = chisq; - chisq1_hyc( nadc, ia, id, nzero, iaz, e1, x1, y1, chi0 ); // initial value of chi2 - + chisq1_hyc(nadc, ia, id, nzero, iaz, e1, x1, y1, chi0); // initial value of chi2 chisq0 = chi0; dof = nzero + nadc - 2; - if( dof < 1 ) dof = 1; + if(dof < 1) dof = 1; chisq = chi0/dof; x0 = x1; y0 = y1; - // start of iterations int rounds = 0; - while( 1 ) { - - chisq1_hyc( nadc, ia, id, nzero, iaz, e1, x0+dxy, y0, chir ); - chisq1_hyc( nadc, ia, id, nzero, iaz, e1, x0-dxy, y0, chil ); - chisq1_hyc( nadc, ia, id, nzero, iaz, e1, x0, y0+dxy, chiu ); - chisq1_hyc( nadc, ia, id, nzero, iaz, e1, x0, y0-dxy, chid ); - - if( chi0 > chir || chi0 > chil ) { - stepx = dxy; - if( chir > chil ) stepx = -stepx; - } else { - stepx = 0.; - parx = chir + chil - 2.*chi0; - if( parx > 0. ) stepx = -dxy*(chir-chil)/(2.*parx); - } - if( chi0 > chiu || chi0 > chid ) { - stepy = dxy; - if( chiu > chid ) stepy = -stepy; - } else { - stepy = 0.; - pary = chiu + chid - 2.*chi0; - if( pary > 0. ) stepy = -dxy*(chiu-chid)/(2.*pary); - } - - - // if steps at minimum, end iterations - - if( fabs(stepx) < stepmin && fabs(stepy) < stepmin ) break; - - chisq1_hyc( nadc, ia, id, nzero, iaz, e1, x0+stepx, y0+stepy, chi00 ); - - // if chi2 at minimum, end iterations - - if( chi00 >= chi0 ) break; - - chi0 = chi00; - x0 = x0+stepx; - y0 = y0+stepy; - - rounds++; - if( rounds > 10000 ) { cout << "max rounds" << endl; break; } - + while(1) { + + chisq1_hyc(nadc, ia, id, nzero, iaz, e1, x0+dxy, y0, chir); + chisq1_hyc(nadc, ia, id, nzero, iaz, e1, x0-dxy, y0, chil); + chisq1_hyc(nadc, ia, id, nzero, iaz, e1, x0, y0+dxy, chiu); + chisq1_hyc(nadc, ia, id, nzero, iaz, e1, x0, y0-dxy, chid); + + if(chi0 > chir || chi0 > chil) { + stepx = dxy; + if(chir > chil) stepx = -stepx; + } else { + stepx = 0.; + parx = chir + chil - 2.*chi0; + if(parx > 0.) stepx = -dxy*(chir-chil)/(2.*parx); + } + if(chi0 > chiu || chi0 > chid) { + stepy = dxy; + if(chiu > chid) stepy = -stepy; + } else { + stepy = 0.; + pary = chiu + chid - 2.*chi0; + if(pary > 0.) stepy = -dxy*(chiu-chid)/(2.*pary); + } + + // if steps at minimum, end iterations + + if(fabs(stepx) < stepmin && fabs(stepy) < stepmin) break; + + chisq1_hyc(nadc, ia, id, nzero, iaz, e1, x0+stepx, y0+stepy, chi00); + + // if chi2 at minimum, end iterations + + if(chi00 >= chi0) break; + + chi0 = chi00; + x0 = x0+stepx; + y0 = y0+stepy; + + rounds++; + if(rounds > 10000) { cout << "max rounds" << endl; break; } } - if( chi0 < chisq0 ) { // if chi2 improved, then fix the improved values - x1 = x0; - y1 = y0; - chisq = chi0/dof; + if(chi0 < chisq0) { // if chi2 improved, then fix the improved values + x1 = x0; + y1 = y0; + chisq = chi0/dof; } // if chi2 is less than maximum allowed for one gamma in a peak, return. // otherwise, try separating the peak into two gammas: - if( chisq <= chimem ) return; + if(chisq <= chimem) return; chiold = chisq; - tgamma_hyc( nadc, ia, id, nzero, iaz, chisq, ee, xx, yy, e2, x2, y2 ); - - if( e2 > 0. ) { // if chi2 improved, decide if the separation - // has physical meaning by calculating the - // effective mass of the two gammas - - d2 = pow((xx-x2)*xsize, 2.0) + pow((yy-y2)*ysize, 2.0); - xm2 = ee*e2*d2; - - if( xm2 > 0. ) xm2 = sqrt(xm2)/1270.*0.1; // mass in MeV; 1270 = zccal - - if( xm2 > xm2cut*xsize ) { // if the separation has physical meaning - e1 = ee; // fix the parameters of the first gamma - x1 = xx; - y1 = yy; - } else { // if no physical meaning e2=0 - e2 = 0.; // (second gamma is killed) - chisq = chiold; - } + tgamma_hyc(nadc, ia, id, nzero, iaz, chisq, ee, xx, yy, e2, x2, y2); + + if(e2 > 0.) { + // if chi2 improved, decide if the separation has physical meaning by calculating + // the effective mass of the two gammas: + + d2 = pow((xx-x2)*xsize, 2.0) + pow((yy-y2)*ysize, 2.0); + xm2 = ee*e2*d2; + + if(xm2 > 0.) xm2 = sqrt(xm2)/1270.*0.1; // mass in MeV; 1270 = zccal + + if(xm2 > xm2cut*xsize) { + // if the separation has physical meaning, fix the parameters of the first gamma: + e1 = ee; + x1 = xx; + y1 = yy; + } else { + // if no physical meaning e2=0 (second gamma is killed): + e2 = 0.; + chisq = chiold; + } } return; } - - - //========================================================== // // fill_zeros // //========================================================== -void DCCALShower_factory::fill_zeros( int nadc, vector ia, int &nneib, vector &iaz ) +void DCCALShower_factory::fill_zeros(int nadc, vector ia, int &nneib, vector &iaz) { - int ix, iy, nneibnew; vector ian; nneib = 0; - for( int ii = 0; ii < nadc; ii++ ) { - ix = ia[ii]/100; - iy = ia[ii] - ix*100; - - if( ix > 1 ) { // fill left neib - nneib = nneib+1; - ian.push_back(iy + (ix-1)*100); - - if( iy > 1 ) { // fill bottom left neib - nneib = nneib+1; - ian.push_back(iy-1 + (ix-1)*100); - } - if( iy < MROW ) { // fill top left neib - nneib = nneib+1; - ian.push_back(iy+1 + (ix-1)*100); - } - } - if( ix < MCOL ) { - nneib = nneib+1; - ian.push_back(iy + (ix+1)*100); - - if( iy > 1 ) { // fill bottom right neib - nneib = nneib+1; - ian.push_back(iy-1 + (ix+1)*100); - } - if( iy < MROW ) { // fill top right neib - nneib = nneib+1; - ian.push_back(iy+1 + (ix+1)*100); - } - } - - if( iy > 1 ) { // fill bottom neib - nneib = nneib+1; - ian.push_back(iy-1 + ix*100); - } - if( iy < MROW ) { // fill top neib - nneib = nneib+1; - ian.push_back(iy+1 + ix*100); - } + for(int ii = 0; ii < nadc; ii++) { + ix = ia[ii]/100; + iy = ia[ii] - ix*100; + + if(ix > 1) { // fill left neib + nneib = nneib+1; + ian.push_back(iy + (ix-1)*100); + + if(iy > 1) { // fill top left neib + nneib = nneib+1; + ian.push_back(iy-1 + (ix-1)*100); + } + if(iy < MROW) { // fill bottom left neib + nneib = nneib+1; + ian.push_back(iy+1 + (ix-1)*100); + } + } + if(ix < MCOL) { // fill right neib + nneib = nneib+1; + ian.push_back(iy + (ix+1)*100); + + if(iy > 1) { // fill top right neib + nneib = nneib+1; + ian.push_back(iy-1 + (ix+1)*100); + } + if(iy < MROW) { // fill bottom right neib + nneib = nneib+1; + ian.push_back(iy+1 + (ix+1)*100); + } + } + + if(iy > 1) { // fill top neib + nneib = nneib+1; + ian.push_back(iy-1 + ix*100); + } + if(iy < MROW) { // fill bottom neib + nneib = nneib+1; + ian.push_back(iy+1 + ix*100); + } } - for( int ii = 0; ii < nneib; ii++ ) { - for( int jj = 0; jj < nadc; jj++ ) { - if( ia[jj] == ian[ii] ) ian[ii] = -1; - } + for(int ii = 0; ii < nneib; ii++) { + for(int jj = 0; jj < nadc; jj++) { + if(ia[jj] == ian[ii]) ian[ii] = -1; + } } - for( int ii = 0; ii < nneib; ii++ ) { - if( ian[ii] == -1 ) continue; - for( int jj = ii+1; jj < nneib; jj++ ) { - if( ian[jj] == ian[ii] ) ian[jj] = -1; - } + for(int ii = 0; ii < nneib; ii++) { + if(ian[ii] == -1) continue; + for(int jj = ii+1; jj < nneib; jj++) { + if(ian[jj] == ian[ii]) ian[jj] = -1; + } } nneibnew = 0; - for( int ii = 0; ii < nneib; ii++ ) { - ix = ian[ii]/100; - iy = ian[ii] - ix*100; - if( ian[ii] != -1 ) { - if( stat_ch[iy-1][ix-1] == 0 ) { - nneibnew = nneibnew+1; - iaz.push_back( ian[ii] ); - } - } + for(int ii = 0; ii < nneib; ii++) { + ix = ian[ii]/100; + iy = ian[ii] - ix*100; + if(ian[ii] != -1) { + if(stat_ch[iy-1][ix-1] == 0) { + nneibnew = nneibnew+1; + iaz.push_back(ian[ii]); + } + } } nneib = nneibnew; - return; } - - - //========================================================== // // mom1_pht // //========================================================== -void DCCALShower_factory::mom1_pht( int nadc, vector ia, vector id, - int nzero, vector iaz, double &e1, double &x1, double &y1 ) +void DCCALShower_factory::mom1_pht(int nadc, vector ia, vector id, + int nzero, vector iaz, double &e1, double &x1, double &y1) { //-------------Local Declarations------------// - + int ix, iy; double dx, dy; @@ -2155,129 +1981,124 @@ void DCCALShower_factory::mom1_pht( int nadc, vector ia, vector id, x1 = 0.; y1 = 0.; - if( nadc <= 0 ) return; - for( int ii = 0; ii < nadc; ii++ ) { - a = static_cast(id[ii]); - ix = ia[ii]/100; - iy = ia[ii] - ix*100; - e1 = e1 + a; - x1 = x1 + a*static_cast(ix); - y1 = y1 + a*static_cast(iy); + if(nadc <= 0) return; + + for(int ii = 0; ii < nadc; ii++) { + a = static_cast(id[ii]); + ix = ia[ii]/100; + iy = ia[ii] - ix*100; + e1 = e1 + a; + x1 = x1 + a*static_cast(ix); + y1 = y1 + a*static_cast(iy); } - if( e1 <= 0. ) return; + + if(e1 <= 0.) return; + x1 = x1/e1; y1 = y1/e1; corr = 0.; - for( int ii = 0; ii < nadc; ii++ ) { - ix = ia[ii]/100; - iy = ia[ii] - ix*100; - dx = static_cast(ix) - x1; - dy = static_cast(iy) - y1; - corr = corr + cell_hyc( dx, dy ); + for(int ii = 0; ii < nadc; ii++) { + ix = ia[ii]/100; + iy = ia[ii] - ix*100; + dx = static_cast(ix) - x1; + dy = static_cast(iy) - y1; + corr = corr + cell_hyc( dx, dy ); } - if( COUNT_ZERO ) { - for( int ii = 0; ii < nzero; ii++ ) { - ix = iaz[ii]/100; - iy = iaz[ii] - ix*100; - dx = static_cast(ix) - x1; - dy = static_cast(iy) - y1; - corr = corr + cell_hyc( dx, dy ); - } + if(COUNT_ZERO) { + for(int ii = 0; ii < nzero; ii++) { + ix = iaz[ii]/100; + iy = iaz[ii] - ix*100; + dx = static_cast(ix) - x1; + dy = static_cast(iy) - y1; + corr = corr + cell_hyc( dx, dy ); + } } corr = corr/1.006; - if( SHOWER_DEBUG ) cout << "e, corr = " << e1 << ", " << corr << endl; + if(SHOWER_DEBUG) cout << "e, corr = " << e1 << ", " << corr << endl; - - if( corr < 0.8 ) { - if( SHOWER_DEBUG ) { - cout << "corr = " << corr << ", " << e1 << ", " << x1 << ", " << y1; - cout << "! Too many around central hole!" << endl; - } - corr = 0.8; - } else if( corr > 1.0 ) { - corr = 1.; + if(corr < 0.8) { + if(SHOWER_DEBUG) { + cout << "corr = " << corr << ", " << e1 << ", " << x1 << ", " << y1; + cout << "! Too many around central hole!" << endl; + } + corr = 0.8; + } else if(corr > 1.0) { + corr = 1.; } e1 = e1/corr; - return; } - - - //========================================================== // // chisq1_hyc // //========================================================== -void DCCALShower_factory::chisq1_hyc( int nadc, vector ia, vector id, - int nneib, vector iaz, double e1, double x1, double y1, double &chisq ) +void DCCALShower_factory::chisq1_hyc(int nadc, vector ia, vector id, + int nneib, vector iaz, double e1, double x1, double y1, double &chisq) { //-------------Local Declarations------------// - + int ix, iy; double dx, dy; double fa, fcell; - //--------------Event Analysis Code-------------// chisq = 0.; - for( int ii = 0; ii < nadc; ii++ ) { - fa = static_cast(id[ii]); - ix = ia[ii]/100; - iy = ia[ii] - ix*100; - dx = x1 - static_cast(ix); - dy = y1 - static_cast(iy); - if( e1 != 0. ) { - if( fabs(dx) <= 6.0 && fabs(dy) <= 6.0 ) { - fcell = cell_hyc( dx, dy ); - chisq = chisq + e1*pow((fcell-(fa/e1)), 2.)/sigma2(dx, dy, fcell, e1); - } - } else { - chisq = chisq + fa*fa/9.; - cout << "case 0 ch" << endl; - //if( SHOWER_DEBUG ) cout << "case 0 ch" << endl; - } + for(int ii = 0; ii < nadc; ii++) { + fa = static_cast(id[ii]); + ix = ia[ii]/100; + iy = ia[ii] - ix*100; + dx = x1 - static_cast(ix); + dy = y1 - static_cast(iy); + if(e1 != 0.) { + if(fabs(dx) <= 6.0 && fabs(dy) <= 6.0) { + fcell = cell_hyc( dx, dy ); + chisq = chisq + e1*pow((fcell-(fa/e1)), 2.)/sigma2(dx, dy, fcell, e1); + } + } else { + chisq = chisq + fa*fa/9.; + //if(SHOWER_DEBUG) cout << "case 0 ch" << endl; + } } - for(int ii = 0; ii < nneib; ii++ ) { - ix = iaz[ii]/100; - iy = iaz[ii] - ix*100; - dx = x1 - static_cast(ix); - dy = y1 - static_cast(iy); - if( e1 != 0. ) { - if( fabs(dx) < 6.0 && fabs(dy) < 6.0 ) { - fcell = cell_hyc( dx, dy ); - chisq = chisq + e1*fcell*fcell/sigma2(dx, dy, fcell, e1); - } - } else { - chisq = chisq + id[ii]*id[ii]/9.; - //if( SHOWER_DEBUG ) cout << "case 0 ch" << endl; - } + for(int ii = 0; ii < nneib; ii++) { + ix = iaz[ii]/100; + iy = iaz[ii] - ix*100; + dx = x1 - static_cast(ix); + dy = y1 - static_cast(iy); + if(e1 != 0.) { + if(fabs(dx) < 6.0 && fabs(dy) < 6.0) { + fcell = cell_hyc(dx, dy); + chisq = chisq + e1*fcell*fcell/sigma2(dx, dy, fcell, e1); + } + } + /* + else { + chisq = chisq + id[ii]*id[ii]/9.; + //if( SHOWER_DEBUG ) cout << "case 0 ch" << endl; + } + */ } - return; } - - - //========================================================== // // sigma2, d2c, & cell_hyc // //========================================================== -double DCCALShower_factory::sigma2( double dx, double dy, double fc, double e ) +double DCCALShower_factory::sigma2(double dx, double dy, double fc, double e) { double sig2; double alp = 0.816; @@ -2285,20 +2106,20 @@ double DCCALShower_factory::sigma2( double dx, double dy, double fc, double e ) double bet2 = 1.72; double r = dx*dx + dy*dy; - if( r > 25. ) { - sig2 = 100.; - return sig2; + if(r > 25.) { + sig2 = 100.; + return sig2; } - sig2 = alp*fc + (bet1 + bet2*sqrt(e/100.))*d2c( dx, dy ) + 0.2/(e/100.); - if( TEST_P ) sig2 = sig2/pow(0.0001*e, 0.166); + sig2 = alp*fc + (bet1 + bet2*sqrt(e/100.))*d2c(dx, dy) + 0.2/(e/100.); + if(TEST_P) sig2 = sig2/pow(0.0001*e, 0.166); sig2 *= 100.; - + return sig2; } -double DCCALShower_factory::d2c( double dx, double dy ) +double DCCALShower_factory::d2c(double dx, double dy) { int i, j; double ax, ay, wx, wy; @@ -2309,19 +2130,20 @@ double DCCALShower_factory::d2c( double dx, double dy ) i = int(ax); j = int(ay); - if( i < 499 && j < 499 && i >= 0 && j >= 0 ) { + if( (i < 499) && (j < 499) && (i >= 0) && (j >= 0) ) { //if( i < 500. && j < 500. ) { - - wx = ax-static_cast(i); - wy = ay-static_cast(j); - - d2c = ad2c[i][j] * (1.-wx) * (1.-wy) + - ad2c[i+1][j] * wx * (1.-wy) + - ad2c[i][j+1] * (1.-wx) * wy + - ad2c[i+1][j+1] * wx * wy; - + + wx = ax-static_cast(i); + wy = ay-static_cast(j); + + d2c = + ad2c[i][j] * (1.-wx) * (1.-wy) + + ad2c[i+1][j] * wx * (1.-wy) + + ad2c[i][j+1] * (1.-wx) * wy + + ad2c[i+1][j+1] * wx * wy; + } else d2c = 1.; - + return d2c; } @@ -2337,35 +2159,33 @@ double DCCALShower_factory::cell_hyc( double dx, double dy ) i = static_cast(ax); j = static_cast(ay); - if( i < 499 && j < 499 && i >= 0 && j >= 0 ) { - - wx = ax-static_cast(i); - wy = ay-static_cast(j); - //std::cout << "i " << i << " j " << j << " wx " << wx << " wy " << wy << std::endl; - cell_hyc = acell[i][j] * (1.-wx) * (1.-wy) + - acell[i+1][j] * wx * (1.-wy) + - acell[i][j+1] * (1.-wx) * wy + - acell[i+1][j+1] * wx * wy; - + if( (i < 499) && (j < 499) && (i >= 0) && (j >= 0) ) { + + wx = ax-static_cast(i); + wy = ay-static_cast(j); + //std::cout << "i " << i << " j " << j << " wx " << wx << " wy " << wy << std::endl; + + cell_hyc = + acell[i][j] * (1.-wx) * (1.-wy) + + acell[i+1][j] * wx * (1.-wy) + + acell[i][j+1] * (1.-wx) * wy + + acell[i+1][j+1] * wx * wy; + } else cell_hyc = 0.; - + return cell_hyc; } - - - //========================================================== // -// tgamma_hyc( int, vector, vector, int, vector, double, -// double, double, double, double, double, double ) +// tgamma_hyc // //========================================================== -void DCCALShower_factory::tgamma_hyc( int nadc, vector ia, vector id, +void DCCALShower_factory::tgamma_hyc(int nadc, vector ia, vector id, int nzero, vector iaz, double &chisq, double &e1, double &x1, double &y1, - double &e2, double &x2, double &y2 ) + double &e2, double &x2, double &y2) { //-------------- Local Declarations -------------// @@ -2415,195 +2235,190 @@ void DCCALShower_factory::tgamma_hyc( int nadc, vector ia, vector id, dx0 = 0.; dy0 = 0.; eps0 = 0.; - mom2_pht( nadc, ia, id, nzero, iaz, e0, x0, y0, xx, yy, yx ); - e2 = 0.; x2 = 0.; y2 = 0.; - if( nadc <= 0 ) return; + if(nadc <= 0) return; + + mom2_pht(nadc, ia, id, nzero, iaz, e0, x0, y0, xx, yy, yx); + + if(e0 <= 0) return; // choosing of the starting point dxy = xx - yy; rsq2 = dxy*dxy + 4.*yx*yx; - if( rsq2 < 1.e-20 ) rsq2 = 1.e-20; + if(rsq2 < 1.e-20) rsq2 = 1.e-20; rsq = sqrt(rsq2); dxc = -sqrt((rsq+dxy)*2.); dyc = sqrt((rsq-dxy)*2.); - if( yx >= 0. ) dyc = -dyc; + if(yx >= 0.) dyc = -dyc; r = sqrt(dxc*dxc + dyc*dyc); epsc = 0.; - for( int ii = 0; ii < nadc; ii++ ) { - ix = ia[ii]/100; - iy = ia[ii] - ix*100; - dx = static_cast(ix) - x0; - dy = static_cast(iy) - y0; - u = dx*dxc/r + dy*dyc/r; - epsc = epsc - 0.01*id[ii]*u*fabs(u); + for(int ii = 0; ii < nadc; ii++) { + ix = ia[ii]/100; + iy = ia[ii] - ix*100; + dx = static_cast(ix) - x0; + dy = static_cast(iy) - y0; + u = dx*dxc/r + dy*dyc/r; + epsc = epsc - 0.01*id[ii]*u*fabs(u); } - epsc = epsc/(0.01*e0*rsq); - if( epsc > 0.8 ) epsc = 0.8; - if( epsc < -0.8 ) epsc = -0.8; + if(rsq != 0) // e0 has been checked above + epsc = epsc/(0.01*e0*rsq); + if( epsc > 0.8) epsc = 0.8; + if(epsc < -0.8) epsc = -0.8; dxc = dxc/sqrt(1.-(epsc*epsc)); dyc = dyc/sqrt(1.-(epsc*epsc)); - - // start of iterations: step = 0.1; cosi = 0.0; chisq2 = 1.e35; - for( int iter = 0; iter < 100; iter++ ) { - - c3to5_pht( e0, x0, y0, epsc, dxc, dyc, e1c, x1c, y1c, e2c, x2c, y2c ); - - eps1 = (1. + epsc)/2.; - eps2 = (1. - epsc)/2.; - chisqc = 0.; - - for( int ii = 0; ii < nadc+nzero; ii++ ) { // chi2 calculation - - if( ii < nadc ) { - ex = static_cast(id[ii]); - ix = ia[ii]/100; - iy = ia[ii] - ix*100; - } else { - ex = 0.; - ix = iaz[ii-nadc]/100; - iy = iaz[ii-nadc] - ix*100; - } - - dx1 = x1c - static_cast(ix); - dy1 = y1c - static_cast(iy); - dx2 = x2c - static_cast(ix); - dy2 = y2c - static_cast(iy); - - f1c = cell_hyc( dx1, dy1 ); - f2c = cell_hyc( dx2, dy2 ); - - chisq2t_hyc( ex, e1c, dx1, dy1, e2c, dx2, dy2, f1c, f2c, chisqt ); - chisqc += chisqt; - - } - - if( chisqc >= chisq2 ) { // new step if no improvement - - if( iter > 0 ) { - dchi = chisqc - chisq2; - dchi0 = gr*step; - step = 0.5*step/sqrt(1. + dchi/dchi0); - } - step = 0.5*step; - - } else { // calculate gradient - - grec = 0.; - grxc = 0.; - gryc = 0.; - - for( int ii = 0; ii < nadc+nzero; ii++ ) { - - if( ii < nadc ) { - ex = static_cast(id[ii]); - ix = ia[ii]/100; - iy = ia[ii] - ix*100; - } else { - ex = 0.; - ix = iaz[ii-nadc]/100; - iy = iaz[ii-nadc] - ix*100; - } - - dx1 = x1c - static_cast(ix); - dy1 = y1c - static_cast(iy); - dx2 = x2c - static_cast(ix); - dy2 = y2c - static_cast(iy); - - f1c = cell_hyc( dx1, dy1 ); - f2c = cell_hyc( dx2, dy2 ); - - a1 = e1c*f1c; - a2 = e2c*f2c; - //a0 = a1 + a2; - - chisq2t_hyc( ex, e1c, dx1, dy1, e2c, dx2, dy2, f1c, f2c, chisqt0 ); - chisq2t_hyc( ex, e1c+1., dx1, dy1, e2c, dx2, dy2, f1c, f2c, chisqt1 ); - chisq2t_hyc( ex, e1c, dx1, dy1, e2c+1., dx2, dy2, f1c, f2c, chisqt2 ); - - f1x = cell_hyc( dx1+0.05, dy1 ); - f2x = cell_hyc( dx2+0.05, dy2 ); - f1y = cell_hyc( dx1, dy1+0.05 ); - f2y = cell_hyc( dx2, dy2+0.05 ); - - chisq2t_hyc( ex, e1c, dx1+0.05, dy1, e2c, dx2, dy2, f1x, f2c, chisqtx1 ); - chisq2t_hyc( ex, e1c, dx1, dy1, e2c, dx2+0.05, dy2, f1c, f2x, chisqtx2 ); - chisq2t_hyc( ex, e1c, dx1, dy1+0.05, e2c, dx2, dy2, f1y, f2c, chisqty1 ); - chisq2t_hyc( ex, e1c, dx1, dy1, e2c, dx2, dy2+0.05, f1c, f2y, chisqty2 ); - - dchidax1 = 20.*(chisqtx1 - chisqt0); - dchidax2 = 20.*(chisqtx2 - chisqt0); - dchiday1 = 20.*(chisqty1 - chisqt0); - dchiday2 = 20.*(chisqty2 - chisqt0); - dchida = 0.5*(chisqt1 + chisqt2 - chisqt0); - - gx1 = (e1c*f1x - a1)*dchidax1; - gx2 = (e2c*f2x - a2)*dchidax2; - gy1 = (e1c*f1y - a1)*dchiday1; - gy2 = (e2c*f2y - a2)*dchiday2; - - grec += dchida*(f1c-f2c)*e0 - ( (gx1+gx2)*dxc + (gy1+gy2)*dyc ); - grxc += gx1*eps2 - gx2*eps1; - gryc += gy1*eps2 - gy2*eps1; - - } - - grc = sqrt( grec*grec + grxc*grxc + gryc*gryc ); - if( grc < 1.e-6 ) grc = 1.e-6; - if( iter > 0 ) { - cosi = ( gre*grec + grx*grxc + gry*gryc )/(gr*grc); - scal = fabs((gr/grc) - cosi); - if( scal < 0.1 ) scal = 0.1; - step = step/scal; - } - chisq2 = chisqc; - eps0 = epsc; - dx0 = dxc; - dy0 = dyc; - gre = grec; - grx = grxc; - gry = gryc; - gr = grc; - } - epsc = eps0 - step*gre/gr; - while( fabs(epsc) > epsmax ) { - step = step/2.; - epsc = eps0 - step*gre/gr; - } - dxc = dx0 - step*grx/gr; - dyc = dy0 - step*gry/gr; - if( step*gr < stepmin ) break; + for(int iter = 0; iter < 100; iter++) { + + c3to5_pht(e0, x0, y0, epsc, dxc, dyc, e1c, x1c, y1c, e2c, x2c, y2c); + + eps1 = (1. + epsc)/2.; + eps2 = (1. - epsc)/2.; + chisqc = 0.; + + for(int ii = 0; ii < nadc+nzero; ii++) { // chi2 calculation + + if(ii < nadc) { + ex = static_cast(id[ii]); + ix = ia[ii]/100; + iy = ia[ii] - ix*100; + } else { + ex = 0.; + ix = iaz[ii-nadc]/100; + iy = iaz[ii-nadc] - ix*100; + } + + dx1 = x1c - static_cast(ix); + dy1 = y1c - static_cast(iy); + dx2 = x2c - static_cast(ix); + dy2 = y2c - static_cast(iy); + + f1c = cell_hyc(dx1, dy1); + f2c = cell_hyc(dx2, dy2); + + chisq2t_hyc(ex, e1c, dx1, dy1, e2c, dx2, dy2, f1c, f2c, chisqt); + chisqc += chisqt; + } + + if(chisqc >= chisq2) { // new step if no improvement + + if(iter > 0) { + dchi = chisqc - chisq2; + dchi0 = gr*step; + step = 0.5*step/sqrt(1. + dchi/dchi0); + } + step = 0.5*step; + + } else { // calculate gradient + + grec = 0.; + grxc = 0.; + gryc = 0.; + + for(int ii = 0; ii < nadc+nzero; ii++) { + + if(ii < nadc) { + ex = static_cast(id[ii]); + ix = ia[ii]/100; + iy = ia[ii] - ix*100; + } else { + ex = 0.; + ix = iaz[ii-nadc]/100; + iy = iaz[ii-nadc] - ix*100; + } + + dx1 = x1c - static_cast(ix); + dy1 = y1c - static_cast(iy); + dx2 = x2c - static_cast(ix); + dy2 = y2c - static_cast(iy); + + f1c = cell_hyc(dx1, dy1); + f2c = cell_hyc(dx2, dy2); + + a1 = e1c*f1c; + a2 = e2c*f2c; + //a0 = a1 + a2; + + chisq2t_hyc(ex, e1c, dx1, dy1, e2c, dx2, dy2, f1c, f2c, chisqt0); + chisq2t_hyc(ex, e1c+1., dx1, dy1, e2c, dx2, dy2, f1c, f2c, chisqt1); + chisq2t_hyc(ex, e1c, dx1, dy1, e2c+1., dx2, dy2, f1c, f2c, chisqt2); + + f1x = cell_hyc(dx1+0.05, dy1); + f2x = cell_hyc(dx2+0.05, dy2); + f1y = cell_hyc(dx1, dy1+0.05); + f2y = cell_hyc(dx2, dy2+0.05); + + chisq2t_hyc(ex, e1c, dx1+0.05, dy1, e2c, dx2, dy2, f1x, f2c, chisqtx1); + chisq2t_hyc(ex, e1c, dx1, dy1, e2c, dx2+0.05, dy2, f1c, f2x, chisqtx2); + chisq2t_hyc(ex, e1c, dx1, dy1+0.05, e2c, dx2, dy2, f1y, f2c, chisqty1); + chisq2t_hyc(ex, e1c, dx1, dy1, e2c, dx2, dy2+0.05, f1c, f2y, chisqty2); + + dchidax1 = 20.*(chisqtx1 - chisqt0); + dchidax2 = 20.*(chisqtx2 - chisqt0); + dchiday1 = 20.*(chisqty1 - chisqt0); + dchiday2 = 20.*(chisqty2 - chisqt0); + dchida = 0.5*(chisqt1 + chisqt2 - chisqt0); + + gx1 = (e1c*f1x - a1)*dchidax1; + gx2 = (e2c*f2x - a2)*dchidax2; + gy1 = (e1c*f1y - a1)*dchiday1; + gy2 = (e2c*f2y - a2)*dchiday2; + + grec += dchida*(f1c-f2c)*e0 - ((gx1+gx2)*dxc + (gy1+gy2)*dyc); + grxc += gx1*eps2 - gx2*eps1; + gryc += gy1*eps2 - gy2*eps1; + } + + grc = sqrt(grec*grec + grxc*grxc + gryc*gryc); + if(grc < 1.e-6) grc = 1.e-6; + if(iter > 0) { + cosi = (gre*grec + grx*grxc + gry*gryc)/(gr*grc); + scal = fabs((gr/grc) - cosi); + if(scal < 0.1) scal = 0.1; + step = step/scal; + } + chisq2 = chisqc; + eps0 = epsc; + dx0 = dxc; + dy0 = dyc; + gre = grec; + grx = grxc; + gry = gryc; + gr = grc; + } + epsc = eps0 - step*gre/gr; + while(fabs(epsc) > epsmax) { + step = step/2.; + epsc = eps0 - step*gre/gr; + } + dxc = dx0 - step*grx/gr; + dyc = dy0 - step*gry/gr; + if(step*gr < stepmin) break; } - if( (chisq*(nadc+nzero-2) - chisq2) < delch ) return; + if((chisq*(nadc+nzero-2) - chisq2) < delch) return; dof = nzero+nadc-5; - if( dof < 1 ) dof = 1; + if(dof < 1) dof = 1; chisq = chisq2/dof; - c3to5_pht( e0, x0, y0, eps0, dx0, dy0, e1, x1, y1, e2, x2, y2 ); + c3to5_pht(e0, x0, y0, eps0, dx0, dy0, e1, x1, y1, e2, x2, y2); return; } - - - //========================================================== // -// mom2_pht( int, vector, vector, int, vector, -// double, double, double, double, double, double ) +// mom2_pht // //========================================================== @@ -2612,7 +2427,7 @@ void DCCALShower_factory::mom2_pht( int nadc, vector ia, vector id, double &xx, double &yy, double &yx) { //-------------- Local Declarations --------------// - + int ix, iy; double dx, dy; double a; @@ -2627,74 +2442,71 @@ void DCCALShower_factory::mom2_pht( int nadc, vector ia, vector id, yy = 0.; yx = 0.; - if( nadc <= 0 ) return; - for( int ii = 0; ii < nadc; ii++ ) { - a = static_cast(id[ii]); - ix = ia[ii]/100; - iy = ia[ii] - ix*100; - a0 = a0 + a; - x0 = x0 + a*static_cast(ix); - y0 = y0 + a*static_cast(iy); + if(nadc <= 0) return; + + for(int ii = 0; ii < nadc; ii++) { + a = static_cast(id[ii]); + ix = ia[ii]/100; + iy = ia[ii] - ix*100; + a0 = a0 + a; + x0 = x0 + a*static_cast(ix); + y0 = y0 + a*static_cast(iy); } - if( a0 <= 0. ) return; + if(a0 <= 0.) return; + x0 = x0/a0; y0 = y0/a0; - for( int ii = 0; ii < nadc; ii++ ) { - a = static_cast(id[ii])/a0; - ix = ia[ii]/100; - iy = ia[ii] - ix*100; - dx = static_cast(ix) - x0; - dy = static_cast(iy) - y0; - xx = xx + a*dx*dx; - yy = yy + a*dy*dy; - yx = yx + a*dx*dy; + for(int ii = 0; ii < nadc; ii++) { + a = static_cast(id[ii])/a0; + ix = ia[ii]/100; + iy = ia[ii] - ix*100; + dx = static_cast(ix) - x0; + dy = static_cast(iy) - y0; + xx = xx + a*dx*dx; + yy = yy + a*dy*dy; + yx = yx + a*dx*dy; } corr = 0.; - for( int ii = 0; ii < nadc; ii++ ) { - ix = ia[ii]/100; - iy = ia[ii] - ix*100; - dx = static_cast(ix) - x0; - dy = static_cast(iy) - y0; - corr = corr + cell_hyc( dx, dy ); + for(int ii = 0; ii < nadc; ii++) { + ix = ia[ii]/100; + iy = ia[ii] - ix*100; + dx = static_cast(ix) - x0; + dy = static_cast(iy) - y0; + corr = corr + cell_hyc(dx, dy); } - if( COUNT_ZERO ) { - for( int ii = 0; ii < nzero; ii++ ) { - ix = iaz[ii]/100; - iy = iaz[ii] - ix*100; - dx = static_cast(ix) - x0; - dy = static_cast(iy) - y0; - corr = corr + cell_hyc( dx, dy ); - } + if(COUNT_ZERO) { + for(int ii = 0; ii < nzero; ii++) { + ix = iaz[ii]/100; + iy = iaz[ii] - ix*100; + dx = static_cast(ix) - x0; + dy = static_cast(iy) - y0; + corr = corr + cell_hyc(dx, dy); + } } corr = corr/1.006; - if( corr < 0.8 ) { - corr = 0.8; - } else if( corr > 1. ) { - corr = 1.0; + if(corr < 0.8) { + corr = 0.8; + } else if(corr > 1.) { + corr = 1.0; } a0 = a0/corr; - return; } - - - //========================================================== // -// c3to5_pht( double, double, double, double, double, double, -// double, double, double, double, double, double ) +// c3to5_pht // //========================================================== -void DCCALShower_factory::c3to5_pht( double e0, double x0, double y0, double eps, - double dx, double dy, double &e1, double &x1, double &y1, double &e2, - double &x2, double &y2 ) +void DCCALShower_factory::c3to5_pht(double e0, double x0, double y0, double eps, + double dx, double dy, double &e1, double &x1, double &y1, double &e2, + double &x2, double &y2) { e1 = e0*(1.+eps)/2.; e2 = e0 - e1; @@ -2707,128 +2519,89 @@ void DCCALShower_factory::c3to5_pht( double e0, double x0, double y0, double eps } - - - //========================================================== // -// chisq2t_hyc( double, double, double, double, double, double, -// double, double, double, double ) +// chisq2t_hyc // //========================================================== -void DCCALShower_factory::chisq2t_hyc( double ecell, double e1, double dx1, double dy1, - double e2, double dx2, double dy2, double f1, double f2, double &chisqt ) +void DCCALShower_factory::chisq2t_hyc(double ecell, double e1, double dx1, double dy1, + double e2, double dx2, double dy2, double f1, double f2, double &chisqt) { double s; double p1, p2; - if( TEST_P ) { - p1 = pow(0.0001*e1, 0.166); - p2 = pow(0.0001*e2, 0.166); + if(TEST_P) { + p1 = pow(0.0001*e1, 0.166); + p2 = pow(0.0001*e2, 0.166); } else { - p1 = 1.; - p2 = 1.; + p1 = 1.; + p2 = 1.; } - if( e1 != 0. && e2 != 0. ) - s = e1*sigma2(dx1, dy1, f1, e1)/p1 + e2*sigma2(dx2, dy2, f2, e2)/p2; - else if( e1 == 0. && e2 == 0. ) - s = 90000.; - else if( e1 == 0. ) - s = e2*sigma2(dx2, dy2, f2, e2)/p2; + if((e1 != 0.) && (e2 != 0.)) + s = e1*sigma2(dx1, dy1, f1, e1)/p1 + e2*sigma2(dx2, dy2, f2, e2)/p2; + else if((e1 == 0.) && (e2 == 0.)) + s = 90000.; + else if(e1 == 0.) + s = e2*sigma2(dx2, dy2, f2, e2)/p2; else - s = e1*sigma2(dx1, dy1, f1, e1)/p1; + s = e1*sigma2(dx1, dy1, f1, e1)/p1; chisqt = pow((e1*f1 + e2*f2 - ecell), 2.)/s; - + return; } - - - - //========================================================== // -// ucopy1( vector, vector, int, int ) +// ucopy1 // //========================================================== -void DCCALShower_factory::ucopy1( vector &ia, vector &iwork, int start, int length ) +void DCCALShower_factory::ucopy1(vector &ia, vector &iwork, int start, int length) { - for( int ii = 0; ii < length; ii++ ) { - iwork.push_back( ia[start+ii] ); + iwork.push_back( ia[start+ii] ); } - return; } - //========================================================== // -// ucopy2( vector, int, int, int ) +// ucopy2 // //========================================================== -void DCCALShower_factory::ucopy2( vector &ia, int start1, int start2, int length ) +void DCCALShower_factory::ucopy2(vector &ia, int start1, int start2, int length) { - vector work; for( int ii = 0; ii < length; ii++ ) { - work.push_back( ia[start1+ii] ); + work.push_back( ia[start1+ii] ); } for( int ii = 0; ii < length; ii++ ) { - ia[start2+ii] = work[ii]; + ia[start2+ii] = work[ii]; } - return; } - - //========================================================== // -// ucopy3( vector, vector, int, int ) +// ucopy3 // //========================================================== -void DCCALShower_factory::ucopy3( vector &iwork, vector &ia, int start, int length ) +void DCCALShower_factory::ucopy3(vector &iwork, vector &ia, int start, int length) { - for( int ii = 0; ii < length; ii++ ) { - ia[start+ii] = iwork[ii]; + ia[start+ii] = iwork[ii]; } - return; } - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/libraries/CCAL/DCCALShower_factory.h b/src/libraries/CCAL/DCCALShower_factory.h index 104938b533..966bfa3a2b 100644 --- a/src/libraries/CCAL/DCCALShower_factory.h +++ b/src/libraries/CCAL/DCCALShower_factory.h @@ -31,9 +31,8 @@ using namespace std; using namespace jana; - class DCCALShower_factory:public JFactory{ - + public: DCCALShower_factory(); ~DCCALShower_factory(){}; @@ -43,40 +42,35 @@ class DCCALShower_factory:public JFactory{ keep them simply public and static for now */ - private: - - JApplication *japp; - jerror_t brun(JEventLoop *eventLoop, int32_t runnumber); - jerror_t evnt(JEventLoop *eventLoop, uint64_t eventnumber); + JApplication *japp; + jerror_t brun(JEventLoop *eventLoop, int32_t runnumber); + jerror_t evnt(JEventLoop *eventLoop, uint64_t eventnumber); + void getHitPatterns(vector hitarray, + vector> &hitPatterns); - void getHitPatterns( vector< const DCCALHit* > hitarray, - vector< vector< const DCCALHit* > > &hitPatterns ); + void sortByTime(vector &hitarray, float hitTime); - void sortByTime( vector< const DCCALHit* > &hitarray, float hitTime ); + void cleanHitPattern(vector hitarray, + vector &hitarrayClean); - void cleanHitPattern( vector< const DCCALHit* > hitarray, - vector< const DCCALHit* > &hitarrayClean ); + void processShowers(vector gammas, DCCALGeometry ccalGeom, + vector locHitPattern, int eventnumber, + vector &ccalClusters, + vector &clusterStorage); - void processShowers( vector< gamma_t > gammas, DCCALGeometry ccalGeom, - vector< const DCCALHit* > locHitPattern, int eventnumber, - vector< ccalcluster_t > &ccalClusters, - vector< cluster_t > &clusterStorage ); + double getEnergyWeightedTime(cluster_t clusterStorage, int nHits); + double getCorrectedTime(double time, double energy); + double getShowerDepth(double energy); + double getCorrectedEnergy(double energy, int id); + double nonlin_func(double e, int id); - double getEnergyWeightedTime( cluster_t clusterStorage, int nHits ); - double getCorrectedTime( double time, double energy ); - double getShowerDepth( double energy ); - double getCorrectedEnergy( double energy, int id ); - double nonlin_func( double e, int id ); - - double m_zTarget; double m_CCALfront; double m_CCALdX,m_CCALdY; - //------------------- Nonlinearity & Timewalk Parameters -------------------// int CCAL_CHANS = DCCALGeometry::kCCALMaxChannels; @@ -90,91 +84,81 @@ class DCCALShower_factory:public JFactory{ vector< double > timewalk_p2; vector< double > timewalk_p3; - //----------------- Shower Profile Data & Channel Status -----------------// double acell[501][501] = { {0.} }; double ad2c[501][501] = { {0.} }; - int stat_ch[MROW][MCOL]; - - + int stat_ch[MROW][MCOL]; //----------------------- Island Functions -----------------------// + void main_island(vector &ia, vector &id, vector &gammas); - void main_island( vector &ia, vector &id, vector &gammas ); + int clus_hyc(int nw, vector &ia, vector &id, vector &lencl); - int clus_hyc( int nw, vector &ia, vector &id, vector &lencl ); + void order_hyc(int nw, vector &ia, vector &id); - void order_hyc( int nw, vector &ia, vector &id ); + void gams_hyc(int nadc, vector &ia, vector &id, int &nadcgam, + vector &gammas); - void gams_hyc( int nadc, vector &ia, vector &id, int &nadcgam, - vector &gammas ); - - int peak_type( int ix, int iy ); + int peak_type(int ix, int iy); - void gamma_hyc( int nadc, vector ia, vector id, double &chisq, - double &e1, double &x1, double &y1, - double &e2, double &x2, double &y2 ); - - void fill_zeros( int nadc, vector ia, int &nneib, vector &iaz ); + void gamma_hyc(int nadc, vector ia, vector id, double &chisq, + double &e1, double &x1, double &y1, + double &e2, double &x2, double &y2); - void mom1_pht( int nadc, vector ia, vector id, int nzero, - vector iaz, double &e1, double &x1, double &y1 ); - - void chisq1_hyc( int nadc, vector ia, vector id, int nneib, - vector iaz, double e1, double x1, double y1, double &chisq ); - - double sigma2( double dx, double dy, double fc, double e ); - double d2c( double x, double y ); - double cell_hyc( double dx, double dy ); + void fill_zeros(int nadc, vector ia, int &nneib, vector &iaz); - void tgamma_hyc( int nadc, vector ia, vector id, int nneib, - vector iaz, double &chisq, double &e1, double &x1, - double &y1, double &e2, double &x2, double &y2 ); - - void mom2_pht( int nadc, vector ia, vector id, int nzero, - vector iaz, double &a0, double &x0, double &y0, - double &xx, double &yy, double &yx ); - - void c3to5_pht( double e0, double x0, double y0, double eps, double dx, - double dy, double &e1, double &x1, double &y1, double &e2, - double &x2, double &y2 ); - - void chisq2t_hyc( double ecell, double e1c, double dx1, double dy1, - double e2c, double dx2, double dy2, double f1c, - double f2c, double &chisqt ); - - void ucopy1( vector &ia, vector &iwork, int start, int length ); - void ucopy2( vector &ia, int start1, int start2, int length ); - void ucopy3( vector &iwork, vector &ia, int start, int length ); - + void mom1_pht(int nadc, vector ia, vector id, int nzero, + vector iaz, double &e1, double &x1, double &y1); + void chisq1_hyc(int nadc, vector ia, vector id, int nneib, + vector iaz, double e1, double x1, double y1, double &chisq); + double sigma2(double dx, double dy, double fc, double e); + double d2c(double x, double y); + double cell_hyc(double dx, double dy); + void tgamma_hyc(int nadc, vector ia, vector id, int nneib, + vector iaz, double &chisq, double &e1, double &x1, + double &y1, double &e2, double &x2, double &y2); + void mom2_pht(int nadc, vector ia, vector id, int nzero, + vector iaz, double &a0, double &x0, double &y0, + double &xx, double &yy, double &yx); - //---------------------- Default Parameters ----------------------// + void c3to5_pht(double e0, double x0, double y0, double eps, double dx, + double dy, double &e1, double &x1, double &y1, double &e2, + double &x2, double &y2); + + void chisq2t_hyc(double ecell, double e1c, double dx1, double dy1, + double e2c, double dx2, double dy2, double f1c, + double f2c, double &chisqt); - int SHOWER_DEBUG; - int MIN_CLUSTER_BLOCK_COUNT; - double MIN_CLUSTER_SEED_ENERGY; - double MIN_CLUSTER_ENERGY; - double MAX_CLUSTER_ENERGY; - double TIME_CUT; - int MAX_HITS_FOR_CLUSTERING; - int DO_NONLINEAR_CORRECTION; + void ucopy1(vector &ia, vector &iwork, int start, int length); + void ucopy2(vector &ia, int start1, int start2, int length); + void ucopy3(vector &iwork, vector &ia, int start, int length); - double CCAL_RADIATION_LENGTH; - double CCAL_CRITICAL_ENERGY; + //---------------------- Default Parameters ----------------------// - double LOG_POS_CONST; + int VERBOSE; + int SHOWER_DEBUG; + int MIN_CLUSTER_BLOCK_COUNT; + double MIN_CLUSTER_SEED_ENERGY; + double MIN_CLUSTER_ENERGY; + double MAX_CLUSTER_ENERGY; + double TIME_CUT; + int MAX_HITS_FOR_CLUSTERING; + int DO_NONLINEAR_CORRECTION; + int DO_TIMEWALK_CORRECTION; + double CCAL_RADIATION_LENGTH; + double CCAL_CRITICAL_ENERGY; + double LOG_POS_CONST; - int VERBOSE; + double CCAL_C_EFFECTIVE; }; #endif // _DCCALShower_factory_ - diff --git a/src/libraries/CCAL/DCCALTruthShower.h b/src/libraries/CCAL/DCCALTruthShower.h index b1d187a4b5..e192ef7d49 100644 --- a/src/libraries/CCAL/DCCALTruthShower.h +++ b/src/libraries/CCAL/DCCALTruthShower.h @@ -18,25 +18,25 @@ class DCCALTruthShower:public jana::JObject{ DCCALTruthShower(){} DCCALTruthShower( oid_t id, - float x, float y, float z, - float px, float py, float pz, - float E, float t, - bool primary, int track, int type, - int itrack=0) : - JObject( id ), - m_x( x ), - m_y( y ), - m_z( z ), - m_px( px ), - m_py( py ), - m_pz( pz ), - m_E( E ), - m_t( t ), - m_primary(primary), - m_track(track), - m_type(type), - m_itrack(itrack){} - + float x, float y, float z, + float px, float py, float pz, + float E, float t, + bool primary, int track, int type, + int itrack=0) : + JObject( id ), + m_x( x ), + m_y( y ), + m_z( z ), + m_px( px ), + m_py( py ), + m_pz( pz ), + m_E( E ), + m_t( t ), + m_primary(primary), + m_track(track), + m_type(type), + m_itrack(itrack){} + float x() const { return m_x; } float y() const { return m_y; } float z() const { return m_z; } @@ -49,7 +49,7 @@ class DCCALTruthShower:public jana::JObject{ int track() const { return m_track; } int type() const { return m_type; } int itrack() const { return m_itrack; } - + void toStrings(vector > &items)const{ AddString(items, "x(cm)", "%3.1f", x()); AddString(items, "y(cm)", "%3.1f", y()); @@ -64,7 +64,7 @@ class DCCALTruthShower:public jana::JObject{ AddString(items, "type", "%d", type()); AddString(items, "itrack", "%d", itrack()); } - + private: float m_x; diff --git a/src/libraries/CCAL/DCCALTruthShower_factory.cc b/src/libraries/CCAL/DCCALTruthShower_factory.cc index 263ed05ba1..06a641b4f8 100644 --- a/src/libraries/CCAL/DCCALTruthShower_factory.cc +++ b/src/libraries/CCAL/DCCALTruthShower_factory.cc @@ -34,7 +34,7 @@ jerror_t DCCALTruthShower_factory::brun(jana::JEventLoop *eventLoop, int32_t run //------------------ jerror_t DCCALTruthShower_factory::evnt(JEventLoop *loop, uint64_t eventnumber) { - + // Code to generate factory data goes here. Add it like: // // DCCALTruthShower *myDCCALTruthShower = new DCCALTruthShower; @@ -45,7 +45,7 @@ jerror_t DCCALTruthShower_factory::evnt(JEventLoop *loop, uint64_t eventnumber) // // Note that the objects you create here will be deleted later // by the system and the _data vector will be cleared automatically. - + return NOERROR; } diff --git a/src/libraries/CCAL/DCCALTruthShower_factory.h b/src/libraries/CCAL/DCCALTruthShower_factory.h index c780a6f1be..237e42b6fe 100644 --- a/src/libraries/CCAL/DCCALTruthShower_factory.h +++ b/src/libraries/CCAL/DCCALTruthShower_factory.h @@ -15,14 +15,13 @@ class DCCALTruthShower_factory:public jana::JFactory{ public: DCCALTruthShower_factory(){}; ~DCCALTruthShower_factory(){}; - - + private: - jerror_t init(void); ///< Called once at program start. - jerror_t brun(jana::JEventLoop *eventLoop, int32_t runnumber); ///< Called everytime a new run number is detected. - jerror_t evnt(jana::JEventLoop *eventLoop, uint64_t eventnumber); ///< Called every event. - jerror_t erun(void); ///< Called everytime run number changes, provided brun has been called. - jerror_t fini(void); ///< Called after last event of last event source has been processed. + jerror_t init(void); + jerror_t brun(jana::JEventLoop *eventLoop, int32_t runnumber); + jerror_t evnt(jana::JEventLoop *eventLoop, uint64_t eventnumber); + jerror_t erun(void); + jerror_t fini(void); }; #endif // _DCCALTruthShower_factory_ diff --git a/src/libraries/CCAL/ccal.h b/src/libraries/CCAL/ccal.h index fed54bc27f..364c223bd8 100644 --- a/src/libraries/CCAL/ccal.h +++ b/src/libraries/CCAL/ccal.h @@ -1,8 +1,6 @@ #ifndef _CCAL_H_ #define _CCAL_H_ - - #define MCOL 12 #define MROW 12 @@ -17,8 +15,6 @@ #define COUNT_ZERO 1 #define TEST_P 1 - - enum ClusterType_t{ SinglePeak=0, MultiPeak @@ -30,57 +26,55 @@ enum PeakType_t{ }; - typedef struct { + + int id[MAX_CC]; /* ID of ith block, where i runs from 0 to 8 */ + double E[MAX_CC]; /* Energy of ith block */ + double x[MAX_CC]; /* Center of ith block x-coord */ + double y[MAX_CC]; /* Center of ith block y-coord */ + double t[MAX_CC]; + +} cluster_t; - int id[MAX_CC]; /* ID of ith block, where i runs from 0 to 8 */ - double E[MAX_CC]; /* Energy of ith block */ - double x[MAX_CC]; /* Center of ith block x-coord */ - double y[MAX_CC]; /* Center of ith block y-coord */ - double t[MAX_CC]; -} cluster_t; - - typedef struct { - - int type; /* cluster types: 0,1,2,10,11,12 */ - int nhits; /* Number of hits in cluster */ - int id; /* Indicates multiple gammas in same peak */ - int idmax; /* Cluster's central cell's ID */ - - double E; /* Cluster's energy [GeV] */ - double Esum; /* Cluster energy calculated as sum of blocks' energies [GeV] */ - double x; /* Cluster's x-position [cm] */ - double y; /* Cluster's y-position [cm] */ - double x1; /* Cluster's x1-position [cm] */ - double y1; /* Cluster's y1-position [cm] */ - double chi2; /* Cluster's profile fit to single shower profile */ - double time; /* Cluster's time [ns] */ - double sigma_E; - double emax; - + + int type; /* cluster types: 0,1,2,10,11,12 */ + int nhits; /* Number of hits in cluster */ + int id; /* Indicates multiple gammas in same peak */ + int idmax; /* Cluster's central cell's ID */ + + double E; /* Cluster's energy [GeV] */ + double Esum; /* Cluster energy calculated as sum of blocks' energies [GeV] */ + double x; /* Cluster's x-position [cm] */ + double y; /* Cluster's y-position [cm] */ + double x1; /* Cluster's x1-position [cm] */ + double y1; /* Cluster's y1-position [cm] */ + double z; /* Cluster's z-position [cm] */ + double chi2; /* Cluster's profile fit to single shower profile */ + double time; /* Cluster's time [ns] */ + double sigma_E; + double emax; + } ccalcluster_t; - - -typedef struct { - - int type; - int dime; - int id; - - double chi2; - double energy; - double x; - double y; - double xc; - double yc; - - int icl_in[MAX_CC]; - int icl_en[MAX_CC]; - -} gamma_t; +typedef struct { + + int type; + int dime; + int id; + + double chi2; + double energy; + double x; + double y; + double xc; + double yc; + + int icl_in[MAX_CC]; + int icl_en[MAX_CC]; + +} gamma_t; #endif diff --git a/src/libraries/CDC/DCDCHit_factory_Calib.cc b/src/libraries/CDC/DCDCHit_factory_Calib.cc index 614d93c646..71e8d2d274 100644 --- a/src/libraries/CDC/DCDCHit_factory_Calib.cc +++ b/src/libraries/CDC/DCDCHit_factory_Calib.cc @@ -6,21 +6,8 @@ // -#include -#include -using namespace std; - - #include -#include -#include -#include -#include -#include - -using namespace jana; -int CDC_HIT_THRESHOLD = 0; //#define ENABLE_UPSAMPLING @@ -30,6 +17,7 @@ int CDC_HIT_THRESHOLD = 0; jerror_t DCDCHit_factory_Calib::init(void) { + CDC_HIT_THRESHOLD = 0; gPARMS->SetDefaultParameter("CDC:CDC_HIT_THRESHOLD", CDC_HIT_THRESHOLD, "Remove CDC Hits with peak amplitudes smaller than CDC_HIT_THRESHOLD"); diff --git a/src/libraries/CDC/DCDCHit_factory_Calib.h b/src/libraries/CDC/DCDCHit_factory_Calib.h index d6d815161c..244e9ac86e 100644 --- a/src/libraries/CDC/DCDCHit_factory_Calib.h +++ b/src/libraries/CDC/DCDCHit_factory_Calib.h @@ -8,19 +8,21 @@ #ifndef _DCDCHit_factory_Calib_ #define _DCDCHit_factory_Calib_ +#include +#include #include -using namespace std; - #include #include #include #include #include #include +#include +#include +#include "CDC/DCDCHit.h" -#include "DCDCHit.h" -#include "DCDCDigiHit.h" -#include "DCDCWire.h" +using namespace std; +using namespace jana; // store constants indexed by ring/straw number typedef vector< vector > cdc_digi_constants_t; @@ -31,6 +33,8 @@ class DCDCHit_factory_Calib:public jana::JFactory{ ~DCDCHit_factory_Calib(){}; const char* Tag(void){return "Calib";} + int CDC_HIT_THRESHOLD; + // overall scale factors. double a_scale, amp_a_scale; double t_scale; diff --git a/src/libraries/DANA/DFactoryGenerator.cc b/src/libraries/DANA/DFactoryGenerator.cc index 3bc48fe73d..5c4dd5a617 100644 --- a/src/libraries/DANA/DFactoryGenerator.cc +++ b/src/libraries/DANA/DFactoryGenerator.cc @@ -13,6 +13,7 @@ extern jerror_t BCAL_init(JEventLoop *loop); extern jerror_t CDC_init(JEventLoop *loop); extern jerror_t FDC_init(JEventLoop *loop); extern jerror_t FCAL_init(JEventLoop *loop); +extern jerror_t ECAL_init(JEventLoop *loop); extern jerror_t CCAL_init(JEventLoop *loop); extern jerror_t RF_init(JEventLoop *loop); extern jerror_t START_COUNTER_init(JEventLoop *loop); @@ -59,6 +60,7 @@ jerror_t DFactoryGenerator::GenerateFactories(JEventLoop *loop) CDC_init(loop); FDC_init(loop); FCAL_init(loop); + ECAL_init(loop); CCAL_init(loop); RF_init(loop); START_COUNTER_init(loop); diff --git a/src/libraries/ECAL/DECALDigiHit.h b/src/libraries/ECAL/DECALDigiHit.h new file mode 100644 index 0000000000..c3487826fc --- /dev/null +++ b/src/libraries/ECAL/DECALDigiHit.h @@ -0,0 +1,44 @@ +// $Id$ +// +// File: DECALDigiHit.h + +#ifndef _DECALDigiHit_ +#define _DECALDigiHit_ + +#include +#include + +class DECALDigiHit:public jana::JObject{ + public: + JOBJECT_PUBLIC(DECALDigiHit); + + int row; + int column; + uint32_t pulse_integral; ///< identified pulse integral as returned by FPGA algorithm + uint32_t pulse_time; ///< identified pulse time as returned by FPGA algorithm + uint32_t pedestal; ///< pedestal info used by FPGA (if any) + uint32_t QF; ///< Quality Factor from FPGA algorithms + uint32_t nsamples_integral; ///< number of samples used in integral + uint32_t nsamples_pedestal; ///< number of samples used in pedestal + uint32_t pulse_peak; ///< maximum sample in pulse + + uint32_t datasource; ///< 0=window raw data, 1=old(pre-Fall16) firmware, 2=Df250PulseData + + // This method is used primarily for pretty printing + // the second argument to AddString is printf style format + void toStrings(vector > &items)const{ + AddString(items, "row", "%4d", row); + AddString(items, "column", "%4d", column); + AddString(items, "pulse_integral", "%d", pulse_integral); + AddString(items, "pulse_peak", "%d", pulse_peak); + AddString(items, "pulse_time", "%d", pulse_time); + AddString(items, "pedestal", "%d", pedestal); + AddString(items, "QF", "%d", QF); + AddString(items, "nsamples_integral", "%d", nsamples_integral); + AddString(items, "nsamples_pedestal", "%d", nsamples_pedestal); + } + +}; + +#endif // _DECALDigiHit_ + diff --git a/src/libraries/ECAL/DECALGeometry.cc b/src/libraries/ECAL/DECALGeometry.cc new file mode 100644 index 0000000000..1ece9034db --- /dev/null +++ b/src/libraries/ECAL/DECALGeometry.cc @@ -0,0 +1,102 @@ +// $Id$ +// +/* + * File: DECALHit_factory.h + * + * Created on 01/16/2024 by A.S. + */ + + +#include +#include +using namespace std; + +#include "DECALGeometry.h" +#include "DVector2.h" + +//--------------------------------- +// DECALGeometry (Constructor) +//--------------------------------- +DECALGeometry::DECALGeometry() : + m_numActiveBlocks( 0 ){ + + for( int row = 0; row < kECALBlocksTall; row++ ){ + for( int col = 0; col < kECALBlocksWide; col++ ){ + + // transform to beam axis + m_positionOnFace[row][col] = + DVector2( ( (double)col - kECALMidBlock + 0.5 ) * blockSize(), + ( (double)row - kECALMidBlock + 0.5 ) * blockSize() ); + + m_activeBlock[row][col] = true; + + // build the "channel map" + m_channelNumber[row][col] = m_numActiveBlocks; + m_row[m_numActiveBlocks] = row; + m_column[m_numActiveBlocks] = col; + + m_numActiveBlocks++; + } + } +} + +bool +DECALGeometry::isBlockActive( int row, int column ) const +{ + // I'm inserting these lines to effectively disable the + // two assert calls below. They are causing all programs + // (hd_dump, hdview) to exit, even when I'm not interested + // in the FCAL. This does not fix the underlying problem + // of why we're getting invalid row/column values. + // 12/13/05 DL + if( row < 0 || row >= kECALBlocksTall )return false; + if( column < 0 || column >= kECALBlocksWide )return false; + + assert( row >= 0 && row < kECALBlocksTall ); + assert( column >= 0 && column < kECALBlocksWide ); + + return m_activeBlock[row][column]; +} + +int +DECALGeometry::row( float y ) const +{ + return static_cast( y / blockSize() + kECALMidBlock ); +} + +int +DECALGeometry::column( float x ) const +{ + return static_cast( x / blockSize() + kECALMidBlock ); +} + +DVector2 +DECALGeometry::positionOnFace( int row, int column ) const +{ + assert( row >= 0 && row < kECALBlocksTall ); + assert( column >= 0 && column < kECALBlocksWide ); + + return m_positionOnFace[row][column]; +} + +DVector2 +DECALGeometry::positionOnFace( int channel ) const +{ + assert( channel >= 0 && channel < m_numActiveBlocks ); + + return positionOnFace( m_row[channel], m_column[channel] ); +} + +int +DECALGeometry::channel( int row, int column ) const +{ + if( isBlockActive( row, column ) ){ + + return m_channelNumber[row][column]; + } + else{ + + cerr << "ERROR: request for channel number of inactive block!" << endl; + return -1; + } +} diff --git a/src/libraries/ECAL/DECALGeometry.h b/src/libraries/ECAL/DECALGeometry.h new file mode 100644 index 0000000000..8a82c92163 --- /dev/null +++ b/src/libraries/ECAL/DECALGeometry.h @@ -0,0 +1,73 @@ +// $Id$ +// +// File: DECALGeometry.h +// Created: Tue Nov 30 15:42:41 EST 2010 +// Creator: davidl (on Linux ifarml6 2.6.18-128.el5 x86_64) +// + +#ifndef _DECALGeometry_ +#define _DECALGeometry_ + +#include +#include + +#include "DVector2.h" +#include "units.h" + +class DECALGeometry:public jana::JObject{ + + public: + JOBJECT_PUBLIC(DECALGeometry); + + DECALGeometry(); + ~DECALGeometry(){} + + static const int kECALBlocksWide = 40; + static const int kECALBlocksTall = 40; + static const int kECALMaxChannels = kECALBlocksWide * kECALBlocksTall; + static const int kECALMidBlock = (kECALBlocksWide)/2; + static const int kECALBeamHoleSize = 2; + + static double blockSize() { return 2.09 * k_cm; } + static double blockLength(){ return 20.0 * k_cm; } + static double ecalFaceZ() { return 1279.376 * k_cm; } + + static double ecalMidplane() { return ecalFaceZ() + 0.5 * blockLength() ; } + + bool isBlockActive( int row, int column ) const; + int numActiveBlocks() const { return m_numActiveBlocks; } + + + DVector2 positionOnFace( int row, int column ) const; + DVector2 positionOnFace( int channel ) const; + + int channel( int row, int column ) const; + + int row ( int channel ) const { return m_row[channel]; } + int column( int channel ) const { return m_column[channel]; } + + // get row and column from x and y positions + int row ( float y ) const; + int column( float x ) const; + + void toStrings(vector > &items)const{ + AddString(items, "kECALBlocksWide", "%d", (int) kECALBlocksWide); + AddString(items, "kECALBlocksTall", "%d", (int) kECALBlocksTall); + AddString(items, "kECALMaxChannels", "%d",(int) kECALMaxChannels); + AddString(items, "kECALBeamHoleSize", "%2.3f",(int) kECALBeamHoleSize); + } + + private: + + bool m_activeBlock[kECALBlocksTall][kECALBlocksWide]; + DVector2 m_positionOnFace[kECALBlocksTall][kECALBlocksWide]; + + int m_channelNumber[kECALBlocksTall][kECALBlocksWide]; + int m_row[kECALMaxChannels]; + int m_column[kECALMaxChannels]; + + int m_numActiveBlocks; +}; + +#endif // _DECALGeometry_ + diff --git a/src/libraries/ECAL/DECALGeometry_factory.h b/src/libraries/ECAL/DECALGeometry_factory.h new file mode 100644 index 0000000000..750fb957c9 --- /dev/null +++ b/src/libraries/ECAL/DECALGeometry_factory.h @@ -0,0 +1,60 @@ +// $Id$ +/* + * File: DECALHit_factory.h + * + * Created on 01/16/2024 by A.S. + */ + +#ifndef _DECALGeometry_factory_ +#define _DECALGeometry_factory_ + +#include +#include "DECALGeometry.h" + +class DECALGeometry_factory:public jana::JFactory{ + public: + DECALGeometry_factory(){}; + ~DECALGeometry_factory(){}; + + DECALGeometry *ecalgeometry = nullptr; + + //------------------ + // brun + //------------------ + jerror_t brun(JEventLoop *loop, int32_t runnumber) + { + SetFactoryFlag(NOT_OBJECT_OWNER); + ClearFactoryFlag(WRITE_TO_OUTPUT); + + if( ecalgeometry ) delete ecalgeometry; + + ecalgeometry = new DECALGeometry(); + + return NOERROR; + } + + //------------------ + // evnt + //------------------ + jerror_t evnt(JEventLoop *loop, uint64_t eventnumber) + { + // Reuse existing DBCALGeometry object. + if( ecalgeometry ) _data.push_back( ecalgeometry ); + + return NOERROR; + } + + //------------------ + // erun + //------------------ + jerror_t erun(void) + { + if( ecalgeometry ) delete ecalgeometry; + ecalgeometry = NULL; + + return NOERROR; + } +}; + +#endif // _DECALGeometry_factory_ + diff --git a/src/libraries/ECAL/DECALHit.h b/src/libraries/ECAL/DECALHit.h new file mode 100644 index 0000000000..972c86c0df --- /dev/null +++ b/src/libraries/ECAL/DECALHit.h @@ -0,0 +1,43 @@ +/* + * File: DECALHit.h + * + * Created on 01/16/2024 by A.S. + */ + + +#ifndef _DECALHit_ +#define _DECALHit_ + +#include +#include +using namespace jana; + +class DECALHit:public jana::JObject{ + public: + + JOBJECT_PUBLIC(DECALHit); + + DECALHit(){} + + int row; + int column; + float x; + float y; + float E; + float t; + float intOverPeak; + + + void toStrings(vector > &items)const{ + AddString(items, "row", "%4d", row); + AddString(items, "column", "%4d", column); + AddString(items, "x(cm)", "%3.1f", x); + AddString(items, "y(cm)", "%3.1f", y); + AddString(items, "E(MeV)", "%2.3f", E); + AddString(items, "t(ns)", "%2.3f", t); + AddString(items, "integral over peak", "%2.3f", intOverPeak); + } +}; + +#endif // _DECALHit_ + diff --git a/src/libraries/ECAL/DECALHit_factory.cc b/src/libraries/ECAL/DECALHit_factory.cc new file mode 100644 index 0000000000..cab0ff8cdb --- /dev/null +++ b/src/libraries/ECAL/DECALHit_factory.cc @@ -0,0 +1,346 @@ +/* + * File: DECALHit_factory.cc + * + * Created on 01/16/2024 by A.S. + */ + +#include +#include +using namespace std; + +#include "ECAL/DECALDigiHit.h" +#include "ECAL/DECALGeometry.h" +#include "ECAL/DECALHit_factory.h" + +#include "DAQ/Df250PulseIntegral.h" +#include "DAQ/Df250PulsePedestal.h" + +#include "DAQ/Df250Config.h" +#include "TTAB/DTTabUtilities.h" + +using namespace jana; + +//---------------- +// Constructor +//---------------- +DECALHit_factory::DECALHit_factory(){ + + HIT_DEBUG = 0; + DB_PEDESTAL = 1; // 1 - take from DB + // 0 - event-by-event pedestal subtraction + + gPARMS->SetDefaultParameter("ECAL:HIT_DEBUG", HIT_DEBUG); + gPARMS->SetDefaultParameter("ECAL:DB_PEDESTAL", DB_PEDESTAL); + +} + + +//------------------ +// init +//------------------ +jerror_t DECALHit_factory::init(void) +{ + // initialize calibration tables + vector< vector > gains_tmp(DECALGeometry::kECALBlocksTall, + vector(DECALGeometry::kECALBlocksWide)); + vector< vector > pedestals_tmp(DECALGeometry::kECALBlocksTall, + vector(DECALGeometry::kECALBlocksWide)); + + vector< vector > time_offsets_tmp(DECALGeometry::kECALBlocksTall, + vector(DECALGeometry::kECALBlocksWide)); + vector< vector > adc_offsets_tmp(DECALGeometry::kECALBlocksTall, + vector(DECALGeometry::kECALBlocksWide)); + + gains = gains_tmp; + pedestals = pedestals_tmp; + time_offsets = time_offsets_tmp; + adc_offsets = adc_offsets_tmp; + + + adc_en_scale = 0; + adc_time_scale = 0; + + base_time = 0; + + + return NOERROR; +} + +//------------------ +// brun +//------------------ +jerror_t DECALHit_factory::brun(jana::JEventLoop *eventLoop, int32_t runnumber) +{ + + // Only print messages for one thread whenever run number change + static pthread_mutex_t print_mutex = PTHREAD_MUTEX_INITIALIZER; + static set runs_announced; + pthread_mutex_lock(&print_mutex); + // bool print_messages = false; + if(runs_announced.find(runnumber) == runs_announced.end()){ + // print_messages = true; + runs_announced.insert(runnumber); + } + pthread_mutex_unlock(&print_mutex); + + // extract the ECAL Geometry + vector ecalGeomVect; + eventLoop->Get( ecalGeomVect ); + if (ecalGeomVect.size() < 1) + return OBJECT_NOT_AVAILABLE; + const DECALGeometry& ecalGeom = *(ecalGeomVect[0]); + + + vector< double > ecal_gains_ch; + vector< double > ecal_pedestals_ch; + vector< double > time_offsets_ch; + vector< double > adc_offsets_ch; + + // load scale factors + map scale_factors; + + if (eventLoop->GetCalib("/ECAL/digi_scales", scale_factors)) + jout << "Error loading /ECAL/digi_scales !" << endl; + if (scale_factors.find("ADC_EN_SCALE") != scale_factors.end()) + adc_en_scale = scale_factors["ADC_EN_SCALE"]; + else + jerr << "Unable to get ADC_EN_SCALE from /ECAL/digi_scales !" << endl; + if (scale_factors.find("ADC_TIME_SCALE") != scale_factors.end()) + adc_time_scale = scale_factors["ADC_TIME_SCALE"]; + else + jerr << "Unable to get ADC_TIME_SCALE from /ECAL/digi_scales !" << endl; + + map base_time_offset; + if (eventLoop->GetCalib("/ECAL/base_time_offset",base_time_offset)) + jout << "Error loading /ECAL/base_time_offset !" << endl; + if (base_time_offset.find("BASE_TIME") != base_time_offset.end()) + base_time = base_time_offset["BASE_TIME"]; + else + jerr << "Unable to get BASE_TIME from /ECAL/base_time_offset !" << endl; + + + if (eventLoop->GetCalib("/ECAL/gains", ecal_gains_ch)) + jout << "DECALHit_factory: Error loading /ECAL/gains !" << endl; + if (eventLoop->GetCalib("/ECAL/pedestals", ecal_pedestals_ch)) + jout << "DECALHit_factory: Error loading /ECAL/pedestals !" << endl; + + if (eventLoop->GetCalib("/ECAL/timing_offsets", time_offsets_ch)) + jout << "Error loading /ECAL/timing_offsets !" << endl; + if (eventLoop->GetCalib("/ECAL/adc_offsets", adc_offsets_ch)) + jout << "Error loading /ECAL/adc_offsets !" << endl; + + + LoadECALConst(gains, ecal_gains_ch, ecalGeom); + LoadECALConst(pedestals, ecal_pedestals_ch, ecalGeom); + LoadECALConst(time_offsets, time_offsets_ch, ecalGeom); + LoadECALConst(adc_offsets, adc_offsets_ch, ecalGeom); + + + if(HIT_DEBUG == 1){ + + + cout << endl; + cout << " ------- Gains -----------" << endl; + + for(int ii = 0; ii < 40; ii++){ + for(int jj = 0; jj < 40; jj++){ + cout << " " << gains[ii][jj]; + } + cout << endl; + } + + cout << endl; + cout << " ------- Pedestals -----------" << endl; + + for(int ii = 0; ii < 40; ii++){ + for(int jj = 0; jj < 40; jj++){ + cout << " " << pedestals[ii][jj]; + } + cout << endl; + } + + cout << endl; + cout << " ------- Timing offsets -----------" << endl; + + for(int ii = 0; ii < 40; ii++){ + for(int jj = 0; jj < 40; jj++){ + cout << " " << time_offsets[ii][jj]; + } + cout << endl; + } + + cout << endl; + cout << " ------- ADC offsets -----------" << endl; + + for(int ii = 0; ii < 40; ii++){ + for(int jj = 0; jj < 40; jj++){ + cout << " " << adc_offsets[ii][jj]; + } + cout << endl; + } + + cout << endl; + cout << "ADC_EN_SCALE = " << adc_en_scale << endl; + cout << "ADC_TIME_SCALE = " << adc_time_scale << endl; + + cout << endl; + + cout << "BASE_TIME_OFFSET = " << base_time << endl; + + cout << endl; + + } + + return NOERROR; +} + +//------------------ +// evnt +//------------------ +jerror_t DECALHit_factory::evnt(JEventLoop *loop, uint64_t eventnumber) +{ + /// Generate DECALHit object for each DECALDigiHit object. + /// This is where the first set of calibration constants + /// is applied to convert from digitzed units into natural + /// units. + /// + /// Note that this code does NOT get called for simulated + /// data in HDDM format. The HDDM event source will copy + /// the precalibrated values directly into the _data vector. + + + // extract the ECAL Geometry + vector ecalGeomVect; + eventLoop->Get( ecalGeomVect ); + if (ecalGeomVect.size() < 1) + return OBJECT_NOT_AVAILABLE; + const DECALGeometry& ecalGeom = *(ecalGeomVect[0]); + + + vector digihits; + + loop->Get(digihits); + + for (unsigned int i = 0; i < digihits.size(); i++) { + + const DECALDigiHit *digihit = digihits[i]; + + double nsamples_integral = digihit->nsamples_integral; + double nsamples_pedestal = digihit->nsamples_pedestal; + + + // Currently use pedestals from the DB. We'll switch to the + // event-by-event pedestal subtraction later + + double pedestal = 0; + + if(DB_PEDESTAL == 1) + pedestal = pedestals[digihit->row][digihit->column]; + else { + pedestal = (double)digihit->pedestal/nsamples_pedestal; + } + + + double integratedPedestal = pedestal * nsamples_integral; + double pulse_amplitude = digihit->pulse_peak - pedestal; + + double pulse_int = (double)digihit->pulse_integral; + double pulse_time = (double)digihit->pulse_time; + + + if(HIT_DEBUG == 1) + cout << "Row = " << digihit->row << "Column = " << digihit->column << + " pulse_int = " << pulse_int << " integratedPedestal = " << integratedPedestal << + " Pedestal = " << pedestal << endl; + + double pulse_int_ped_subt = adc_en_scale * gains[digihit->row][digihit->column] * (pulse_int - integratedPedestal); + double pulse_time_correct = adc_time_scale * pulse_time + base_time - time_offsets[digihit->row][digihit->column] + + adc_offsets[digihit->row][digihit->column]; + + + if(pulse_int_ped_subt > 0 && pulse_time > 0){ + + // Build hit object + DECALHit *hit = new DECALHit; + + hit->row = digihit->row; + hit->column = digihit->column; + + hit->E = pulse_int_ped_subt; + hit->t = pulse_time_correct; + + // Get position of blocks on front face. (This should really come from + // hdgeant directly so the poisitions can be shifted in mcsmear.) + DVector2 pos = ecalGeom.positionOnFace(hit->row, hit->column); + hit->x = pos.X(); + hit->y = pos.Y(); + + if(pulse_amplitude > 0){ + hit->intOverPeak = (pulse_int - integratedPedestal)/pulse_amplitude; + } else + hit->intOverPeak = 0; + + hit->AddAssociatedObject(digihit); + _data.push_back(hit); + + } // Good hit + + } + + return NOERROR; +} + +//------------------ +// erun +//------------------ +jerror_t DECALHit_factory::erun(void) +{ + return NOERROR; +} + +//------------------ +// fini +//------------------ +jerror_t DECALHit_factory::fini(void) +{ + return NOERROR; +} + + +void DECALHit_factory::LoadECALConst(ecal_constants_t &table, const vector &ecal_const_ch, + const DECALGeometry &ecalGeom){ + + char str[256]; + + // if (ecalGeom.numActiveBlocks() != ECAL_MAX_CHANNELS) { + // sprintf(str, "ECAL geometry is wrong size! channels=%d (should be %d)", + // ecalGeom.numActiveBlocks(), ECAL_MAX_CHANNELS); + // throw JException(str); + // } + + + for (int ch = 0; ch < static_cast(ecal_const_ch.size()); ch++) { + + // make sure that we don't try to load info for channels that don't exist + if (ch == ecalGeom.numActiveBlocks()) + break; + + int row = ecalGeom.row(ch); + int col = ecalGeom.column(ch); + + // results from DECALGeometry should be self consistent, but add in some + // sanity checking just to be sure + + if (ecalGeom.isBlockActive(row,col) == false) { + sprintf(str, "DECALHit: Loading ECAL constant for inactive channel! " + "row=%d, col=%d", row, col); + throw JException(str); + } + + table[row][col] = ecal_const_ch[ch]; + } + +} + + + diff --git a/src/libraries/ECAL/DECALHit_factory.h b/src/libraries/ECAL/DECALHit_factory.h new file mode 100644 index 0000000000..ca6714504c --- /dev/null +++ b/src/libraries/ECAL/DECALHit_factory.h @@ -0,0 +1,55 @@ +/* + * File: DECALHit_factory.h + * + * Created on 01/16/2024 by A.S. + */ + + +#ifndef _DECALHit_factory_ +#define _DECALHit_factory_ + +#include +using namespace std; + +#include +#include "TTAB/DTranslationTable.h" + +#include "DECALDigiHit.h" +#include "DECALHit.h" + +typedef vector< vector > ecal_constants_t; + +class DECALHit_factory:public jana::JFactory{ + public: + DECALHit_factory(); + ~DECALHit_factory(){}; + + ecal_constants_t gains; + ecal_constants_t pedestals; + ecal_constants_t time_offsets; + ecal_constants_t adc_offsets; + + double adc_en_scale; + double adc_time_scale; + + double base_time; + + private: + jerror_t init(void); ///< Called once at program start.2 + jerror_t brun(jana::JEventLoop *eventLoop, int32_t runnumber); ///< Called everytime a new run number is detected. + jerror_t evnt(jana::JEventLoop *eventLoop, uint64_t eventnumber); ///< Called every event. + jerror_t erun(void); ///< Called everytime run number changes, provided brun has been called. + jerror_t fini(void); ///< Called after last event of last event source has been processed. + + void LoadECALConst( ecal_constants_t &table, + const vector &ecal_const_ch, + const DECALGeometry &ecalGeom); + + + unsigned int DB_PEDESTAL; + unsigned int HIT_DEBUG; + +}; + +#endif // _DECALHit_factory_ + diff --git a/src/libraries/ECAL/DECALRefDigiHit.h b/src/libraries/ECAL/DECALRefDigiHit.h new file mode 100644 index 0000000000..be746ba41a --- /dev/null +++ b/src/libraries/ECAL/DECALRefDigiHit.h @@ -0,0 +1,45 @@ +// $Id$ +// +// File: DECALRefDigiHit.h +// Created: Tue Aug 6 12:23:55 EDT 2013 + + +#ifndef _DECALRefDigiHit_ +#define _DECALRefDigiHit_ + +#include +#include + +class DECALRefDigiHit:public jana::JObject{ + public: + JOBJECT_PUBLIC(DECALRefDigiHit); + + int id; /// Reference counter number + + uint32_t pulse_integral; ///< identified pulse integral as returned by FPGA algorithm + uint32_t pulse_time; ///< identified pulse time as returned by FPGA algorithm + uint32_t pedestal; ///< pedestal info used by FPGA (if any) + uint32_t QF; ///< Quality Factor from FPGA algorithms + uint32_t nsamples_integral; ///< number of samples used in integral + uint32_t nsamples_pedestal; ///< number of samples used in pedestal + uint32_t pulse_peak; ///< maximum sample in pulse + + uint32_t datasource; ///< 0=window raw data, 1=old(pre-Fall16) firmware, 2=Df250PulseData + + // This method is used primarily for pretty printing + // the second argument to AddString is printf style format + void toStrings(vector > &items)const{ + AddString(items, "id", "%d", id); + AddString(items, "pulse_integral", "%d", pulse_integral); + AddString(items, "pulse_peak", "%d", pulse_peak); + AddString(items, "pulse_time", "%d", pulse_time); + AddString(items, "pedestal", "%d", pedestal); + AddString(items, "QF", "%d", QF); + AddString(items, "nsamples_integral", "%d", nsamples_integral); + AddString(items, "nsamples_pedestal", "%d", nsamples_pedestal); + } + +}; + +#endif // _DECALRefDigiHit_ + diff --git a/src/libraries/ECAL/DECALTruthShower.h b/src/libraries/ECAL/DECALTruthShower.h new file mode 100644 index 0000000000..1df029d811 --- /dev/null +++ b/src/libraries/ECAL/DECALTruthShower.h @@ -0,0 +1,82 @@ +// $Id$ +// +// File: DECALTruthShower.h + +#ifndef _DECALTruthShower_ +#define _DECALTruthShower_ + +#include +#include + +class DECALTruthShower:public jana::JObject{ + public: + JOBJECT_PUBLIC(DECALTruthShower); + + DECALTruthShower(){} + + DECALTruthShower( oid_t id, + float x, float y, float z, + float px, float py, float pz, + float E, float t, + bool primary, int track, int type, + int itrack=0) : + JObject( id ), + m_x( x ), + m_y( y ), + m_z( z ), + m_px( px ), + m_py( py ), + m_pz( pz ), + m_E( E ), + m_t( t ), + m_primary(primary), + m_track(track), + m_type(type), + m_itrack(itrack){} + + float x() const { return m_x; } + float y() const { return m_y; } + float z() const { return m_z; } + float t() const { return m_t; } + float px() const { return m_px; } + float py() const { return m_py; } + float pz() const { return m_pz; } + float E() const { return m_E; } + bool primary() const { return m_primary; } + int track() const { return m_track; } + int type() const { return m_type; } + int itrack() const { return m_itrack; } + + void toStrings(vector > &items)const{ + AddString(items, "x(cm)", "%3.1f", x()); + AddString(items, "y(cm)", "%3.1f", y()); + AddString(items, "z(cm)", "%3.1f", z()); + AddString(items, "px(MeV/c)", "%3.1f", px()*1000); + AddString(items, "py(MeV/c)", "%3.1f", py()*1000); + AddString(items, "pz(MeV/c)", "%3.1f", pz()*1000); + AddString(items, "E(MeV)", "%3.3f", E()*1000.0); + AddString(items, "t(ns)", "%3.1f", t()); + AddString(items, "primary", "%d", primary()); + AddString(items, "track", "%d", track()); + AddString(items, "type", "%d", type()); + AddString(items, "itrack", "%d", itrack()); + } + + private: + + float m_x; + float m_y; + float m_z; + float m_px; + float m_py; + float m_pz; + float m_E; + float m_t; + bool m_primary; + int m_track; + int m_type; + int m_itrack; +}; + +#endif // _DECALTruthShower_ + diff --git a/src/libraries/ECAL/DECALTruthShower_factory.cc b/src/libraries/ECAL/DECALTruthShower_factory.cc new file mode 100644 index 0000000000..201ce26a8e --- /dev/null +++ b/src/libraries/ECAL/DECALTruthShower_factory.cc @@ -0,0 +1,67 @@ +// $Id$ +// +// File: DECALTruthShower_factory.cc +// Created: Tue Nov 30 15:02:26 EST 2010 +// Creator: davidl (on Linux ifarml6 2.6.18-128.el5 x86_64) +// + + +#include +#include +using namespace std; + +#include "DECALTruthShower_factory.h" +using namespace jana; + +//------------------ +// init +//------------------ +jerror_t DECALTruthShower_factory::init(void) +{ + return NOERROR; +} + +//------------------ +// brun +//------------------ +jerror_t DECALTruthShower_factory::brun(jana::JEventLoop *eventLoop, int32_t runnumber) +{ + return NOERROR; +} + +//------------------ +// evnt +//------------------ +jerror_t DECALTruthShower_factory::evnt(JEventLoop *loop, uint64_t eventnumber) +{ + + // Code to generate factory data goes here. Add it like: + // + // DECALTruthShower *myDECALTruthShower = new DECALTruthShower; + // myDECALTruthShower->x = x; + // myDECALTruthShower->y = y; + // ... + // _data.push_back(myDECALTruthShower); + // + // Note that the objects you create here will be deleted later + // by the system and the _data vector will be cleared automatically. + + return NOERROR; +} + +//------------------ +// erun +//------------------ +jerror_t DECALTruthShower_factory::erun(void) +{ + return NOERROR; +} + +//------------------ +// fini +//------------------ +jerror_t DECALTruthShower_factory::fini(void) +{ + return NOERROR; +} + diff --git a/src/libraries/ECAL/DECALTruthShower_factory.h b/src/libraries/ECAL/DECALTruthShower_factory.h new file mode 100644 index 0000000000..7f19f3c7d2 --- /dev/null +++ b/src/libraries/ECAL/DECALTruthShower_factory.h @@ -0,0 +1,27 @@ +// $Id$ +// +// File: DECALTruthShower_factory.h +// + +#ifndef _DECALTruthShower_factory_ +#define _DECALTruthShower_factory_ + +#include +#include "DECALTruthShower.h" + +class DECALTruthShower_factory:public jana::JFactory{ + public: + DECALTruthShower_factory(){}; + ~DECALTruthShower_factory(){}; + + + private: + jerror_t init(void); ///< Called once at program start. + jerror_t brun(jana::JEventLoop *eventLoop, int32_t runnumber); ///< Called everytime a new run number is detected. + jerror_t evnt(jana::JEventLoop *eventLoop, uint64_t eventnumber); ///< Called every event. + jerror_t erun(void); ///< Called everytime run number changes, provided brun has been called. + jerror_t fini(void); ///< Called after last event of last event source has been processed. +}; + +#endif // _DECALTruthShower_factory_ + diff --git a/src/libraries/ECAL/ECAL_init.cc b/src/libraries/ECAL/ECAL_init.cc new file mode 100644 index 0000000000..6bfbe5d8ed --- /dev/null +++ b/src/libraries/ECAL/ECAL_init.cc @@ -0,0 +1,26 @@ +// $Id: FCAL_init.cc 5342 2009-07-09 15:46:12Z davidl $ + +#include +using namespace jana; + +#include +#include + +#include "DECALDigiHit.h" +#include "DECALHit_factory.h" + + +#include "DECALRefDigiHit.h" + +jerror_t ECAL_init(JEventLoop *loop) +{ + /// Create and register ECAL data factories + loop->AddFactory(new JFactory()); + loop->AddFactory(new JFactory()); + loop->AddFactory(new DECALHit_factory()); + loop->AddFactory(new JFactory("TRUTH")); + loop->AddFactory(new DECALTruthShower_factory()); + loop->AddFactory(new DECALGeometry_factory()); + + return NOERROR; +} diff --git a/src/libraries/ECAL/SConscript b/src/libraries/ECAL/SConscript new file mode 100644 index 0000000000..2d42473d1e --- /dev/null +++ b/src/libraries/ECAL/SConscript @@ -0,0 +1,14 @@ + + +import sbms + +# get env object and clone it +Import('*') +env = env.Clone() + +env.AppendUnique(LIBS = 'gfortran') + +sbms.AddDANA(env) +sbms.library(env) + + diff --git a/src/libraries/ECAL/ecal.h b/src/libraries/ECAL/ecal.h new file mode 100644 index 0000000000..d7b1d2fdf6 --- /dev/null +++ b/src/libraries/ECAL/ecal.h @@ -0,0 +1,20 @@ +#ifndef _ECAL_H_ +#define _ECAL_H_ + + +#define MCOL 40 +#define MROW 40 + +#define MADCGAM 50 // maximum allowed showers +#define MAX_CC 60 + +#define xsize 2.09 +#define ysize 2.09 + +#define MIN_ENERGY 0. + +#define COUNT_ZERO 1 +#define TEST_P 1 + + +#endif diff --git a/src/libraries/FCAL/DFCALCluster_factory_Island.cc b/src/libraries/FCAL/DFCALCluster_factory_Island.cc index c4be1011f3..555d88cf4f 100644 --- a/src/libraries/FCAL/DFCALCluster_factory_Island.cc +++ b/src/libraries/FCAL/DFCALCluster_factory_Island.cc @@ -32,19 +32,28 @@ jerror_t DFCALCluster_factory_Island::init(void) MAX_HITS_FOR_CLUSTERING = 250; gPARMS->SetDefaultParameter("FCAL:MAX_HITS_FOR_CLUSTERING", MAX_HITS_FOR_CLUSTERING); - + MIN_EXCESS_SEED_ENERGY=35.*k_MeV; + gPARMS->SetDefaultParameter("FCAL:MIN_EXCESS_SEED_ENERGY", + MIN_EXCESS_SEED_ENERGY); MIN_CLUSTER_SEED_ENERGY=35.*k_MeV; gPARMS->SetDefaultParameter("FCAL:MIN_CLUSTER_SEED_ENERGY", MIN_CLUSTER_SEED_ENERGY); SHOWER_ENERGY_THRESHOLD = 50*k_MeV; gPARMS->SetDefaultParameter("FCAL:SHOWER_ENERGY_THRESHOLD", SHOWER_ENERGY_THRESHOLD); - SHOWER_WIDTH_PARAMETER=0.72; - gPARMS->SetDefaultParameter("FCAL:SHOWER_WIDTH_PARAMETER", - SHOWER_WIDTH_PARAMETER); - INSERT_SHOWER_WIDTH_PARAMETER=0.31; - gPARMS->SetDefaultParameter("FCAL:INSERT_SHOWER_WIDTH_PARAMETER", - INSERT_SHOWER_WIDTH_PARAMETER); + SHOWER_WIDTH_PAR0=0.6356; + gPARMS->SetDefaultParameter("FCAL:SHOWER_WIDTH_PAR0",SHOWER_WIDTH_PAR0); + SHOWER_WIDTH_PAR1=-1.516e-6; + gPARMS->SetDefaultParameter("FCAL:SHOWER_WIDTH_PAR1",SHOWER_WIDTH_PAR1); + SHOWER_WIDTH_PAR2=4.845e-5; + gPARMS->SetDefaultParameter("FCAL:SHOWER_WIDTH_PAR2",SHOWER_WIDTH_PAR2); + + INSERT_SHOWER_WIDTH_PAR0=0.3284; + gPARMS->SetDefaultParameter("FCAL:INSERT_SHOWER_WIDTH_PAR0", + INSERT_SHOWER_WIDTH_PAR0); + INSERT_SHOWER_WIDTH_PAR1=0.000886; + gPARMS->SetDefaultParameter("FCAL:INSERT_SHOWER_WIDTH_PAR1", + INSERT_SHOWER_WIDTH_PAR1); MIN_CUTDOWN_FRACTION=0.1; gPARMS->SetDefaultParameter("FCAL:MIN_CUTDOWN_FRACTION", MIN_CUTDOWN_FRACTION); @@ -52,14 +61,29 @@ jerror_t DFCALCluster_factory_Island::init(void) DEBUG_HISTS=false; gPARMS->SetDefaultParameter("FCAL:DEBUG_HISTS",DEBUG_HISTS); - CHISQ_MARGIN=5.; + CHISQ_MARGIN=12.5; gPARMS->SetDefaultParameter("FCAL:CHISQ_MARGIN",CHISQ_MARGIN); - MASS_CUT=5e-5; - gPARMS->SetDefaultParameter("FCAL:MASS_CUT",MASS_CUT); + SPLIT_PEAKS=false; + gPARMS->SetDefaultParameter("FCAL:SPLIT_PEAKS",SPLIT_PEAKS); + + MERGE_HITS_AT_BOUNDARY=true; + gPARMS->SetDefaultParameter("FCAL:MERGE_HITS_AT_BOUNDARY",MERGE_HITS_AT_BOUNDARY); ENERGY_SHARING_CUTOFF=0.9; gPARMS->SetDefaultParameter("FCAL:ENERGY_SHARING_CUTOFF",ENERGY_SHARING_CUTOFF); + APPLY_S_CURVE_CORRECTION=true; + gPARMS->SetDefaultParameter("FCAL:APPLY_S_CURVE_CORRECTION", + APPLY_S_CURVE_CORRECTION); + + S_CURVE_PAR1=-0.0517; + gPARMS->SetDefaultParameter("FCAL:S_CURVE_PAR1",S_CURVE_PAR1); + S_CURVE_PAR2=0.02565; + gPARMS->SetDefaultParameter("FCAL:S_CURVE_PAR2",S_CURVE_PAR2); + INSERT_S_CURVE_PAR1=-0.1593; + gPARMS->SetDefaultParameter("FCAL:INSERT_S_CURVE_PAR1",INSERT_S_CURVE_PAR1); + INSERT_S_CURVE_PAR2=0.02337; + gPARMS->SetDefaultParameter("FCAL:INSERT_S_CURVE_PAR2",INSERT_S_CURVE_PAR2); HistdE=new TH2D("HistdE",";E [GeV];#deltaE [GeV]",100,0,10,201,-0.25,0.25); HistProb=new TH1D("HistProb",";CL",100,0,1); @@ -141,6 +165,23 @@ jerror_t DFCALCluster_factory_Island::evnt(JEventLoop *loop, uint64_t eventnumbe int channel=dFCALGeom->channel(clusterCandidate[0]->row, clusterCandidate[0]->column); myCluster->setChannelEmax(channel); + + if (APPLY_S_CURVE_CORRECTION){ + DVector2 blockPos=dFCALGeom->positionOnFace(channel); + double dx=blockPos.X()-x; + double dy=blockPos.Y()-y; + if (dFCALGeom->inInsert(channel)==false){ + x-=0.12*dx*(4.0157*4.0157/4-dx*dx); + y-=0.12*dy*(4.0157*4.0157/4-dy*dy); + } + else{ + double diffx=2.05*2.05/4-dx*dx; + double diffy=2.05*2.05/4-dy*dy; + x-=1.055*dx*diffx*diffx; + y-=1.055*dy*diffy*diffy; + } + } + myCluster->setCentroid(x,y); _data.push_back(myCluster); @@ -151,6 +192,8 @@ jerror_t DFCALCluster_factory_Island::evnt(JEventLoop *loop, uint64_t eventnumbe //------------------------------------------------------------------------ // Handle cluster candidates containing more than 3 hits //------------------------------------------------------------------------ + //cout <<"Finding peaks for cluster " << i << endl; + vectorclusterHits=clusterCandidates[i]; vectorpeaks; @@ -158,8 +201,9 @@ jerror_t DFCALCluster_factory_Island::evnt(JEventLoop *loop, uint64_t eventnumbe unsigned int num_hits=clusterHits.size(); TMatrixD W(num_hits,num_hits); double Esum=0.; - for (unsigned int i=0;iE; double varE=0.; if (dFCALGeom->isInsertBlock(hit->row,hit->column)){ @@ -168,10 +212,12 @@ jerror_t DFCALCluster_factory_Island::evnt(JEventLoop *loop, uint64_t eventnumbe else{ varE=m_Eres[0]+m_Eres[1]*E+m_Eres[2]*E*E; } - W(i,i)=1./varE; + W(j,j)=1./varE; Esum+=E; + R+=sqrt(hit->x*hit->x+hit->y*hit->y); } - + R/=double(num_hits); + double chisq=1e6,chisq_old=1e6; unsigned int ndf=1,ndf_old=1; // Find the minimum and maximum row and column numbers @@ -187,32 +233,45 @@ jerror_t DFCALCluster_factory_Island::evnt(JEventLoop *loop, uint64_t eventnumbe int num_cols=max_col-min_col+3; vector>Emap(num_cols,vector(num_rows)); vector>imap(num_cols,vector(num_rows)); + // Info for block with maximum energy + unsigned int jmax=0; + double Emax=0.; for (unsigned int j=0;jcolumn-min_col+1; int ir=clusterHits[j]->row-min_row+1; Emap[ic][ir]=clusterHits[j]->E; - imap[ic][ir]=j; + imap[ic][ir]=j; + if (clusterHits[j]->E>Emax){ + Emax=clusterHits[j]->E; + jmax=j; + } } - - if (min_row<100 && max_row>=100){ + + // Compute estimate for shower shape parameter b + double b=0.; + if (dFCALGeom->isInsertBlock(clusterHits[jmax]->row, + clusterHits[jmax]->column)){ + b=INSERT_SHOWER_WIDTH_PAR0+INSERT_SHOWER_WIDTH_PAR1*R; + } + else{ + b=SHOWER_WIDTH_PAR0+SHOWER_WIDTH_PAR1*R+SHOWER_WIDTH_PAR2*R*R; + } + + if (MERGE_HITS_AT_BOUNDARY && min_row<100 && max_row>=100){ + //cout << "!!! overlap " << Emax << endl; // Handle the interface between the insert and the lead glass blocks - // Find the block with the maximum energy and make a peak object - double Emax=0.,Esum=0.; - unsigned int jmax=0; + double Esum=0.; for (unsigned int j=0;jE; Esum+=Ej; - if (Ej>Emax){ - Emax=Ej; - jmax=j; - } } if (Emax>MIN_CLUSTER_SEED_ENERGY){ PeakInfo myPeak(Esum,clusterHits[jmax]->x,clusterHits[jmax]->y,0,0, num_hits); - bool good_fit=FitPeaks(W,clusterHits,peaks,myPeak,chisq,ndf); + bool good_fit=FitPeaks(W,b,clusterHits,peaks,myPeak,chisq,ndf); if (good_fit){ peaks.push_back(myPeak); + // cout << "Transition region " << peaks.size() << endl; } else{ // Use energy-weighted average for position and put myPeak in peak @@ -227,13 +286,14 @@ jerror_t DFCALCluster_factory_Island::evnt(JEventLoop *loop, uint64_t eventnumbe myPeak.x/=Esum; myPeak.y/=Esum; peaks.push_back(myPeak); + //cout << "Fit did not work " << endl; // Compute chisq estimate just in case we need to make a split chisq=0.; ndf=num_hits-3; for (unsigned int j=0;jE - -Esum*CalcClusterEDeriv(clusterHits[j],myPeak); + -Esum*CalcClusterEDeriv(b,clusterHits[j],myPeak); chisq+=W(j,j)*dE*dE; } } @@ -280,14 +340,16 @@ jerror_t DFCALCluster_factory_Island::evnt(JEventLoop *loop, uint64_t eventnumbe }// cut on minimum energy of central block } // loop over rows } // loop over columns - + // Sort peak candidates by energy + //cout << "---> Candidates: "<< peak_candidates.size() << endl; if (peak_candidates.size()>0){ sort(peak_candidates.begin(),peak_candidates.end(),peak_E_cmp); } - + // Loop over peak candidates to perform the peak fit and add good // candidates to the output list. + for (size_t i=0;i0){ @@ -305,14 +367,14 @@ jerror_t DFCALCluster_factory_Island::evnt(JEventLoop *loop, uint64_t eventnumbe for (int j=lo_col;j<=hi_col;j++){ for (int k=lo_row;k<=hi_row;k++){ if (Emap[j][k]>0.){ - frac+=CalcClusterEDeriv(clusterHits[imap[j][k]],peaks[m]); + frac+=CalcClusterEDeriv(b,clusterHits[imap[j][k]],peaks[m]); } } } myPeak.E-=peaks[m].E*frac; } } - + //cout << " E guess: " << myPeak.E << endl; if (myPeak.E>MIN_CLUSTER_SEED_ENERGY){ // Save the current peak list vectorsaved_peaks=peaks; @@ -322,23 +384,13 @@ jerror_t DFCALCluster_factory_Island::evnt(JEventLoop *loop, uint64_t eventnumbe // parameters for each peak within this group of FCAL hits. chisq_old=chisq; ndf_old=ndf; - bool good_fit=FitPeaks(W,clusterHits,peaks,myPeak,chisq,ndf); + bool good_fit=FitPeaks(W,b,clusterHits,peaks,myPeak,chisq,ndf); + //cout << "Main fits " << chisq/ndf << " " << chisq_old/ndf_old<E - -Esum*CalcClusterEDeriv(clusterHits[j],peak_guess); + -Esum*CalcClusterEDeriv(b,clusterHits[j],peak_guess); chisq+=W(j,j)*dE*dE; } } @@ -368,20 +420,20 @@ jerror_t DFCALCluster_factory_Island::evnt(JEventLoop *loop, uint64_t eventnumbe PeakInfo myPeakInfo=peaks[0]; for (unsigned int k=0;kE; - Ecalc+=myPeakInfo.E*CalcClusterEDeriv(clusterHits[k],myPeakInfo); + Ecalc+=myPeakInfo.E*CalcClusterEDeriv(b,clusterHits[k],myPeakInfo); HistdE->Fill(E,E-Ecalc); } } } - if (num_hits>3*(peaks.size()+1)){ + while (num_hits>3*(peaks.size()+1)){ // Subtract the energy due to the fitted peaks from the energy of each // hit to see if we have excess energy that has not been accounted for vectorElist(clusterHits.size()); for (unsigned int m=0;mE; for (unsigned int k=0;kMIN_CLUSTER_SEED_ENERGY){ + if (Emax>MIN_EXCESS_SEED_ENERGY){ // Make a peak candidate out of the excess energy in the cluster of hits int ic=clusterHits[mmax]->column-min_col+1; int ir=clusterHits[mmax]->row-min_row+1; @@ -401,31 +453,29 @@ jerror_t DFCALCluster_factory_Island::evnt(JEventLoop *loop, uint64_t eventnumbe int hi_col=ic+1; int lo_row=ir-1; int hi_row=ir+1; - int num_hits=0; - double Esum=0.; + int num_peak_hits=0; + double excessE=0.; for (int j=lo_col;j<=hi_col;j++){ for (int k=lo_row;k<=hi_row;k++){ int index=imap[j][k]; if (Elist[index]>0){ - Esum+=Elist[index]; - num_hits++; + excessE+=Elist[index]; + num_peak_hits++; } } } double x=clusterHits[mmax]->x; double y=clusterHits[mmax]->y; - PeakInfo myPeak(Esum,x,y,ic,ir,num_hits); - + PeakInfo myPeak(excessE,x,y,ic,ir,num_peak_hits); + // Save the current list of peaks vectorsaved_peaks=peaks; - + // Add the new peak to the fit to see if the fit quality improves chisq_old=chisq; ndf_old=ndf; - bool good_fit=FitPeaks(W,clusterHits,peaks,myPeak,chisq,ndf); - if (good_fit && chisq/ndf+CHISQ_MARGINt; fsum+=f; if (f>fmax){ @@ -477,7 +532,22 @@ jerror_t DFCALCluster_factory_Island::evnt(JEventLoop *loop, uint64_t eventnumbe int channel=dFCALGeom->channel(clusterHits[jmax]->row, clusterHits[jmax]->column); myCluster->setChannelEmax(channel); - myCluster->setCentroid(peaks[k].x,peaks[k].y); + + double xc=peaks[k].x,yc=peaks[k].y; + if (APPLY_S_CURVE_CORRECTION){ + DVector2 blockPos=dFCALGeom->positionOnFace(channel); + double dx=blockPos.X()-xc; + double dy=blockPos.Y()-yc; + if (dFCALGeom->inInsert(channel)==false){ + xc+=S_CURVE_PAR1*dx*(4.0157*4.0157/4-dx*dx)+S_CURVE_PAR2; + yc+=S_CURVE_PAR1*dy*(4.0157*4.0157/4-dy*dy)+S_CURVE_PAR2; + } + else{ + xc+=INSERT_S_CURVE_PAR1*dx*(2.05*2.05/4-dx*dx)+INSERT_S_CURVE_PAR2; + yc+=INSERT_S_CURVE_PAR1*dy*(2.05*2.05/4-dy*dy)+INSERT_S_CURVE_PAR2; + } + } + myCluster->setCentroid(xc,yc); // Add hits to the cluster object as associated objects for (unsigned int j=0;j& // look for adjacent clusters between the lead glass and the insert, // if present - if (dFCALGeom->hitPairHasInsertHit(row1,row2)){ + if (MERGE_HITS_AT_BOUNDARY + && dFCALGeom->hitPairHasInsertHit(row1,row2)){ double dx=(*iter)[i]->x-(*iter2)[j]->x; double dy=(*iter)[i]->y-(*iter2)[j]->y; if (fabs(dx)& } if (matched==false) iter++; } + //cout << "Finished finding clusters" << endl; } // Fit peaks within a cluster containing a list of hits contained in hitList -bool DFCALCluster_factory_Island::FitPeaks(const TMatrixD &W, +bool DFCALCluster_factory_Island::FitPeaks(const TMatrixD &W,double b, vector&hitList, vector&peaks, PeakInfo &myNewPeak,double &chisq, @@ -635,14 +707,15 @@ bool DFCALCluster_factory_Island::FitPeaks(const TMatrixD &W, size_t npeaks=peaks.size(); // Save the current peak info vectorsaved_peaks=peaks; - PeakInfo saved_new_peak=myNewPeak; + PeakInfo saved_new_peak=myNewPeak; // Iterate to find best shower energy and position chisq=1e6; - unsigned int max_iter=200; + unsigned int min_iter=10,max_iter=200; double min_frac=MIN_CUTDOWN_FRACTION; - double cutdown_scale=(1.-min_frac)/double(max_iter); //for cut-down for parameter adjustment + double cutdown_scale=(1.-min_frac)/double(min_iter); //for cut-down for parameter adjustment for (unsigned int k=0;kisFiducial(myNewPeak.x,myNewPeak.y)==false){ + //_DBG_ << myNewPeak.x << " " << myNewPeak.y << endl; return false; } @@ -666,30 +740,29 @@ bool DFCALCluster_factory_Island::FitPeaks(const TMatrixD &W, // Make sure the energy is positive! if (myPeakInfo.E<0){ - //_DBG_ <isFiducial(myPeakInfo.x,myPeakInfo.y)==false){ - //_DBG_ << myPeakInfo.x << " " << myPeakInfo.y << endl; + //_DBG_<< myPeakInfo.x << " " << myPeakInfo.y << endl; return false; } // Compute the Jacobian matrix elements - df_dE=CalcClusterEDeriv(hitList[i],myPeakInfo); + df_dE=CalcClusterEDeriv(b,hitList[i],myPeakInfo); A(i,3*j+0)=df_dE; - A(i,3*j+1)=CalcClusterXYDeriv(true,hitList[i],myPeakInfo); - A(i,3*j+2)=CalcClusterXYDeriv(false,hitList[i],myPeakInfo); + A(i,3*j+1)=CalcClusterXYDeriv(true,b,hitList[i],myPeakInfo); + A(i,3*j+2)=CalcClusterXYDeriv(false,b,hitList[i],myPeakInfo); Ecalc+=myPeakInfo.E*df_dE; } // Add contributions from the peak we wish to add - df_dE=CalcClusterEDeriv(hitList[i],myNewPeak); + df_dE=CalcClusterEDeriv(b,hitList[i],myNewPeak); A(i,3*npeaks+0)=df_dE; - A(i,3*npeaks+1)=CalcClusterXYDeriv(true,hitList[i],myNewPeak); - A(i,3*npeaks+2)=CalcClusterXYDeriv(false,hitList[i],myNewPeak); + A(i,3*npeaks+1)=CalcClusterXYDeriv(true,b,hitList[i],myNewPeak); + A(i,3*npeaks+2)=CalcClusterXYDeriv(false,b,hitList[i],myNewPeak); Ecalc+=myNewPeak.E*df_dE; @@ -701,10 +774,12 @@ bool DFCALCluster_factory_Island::FitPeaks(const TMatrixD &W, double chisq_new=0.; for (unsigned int i=0;ichisq) break; + //cout << k << " chisq "<< chisq_new << " " << (chisq_new-chisq)/chisq <=min_iter){ + if (fabs(chisq_new-chisq)/chisq<0.0001) break; + if (chisq_new>chisq) break; + } // Save the current value of chisq chisq=chisq_new; @@ -756,7 +831,6 @@ bool DFCALCluster_factory_Island::FitPeaks(const TMatrixD &W, for (unsigned int j=0;jblockSize(); - double b=SHOWER_WIDTH_PARAMETER; // cm if (dFCALGeom->isInsertBlock(hit->row,hit->column)){ half_block=0.5*dFCALGeom->insertBlockSize(); - b=INSERT_SHOWER_WIDTH_PARAMETER; } double b2=b*b; double f=0.; @@ -802,15 +874,14 @@ double DFCALCluster_factory_Island::CalcClusterXYDeriv(bool isXDeriv, // Techniques, 2008, Vol. 51, No. 3, pp. 342-350, eq. 6. Note that the // normalization of this function in this equation does not appear to be // correct (it's off by 1/sqrt(2pi)). -double DFCALCluster_factory_Island::CalcClusterEDeriv(const DFCALHit *hit, +double DFCALCluster_factory_Island::CalcClusterEDeriv(double b, + const DFCALHit *hit, const PeakInfo &myPeakInfo) const { double sign1[4]={1,1,-1,-1}; double sign2[4]={1,-1,-1,1}; double half_block=0.5*dFCALGeom->blockSize(); - double b=SHOWER_WIDTH_PARAMETER; // cm if (dFCALGeom->isInsertBlock(hit->row,hit->column)){ half_block=0.5*dFCALGeom->insertBlockSize(); - b=INSERT_SHOWER_WIDTH_PARAMETER; } double f=0.; double dxc=hit->x-myPeakInfo.x; @@ -825,7 +896,7 @@ double DFCALCluster_factory_Island::CalcClusterEDeriv(const DFCALHit *hit, // Try to split peaks into two following the algorithm (barely) described in // Lednev, IHEP 93-153. -void DFCALCluster_factory_Island::SplitPeaks(const TMatrixD &W, +void DFCALCluster_factory_Island::SplitPeaks(const TMatrixD &W,double b, vector&hits, vector&peaks, double &chisq,unsigned int &ndf) const{ @@ -842,7 +913,7 @@ void DFCALCluster_factory_Island::SplitPeaks(const TMatrixD &W, double Ecalc=0.; for (unsigned int k=0;kE-Ecalc; E0+=Elist[j]; @@ -911,21 +982,10 @@ void DFCALCluster_factory_Island::SplitPeaks(const TMatrixD &W, // Refit with the split peaks chisq_old=chisq; ndf_old=ndf; - bool good_fit=FitPeaks(W,hits,peaks,myNewPeak,chisq,ndf); + bool good_fit=FitPeaks(W,b,hits,peaks,myNewPeak,chisq,ndf); if (good_fit && chisq/ndf+CHISQ_MARGIN&peaks,const PeakInfo &myNewPeak) const{ - DVector3 dir1(myNewPeak.x,myNewPeak.y,m_zdiff); - dir1.SetMag(1.); - for (unsigned int m=0;m{ void FindClusterCandidates(vector&fcal_hits, vector>&clusterCandidates) const; - bool FitPeaks(const TMatrixD &W,vector&hitList, + bool FitPeaks(const TMatrixD &W,double b,vector&hitList, vector&peaks,PeakInfo &myPeak,double &chisq, unsigned int &ndf) const; - double CalcClusterEDeriv(const DFCALHit *hit,const PeakInfo &myPeakInfo) const; - double CalcClusterXYDeriv(bool isXDeriv,const DFCALHit *hit, + double CalcClusterEDeriv(double b,const DFCALHit *hit,const PeakInfo &myPeakInfo) const; + double CalcClusterXYDeriv(bool isXDeriv,double b,const DFCALHit *hit, const PeakInfo &myPeakInfo) const; - void SplitPeaks(const TMatrixD &W,vector&hits, + void SplitPeaks(const TMatrixD &W,double b,vector&hits, vector&peaks,double &chisq,unsigned int &ndf) const; - bool CheckPeak(const vector&peaks,const PeakInfo &myNewPeak) const; double TIME_CUT,MIN_CLUSTER_SEED_ENERGY,SHOWER_ENERGY_THRESHOLD; + double MIN_EXCESS_SEED_ENERGY; double SHOWER_WIDTH_PARAMETER,ENERGY_SHARING_CUTOFF; - double INSERT_SHOWER_WIDTH_PARAMETER; + double INSERT_SHOWER_WIDTH_PAR0,INSERT_SHOWER_WIDTH_PAR1; + double SHOWER_WIDTH_PAR0,SHOWER_WIDTH_PAR1,SHOWER_WIDTH_PAR2; double MIN_CUTDOWN_FRACTION,CHISQ_MARGIN,MASS_CUT; bool DEBUG_HISTS; unsigned int MAX_HITS_FOR_CLUSTERING; double m_insert_Eres[3],m_Eres[3]; double m_zdiff; + + bool SPLIT_PEAKS,MERGE_HITS_AT_BOUNDARY; + bool APPLY_S_CURVE_CORRECTION; + double S_CURVE_PAR1,S_CURVE_PAR2,INSERT_S_CURVE_PAR1,INSERT_S_CURVE_PAR2; const DFCALGeometry *dFCALGeom=NULL; TH2D *HistdE; diff --git a/src/libraries/FCAL/DFCALGeometry.cc b/src/libraries/FCAL/DFCALGeometry.cc index 30d582d9e7..9a8767cc81 100644 --- a/src/libraries/FCAL/DFCALGeometry.cc +++ b/src/libraries/FCAL/DFCALGeometry.cc @@ -124,7 +124,7 @@ DFCALGeometry::row( float y, bool in_insert ) const y-=m_FCALdY; if (in_insert){ - return kBlocksTall+static_cast( y / insertBlockSize() + m_insertMidBlock + 0.5); + return kBlocksTall+static_cast( y / insertBlockSize() + m_insertMidBlock )+1; } int my_row=static_cast( y / blockSize() + kMidBlock + 0.5); if (my_row<0) return -1; @@ -138,7 +138,7 @@ DFCALGeometry::column( float x, bool in_insert ) const x-=m_FCALdX; if (in_insert){ - return kBlocksWide+static_cast( x / insertBlockSize() + m_insertMidBlock + 0.5); + return kBlocksWide+static_cast( x / insertBlockSize() + m_insertMidBlock )+1; } int my_col=static_cast( x / blockSize() + kMidBlock + 0.5); if (my_col<0) return -1; diff --git a/src/libraries/FCAL/DFCALShower_factory.cc b/src/libraries/FCAL/DFCALShower_factory.cc index 7afcb510cb..0f0a86d8c7 100644 --- a/src/libraries/FCAL/DFCALShower_factory.cc +++ b/src/libraries/FCAL/DFCALShower_factory.cc @@ -33,9 +33,15 @@ DFCALShower_factory::DFCALShower_factory() gPARMS->SetDefaultParameter("FCAL:LOAD_NONLIN_CCDB", LOAD_NONLIN_CCDB); gPARMS->SetDefaultParameter("FCAL:LOAD_TIMING_CCDB", LOAD_TIMING_CCDB); // Should we use the PrimeX-D energy correction? - USE_RING_E_CORRECTION=false; - gPARMS->SetDefaultParameter("FCAL:USE_RING_E_CORRECTION",USE_RING_E_CORRECTION); + USE_RING_E_CORRECTION_V1=false; + gPARMS->SetDefaultParameter("FCAL:USE_RING_E_CORRECTION_V1",USE_RING_E_CORRECTION_V1); + USE_RING_E_CORRECTION_V2=false; + gPARMS->SetDefaultParameter("FCAL:USE_RING_E_CORRECTION_V2",USE_RING_E_CORRECTION_V2); + + USE_CPP_E_CORRECTION=false; + gPARMS->SetDefaultParameter("FCAL:USE_CPP_CORRECTION",USE_CPP_E_CORRECTION); + SHOWER_ENERGY_THRESHOLD = 50*k_MeV; gPARMS->SetDefaultParameter("FCAL:SHOWER_ENERGY_THRESHOLD", SHOWER_ENERGY_THRESHOLD); @@ -64,6 +70,33 @@ DFCALShower_factory::DFCALShower_factory() gPARMS->SetDefaultParameter("FCAL:expfit_param1", expfit_param1); gPARMS->SetDefaultParameter("FCAL:expfit_param2", expfit_param2); gPARMS->SetDefaultParameter("FCAL:expfit_param3", expfit_param3); + + USE_NONLINEAR_CORRECTION_TYPE = -1; + gPARMS->SetDefaultParameter("FCAL:USE_NONLINEAR_CORRECTION_TYPE",USE_NONLINEAR_CORRECTION_TYPE); + + if (USE_NONLINEAR_CORRECTION_TYPE == 0) { + } else if (USE_NONLINEAR_CORRECTION_TYPE == 1) { + expfit_param1 = 2; + expfit_param1 = 0; + expfit_param1 = 0; + SHOWER_POSITION_LOG = true; + USE_RING_E_CORRECTION_V1 = true; + USE_RING_E_CORRECTION_V2 = false; + USE_CPP_E_CORRECTION = false; + } else if (USE_NONLINEAR_CORRECTION_TYPE == 2) { + expfit_param1 = 2; + expfit_param1 = 0; + expfit_param1 = 0; + SHOWER_POSITION_LOG = true; + USE_RING_E_CORRECTION_V1 = false; + USE_RING_E_CORRECTION_V2 = true; + USE_CPP_E_CORRECTION = false; + } else if (USE_NONLINEAR_CORRECTION_TYPE == 3) { + SHOWER_POSITION_LOG = true; + USE_RING_E_CORRECTION_V1 = false; + USE_RING_E_CORRECTION_V2 = false; + USE_CPP_E_CORRECTION = true; + } gPARMS->SetDefaultParameter("FCAL:P0", timeConst0); gPARMS->SetDefaultParameter("FCAL:P1", timeConst1); @@ -95,25 +128,29 @@ DFCALShower_factory::DFCALShower_factory() INSERT_CRITICAL_ENERGY = 0.00964; INSERT_SHOWER_OFFSET = 1.0; - INSERT_PAR1=0.0843; - INSERT_PAR2=1.1356; + INSERT_PAR1=0.167457; + INSERT_PAR2=1.1349; gPARMS->SetDefaultParameter("FCAL:INSERT_PAR1",INSERT_PAR1); gPARMS->SetDefaultParameter("FCAL:INSERT_PAR2",INSERT_PAR2); - INSERT_POS_RES1=0.11; - INSERT_POS_RES2=0.22; - // For Island algorithm: - // INSERT_POS_RES1=0.18; - // INSERT_POS_RES2=0.055; - INSERT_E_VAR1=0.001223; - INSERT_E_VAR2=0.; - INSERT_E_VAR3=2.025e-5; + // For island algo + INSERT_POS_RES1=0.168; + INSERT_POS_RES2=0.0636; + INSERT_POS_PHI1=0.0; + INSERT_POS_PHI2=0.0; + // For default algorithm: + // INSERT_POS_RES1=0.10; + // INSERT_POS_RES2=0.21; + INSERT_E_VAR1=6.49300e-04; + INSERT_E_VAR2=1.24109e-04; + INSERT_E_VAR3=4.70327e-05; gPARMS->SetDefaultParameter("FCAL:INSERT_POS_RES1",INSERT_POS_RES1); - gPARMS->SetDefaultParameter("FCAL:INSERT_POS_RES2",INSERT_POS_RES2); + gPARMS->SetDefaultParameter("FCAL:INSERT_POS_RES2",INSERT_POS_RES2); + gPARMS->SetDefaultParameter("FCAL:INSERT_POS_PHI1",INSERT_POS_PHI1); + gPARMS->SetDefaultParameter("FCAL:INSERT_POS_PHI2",INSERT_POS_PHI2); gPARMS->SetDefaultParameter("FCAL:INSERT_E_VAR2",INSERT_E_VAR2); gPARMS->SetDefaultParameter("FCAL:INSERT_E_VAR3",INSERT_E_VAR3); gPARMS->SetDefaultParameter("FCAL:INSERT_E_VAR1",INSERT_E_VAR1); - } //------------------ @@ -161,9 +198,50 @@ jerror_t DFCALShower_factory::brun(JEventLoop *loop, int32_t runnumber) std::map beam_spot; jcalib->Get("PHOTON_BEAM/beam_spot", beam_spot); - // by default, load non-linear shower corrections from the CCDB + // Look in CCDB which non-linear correction version should be used + nonlinear_correction_type.clear(); + loop->GetCalib("FCAL/nonlinear_correction_type", nonlinear_correction_type); + if (nonlinear_correction_type.size() > 0 && USE_NONLINEAR_CORRECTION_TYPE < 0) { + if (debug_level > 0) { + TString str_coef[] = {"A"}; + jout << Form(" %s", str_coef[0].Data()) << nonlinear_correction_type[0]; + jout << endl; + } + + if (nonlinear_correction_type[0] == 0) { + LOAD_NONLIN_CCDB = true; + } else if (nonlinear_correction_type[0] == 1) { + LOAD_NONLIN_CCDB = true; + expfit_param1 = 2; + expfit_param1 = 0; + expfit_param1 = 0; + SHOWER_POSITION_LOG = true; + USE_RING_E_CORRECTION_V1 = true; + USE_RING_E_CORRECTION_V2 = false; + USE_CPP_E_CORRECTION = false; + } else if (nonlinear_correction_type[0] == 2) { + LOAD_NONLIN_CCDB = true; + expfit_param1 = 2; + expfit_param1 = 0; + expfit_param1 = 0; + SHOWER_POSITION_LOG = true; + USE_RING_E_CORRECTION_V1 = false; + USE_RING_E_CORRECTION_V2 = true; + USE_CPP_E_CORRECTION = false; + } else if (nonlinear_correction_type[0] == 3) { + LOAD_NONLIN_CCDB = true; + SHOWER_POSITION_LOG = true; + USE_RING_E_CORRECTION_V1 = false; + USE_RING_E_CORRECTION_V2 = false; + USE_CPP_E_CORRECTION = true; + } + } + // but allow these to be overridden by command line parameters energy_dependence_correction_vs_ring.clear(); + nonlinear_correction.clear(); + nonlinear_correction_cpp.clear(); + block_to_square.clear(); if(LOAD_NONLIN_CCDB) { map shower_calib_piecewise; loop->GetCalib("FCAL/shower_calib_piecewise", shower_calib_piecewise); @@ -175,7 +253,9 @@ jerror_t DFCALShower_factory::brun(JEventLoop *loop, int32_t runnumber) expfit_param3 = shower_calib_piecewise["expfit_param3"]; m_beamSpotX = 0; m_beamSpotY = 0; - + //expfit_param1 = 1.10358; + //expfit_param2 = 0.31385; + //expfit_param3 = -2.02585; if(debug_level>0) { jout << "cutoff_energy = " << cutoff_energy << endl; jout << "linfit_slope = " << linfit_slope << endl; @@ -199,8 +279,44 @@ jerror_t DFCALShower_factory::brun(JEventLoop *loop, int32_t runnumber) } } } + loop->GetCalib("FCAL/nonlinear_correction", nonlinear_correction); + if (nonlinear_correction.size() > 0) { + m_beamSpotX = beam_spot.at("x"); + m_beamSpotY = beam_spot.at("y"); + if (debug_level > 0) { + TString str_coef[] = {"A", "B", "C", "D", "E", "F", "G", "H", "I"}; + for (int i = 0; i < 5; i ++) { + //for (int j = 0; j < 6; j ++) { + for (int j = 0; j < 9; j ++) { + jout << "Ring # " << i << Form(" %s", str_coef[j].Data()) << nonlinear_correction[i][j]; + } + jout << endl; + } + } + } + + loop->GetCalib("FCAL/block_to_square", block_to_square); + if (block_to_square.size() > 0) { + if (debug_level > 0) { + for (int i = 0; i < (int) block_to_square.size(); i ++) { + jout << block_to_square[i]; + } + jout << endl; + } + } + + loop->GetCalib("FCAL/nonlinear_correction_cpp", nonlinear_correction_cpp); + if (nonlinear_correction_cpp.size() > 0) { + m_beamSpotX = beam_spot.at("x"); + m_beamSpotY = beam_spot.at("y"); + if (debug_level > 0) { + for (int i = 0; i < (int) nonlinear_correction_cpp.size(); i ++) { + jout << nonlinear_correction_cpp[i]; + } + jout << endl; + } + } } - if (LOAD_TIMING_CCDB) { // Get timing correction polynomial, J. Mirabelli 10/31/17 map timing_correction; @@ -320,18 +436,24 @@ jerror_t DFCALShower_factory::evnt(JEventLoop *eventLoop, uint64_t eventnumber) } else{ // Some guesses for insert resolution - double sigx=INSERT_POS_RES1/sqrt(Ecorrected)+INSERT_POS_RES2; + double phi=pos_corrected.Phi(); + double fsinphi=fabs(sin(phi)); + double fcosphi=fabs(cos(phi)); + double sigx=(INSERT_POS_RES1+INSERT_POS_PHI1*fsinphi)/sqrt(Ecorrected) + +INSERT_POS_RES2+INSERT_POS_PHI2*fsinphi; + double sigy=(INSERT_POS_RES1+INSERT_POS_PHI1*fcosphi)/sqrt(Ecorrected) + +INSERT_POS_RES2+INSERT_POS_PHI2*fcosphi; shower->ExyztCovariance(1,1)=sigx*sigx; - shower->ExyztCovariance(2,2)=sigx*sigx; + shower->ExyztCovariance(2,2)=sigy*sigy; shower->ExyztCovariance(0,0) =Ecorrected*Ecorrected*(INSERT_E_VAR1/Ecorrected + INSERT_E_VAR2/(Ecorrected*Ecorrected) + INSERT_E_VAR3); + // Make sure off-diagonal elements are zero, for now... for (unsigned int i=0;i<5;i++){ for(unsigned int j=0;j<5;j++){ if (i!=j) shower->ExyztCovariance(i,j)=0.; } - } } @@ -437,7 +559,11 @@ jerror_t DFCALShower_factory::evnt(JEventLoop *eventLoop, uint64_t eventnumber) //int MAXITER = 1000; DVector3 posInCal = cluster->getCentroid(); - + int block = cluster->getChannelEmax(); + int square_nb = -1; + if (USE_CPP_E_CORRECTION) + square_nb = block_to_square[block]; + float x0 = posInCal.Px(); float y0 = posInCal.Py(); double Eclust = cluster->getEnergy(); @@ -448,9 +574,15 @@ jerror_t DFCALShower_factory::evnt(JEventLoop *eventLoop, uint64_t eventnumber) double C = 0; double D = 0; double E = 0; + double F = 0; + double G = 0; + double H = 0; + double I = 0; double Egamma = Eclust; Ecorrected = 0; + + // block properties double radiation_length=FCAL_RADIATION_LENGTH; double shower_offset=FCAL_SHOWER_OFFSET; @@ -465,10 +597,9 @@ jerror_t DFCALShower_factory::evnt(JEventLoop *eventLoop, uint64_t eventnumber) zfront=m_insertFront; Egamma=INSERT_PAR1*sqrt(Eclust)+INSERT_PAR2*Eclust; - } - else{ - // 06/04/2020 ijaegle@jlab.org allows two different energy dependence correction - if (USE_RING_E_CORRECTION && energy_dependence_correction_vs_ring.size()>0){ + } else { + // 06/04/2020 ijaegle@jlab.org allows two different energy dependence correction + if (USE_RING_E_CORRECTION_V1 && energy_dependence_correction_vs_ring.size() > 0) { // Method II: PRIMEXD way, correction per ring Egamma=Eclust; // Initialize, before correction int ring_region = -1; @@ -502,8 +633,36 @@ jerror_t DFCALShower_factory::evnt(JEventLoop *eventLoop, uint64_t eventnumber) //Egamma = Eclust / (A + B * Eclust + C * pow(Eclust, 2)); Egamma = Eclust / (A - exp(-B * Eclust + C)); } - // End Correction method II - } else { + } else if (USE_RING_E_CORRECTION_V2 && nonlinear_correction.size() > 0) { + // Method III: E/P method, correction per for the first 4 then one correction for ring 5 to 23 + Egamma=Eclust; // Initialize, before correction + int ring_region = -1; + if (ring_nb == 1) + ring_region = 0; + else if (ring_nb == 2) + ring_region = 1; + else if (ring_nb == 3) + ring_region = 2; + else if (ring_nb == 4) + ring_region = 3; + else if (5 <= ring_nb) + ring_region = 4; + if (ring_region != -1) { + Egamma = 0; + A = nonlinear_correction[ring_region][0]; + B = nonlinear_correction[ring_region][1]; + C = nonlinear_correction[ring_region][2]; + D = nonlinear_correction[ring_region][3]; + E = nonlinear_correction[ring_region][4]; + F = nonlinear_correction[ring_region][5]; + G = nonlinear_correction[ring_region][6]; + H = nonlinear_correction[ring_region][7]; + I = nonlinear_correction[ring_region][8]; + //[0]-[1]*exp(-[2]*x+[3]) -[4]/([5]+[6]*exp(-x*[7]+[8]) + Egamma = Eclust / (A - B * exp(-C * Eclust + D) - E / (F + G * exp(-Eclust * H + I))); + } + // End Correction method III + } else if (LOAD_NONLIN_CCDB && !USE_RING_E_CORRECTION_V2 && !USE_RING_E_CORRECTION_V1) { // Method I: IU way, one overall correction Egamma = 0; Ecutoff = cutoff_energy; @@ -523,7 +682,29 @@ jerror_t DFCALShower_factory::evnt(JEventLoop *eventLoop, uint64_t eventnumber) // if all C=D=E=0 by mistake then Egamma = - Eclust Egamma = Eclust / (C - exp(-D * Eclust + E)); // Non-linear part } - } // End Correction method I + //cout <<"Eclust " << Eclust << " Egamma " << Egamma << " A " << A << " B " << B << " C " << C << " D " << D << " E " << E << endl; + } // End Correction method I + + if (USE_CPP_E_CORRECTION && !USE_RING_E_CORRECTION_V2 && !USE_RING_E_CORRECTION_V1) { + double scalef = nonlinear_correction_cpp[0]; + if (square_nb >= 0 && square_nb <= 13) { + double Eshift = 0; + if (square_nb == 10) { + Eshift = atan(nonlinear_correction_cpp[4 + square_nb * 3] * Egamma + nonlinear_correction_cpp[5 + square_nb * 3]); + Eshift *= nonlinear_correction_cpp[3 + square_nb * 3] * Eshift; + } else { + Eshift = nonlinear_correction_cpp[3 + square_nb * 3] * atan(nonlinear_correction_cpp[4 + square_nb * 3] * Egamma + nonlinear_correction_cpp[5 + square_nb * 3]); + } + Eshift = scalef * Eshift; + if (Eshift > 0.) { + Egamma *= (1. + nonlinear_correction_cpp[1] * 1.e-2 * Egamma + nonlinear_correction_cpp[2] * 1.e-2 * Egamma * Egamma) / Eshift; + } else { + if (VERBOSE > 3) jerr << "CPP nonlinear correction has a wrong Eshift" << endl; + } + } else { + if (VERBOSE > 3) jerr << "CPP nonlinear correction has no square_nb" << endl; + } + } } //End energy dependence correction @@ -555,11 +736,12 @@ jerror_t DFCALShower_factory::evnt(JEventLoop *eventLoop, uint64_t eventnumber) posInCal.SetZ( zed + zV ); errZ = zed - zed1; + } Ecorrected = Egamma; pos_corrected = posInCal; - + } diff --git a/src/libraries/FCAL/DFCALShower_factory.h b/src/libraries/FCAL/DFCALShower_factory.h index 28b34cbf25..282d4abbb4 100644 --- a/src/libraries/FCAL/DFCALShower_factory.h +++ b/src/libraries/FCAL/DFCALShower_factory.h @@ -62,10 +62,13 @@ class DFCALShower_factory:public JFactory{ double m_FCALdX,m_FCALdY; double m_beamSpotX; double m_beamSpotY; + int USE_NONLINEAR_CORRECTION_TYPE; bool LOAD_NONLIN_CCDB; bool LOAD_TIMING_CCDB; bool LOAD_CCDB_CONSTANTS; - bool USE_RING_E_CORRECTION; + bool USE_RING_E_CORRECTION_V1; + bool USE_RING_E_CORRECTION_V2; + bool USE_CPP_E_CORRECTION; bool SHOWER_POSITION_LOG; double SHOWER_ENERGY_THRESHOLD; double cutoff_energy; @@ -75,7 +78,14 @@ class DFCALShower_factory:public JFactory{ double expfit_param2; double expfit_param3; + //V1 based on pi^0 vector < vector > energy_dependence_correction_vs_ring; + //V2 based on E/P + vector < vector > nonlinear_correction; + vector nonlinear_correction_cpp; + vector block_to_square; + //Choose directly in DB which non-linear correction version to use + vector nonlinear_correction_type; double timeConst0; double timeConst1; @@ -96,6 +106,7 @@ class DFCALShower_factory:public JFactory{ double INSERT_C_EFFECTIVE; double m_insertFront; double INSERT_POS_RES1,INSERT_POS_RES2; + double INSERT_POS_PHI1,INSERT_POS_PHI2; double INSERT_E_VAR1,INSERT_E_VAR2,INSERT_E_VAR3; const DFCALGeometry *fcalGeom=NULL; diff --git a/src/libraries/FMWPC/DCPPEpEm_factory.cc b/src/libraries/FMWPC/DCPPEpEm_factory.cc index ee9bd15463..f89f3f09c8 100644 --- a/src/libraries/FMWPC/DCPPEpEm_factory.cc +++ b/src/libraries/FMWPC/DCPPEpEm_factory.cc @@ -123,13 +123,13 @@ jerror_t DCPPEpEm_factory::evnt(JEventLoop *loop, uint64_t eventnumber) unsigned int ip=(q1>q2)?0:1; unsigned int in=(q1>q2)?1:0; - hyp=tracks[ip]->Get_Hypothesis(PiPlus); - if (hyp==NULL) return RESOURCE_UNAVAILABLE; - const DTrackTimeBased *piplus=hyp->Get_TrackTimeBased(); + const DChargedTrackHypothesis *PiPhyp=tracks[ip]->Get_Hypothesis(PiPlus); + if (PiPhyp==NULL) return RESOURCE_UNAVAILABLE; + const DTrackTimeBased *piplus=PiPhyp->Get_TrackTimeBased(); - hyp=tracks[in]->Get_Hypothesis(PiMinus); - if (hyp==NULL) return RESOURCE_UNAVAILABLE; - const DTrackTimeBased *piminus=hyp->Get_TrackTimeBased(); + const DChargedTrackHypothesis *PiMhyp=tracks[in]->Get_Hypothesis(PiMinus); + if (PiMhyp==NULL) return RESOURCE_UNAVAILABLE; + const DTrackTimeBased *piminus=PiMhyp->Get_TrackTimeBased(); hyp=tracks[ip]->Get_Hypothesis(KPlus); if (hyp==NULL) return RESOURCE_UNAVAILABLE; @@ -285,7 +285,7 @@ jerror_t DCPPEpEm_factory::evnt(JEventLoop *loop, uint64_t eventnumber) // n.b. if we need to use a mutex then we should pass a local // array for "input" and the lock the mutex just for the copy // to the tflite tensor. - if( PiMuFillFeatures(loop, piplus, piminus, pimu_input) ){ + if( PiMuFillFeatures(loop, tracks.size(), PiPhyp, PiMhyp, pimu_input) ){ // Run inference if( pimu_interpreter->Invoke() == kTfLiteOk){ @@ -418,26 +418,9 @@ bool DCPPEpEm_factory::VetoNeutrals(double t0_rf,const DVector3 &vect, // Return true if values are valid, false otherwise. // e.g. return false if there is not at least 1 pi+ // and 1 pi- candidate. -bool DCPPEpEm_factory::PiMuFillFeatures(jana::JEventLoop *loop, const DTrackTimeBased *piplus, const DTrackTimeBased *piminus, float *features){ - - vector matchedtracks; - loop->Get( matchedtracks ); - - // Find the DFMWPCMatchedTrack objects corresponding to - // the piplus, piminus tracks used in for the kinematic fit - // (i.e. the ones passed into this method as arguments) - const DFMWPCMatchedTrack *piplus_mt = nullptr; - const DFMWPCMatchedTrack *piminus_mt = nullptr; - for( auto mt : matchedtracks ){ - const DTrackTimeBased *trk; - mt->GetSingleT(trk); - if( trk == piplus ) piplus_mt = mt; - if( trk == piminus ) piminus_mt = mt; - } - - // Must have a DFMWPCMatchedTrack for both a pi+ and pi- - if( (piplus_mt==nullptr) || (piminus_mt==nullptr) ) return false; - +bool DCPPEpEm_factory::PiMuFillFeatures(jana::JEventLoop *loop, unsigned int nChargedTracks,const DChargedTrackHypothesis *PiPhyp, const DChargedTrackHypothesis *PiMhyp, float *features){ + memset(features,0,47*sizeof(float)); + // Features list is the following: // 0 nChargedTracks // 1 nFCALShowers @@ -487,53 +470,82 @@ bool DCPPEpEm_factory::PiMuFillFeatures(jana::JEventLoop *loop, const DTrackTime // 45 FMWPC_dist_closest_wire6_9 // 46 FMWPC_Nhits_cluster6_9 - vector chargedtracks; vector fcalshowers; vector fcalhits; vector fmwpchits; - loop->Get( chargedtracks ); + vectorstats; + loop->Get( stats ); loop->Get( fcalshowers ); loop->Get( fcalhits ); loop->Get( fmwpchits ); - features[ 0] = chargedtracks.size(); + features[ 0] = nChargedTracks; features[ 1] = fcalshowers.size(); - features[ 2] = fcalhits.size(); + features[ 2] = (stats.size()>0) ? stats[0]->fcal_blocks : fcalhits.size(); features[ 3] = fmwpchits.size(); - features[ 4] = matchedtracks.size(); - features[ 5] = piplus_mt->FCAL_E_center; - features[ 6] = piplus_mt->FCAL_E_3x3; - features[ 7] = piplus_mt->FCAL_E_5x5; - for(int ilayer=0; ilayer<6; ilayer++){ - features[ 8+3*ilayer] = piplus_mt->FMWPC_closest_wire[ilayer]; - features[ 9+3*ilayer] = piplus_mt->FMWPC_dist_closest_wire[ilayer]; - features[10+3*ilayer] = piplus_mt->FMWPC_Nhits_cluster[ilayer]; - } - features[26] = piminus_mt->FCAL_E_center; - features[27] = piminus_mt->FCAL_E_3x3; - features[28] = piminus_mt->FCAL_E_5x5; - for(int ilayer=0; ilayer<6; ilayer++){ - features[29+3*ilayer] = piminus_mt->FMWPC_closest_wire[ilayer]; - features[30+3*ilayer] = piminus_mt->FMWPC_dist_closest_wire[ilayer]; - features[31+3*ilayer] = piminus_mt->FMWPC_Nhits_cluster[ilayer]; + features[ 4] = 4; // lepton and pion tracks found + + // Match to FCAL for pi+ hypothesis + shared_ptrfcalparms=PiPhyp->Get_FCALShowerMatchParams(); + if (fcalparms!=nullptr){ + features[ 5] = fcalparms->dEcenter; + features[ 6] = fcalparms->dE3x3; + features[ 7] = fcalparms->dE5x5; } - + // Match to FMWPCs for pi+ hypothesis + shared_ptrfmwpcparms=PiPhyp->Get_FMWPCMatchParams(); // Before training the model, Nikhil's code replaced feature values // where the distance to the closest wire was >30 with values used // to indicate no wire hit. - for(int ilayer=0; ilayer<6; ilayer++){ - if( piminus_mt->FMWPC_dist_closest_wire[ilayer] >30.0 ){ - features[29+3*ilayer] = -1000.0; - features[30+3*ilayer] = 1000000; - features[31+3*ilayer] = 0; + for (int ilayer=0; ilayer<6; ilayer++){ + features[ 8+3*ilayer] = -1000.0; + features[ 9+3*ilayer] = 1000000; + features[10+3*ilayer] = 0; + } + if (fmwpcparms!=nullptr){ + for (unsigned int i=0;idLayers.size();i++){ + if (fmwpcparms->dDists[i]<30){ + int ilayer=fmwpcparms->dLayers[i]-1; + features[ 8+3*ilayer] = fmwpcparms->dClosestWires[i]; + features[ 9+3*ilayer] = fmwpcparms->dDists[i]; + features[10+3*ilayer] = fmwpcparms->dNhits[i]; + } } } + // Match to FCAL for pi- hypothesis + fcalparms=PiMhyp->Get_FCALShowerMatchParams(); + if (fcalparms!=nullptr){ + features[26] = fcalparms->dEcenter; + features[27] = fcalparms->dE3x3; + features[28] = fcalparms->dE5x5; + } + // Match to FMWPCs for pi- hypothesis + fmwpcparms=PiMhyp->Get_FMWPCMatchParams(); + // Before training the model, Nikhil's code replaced feature values + // where the distance to the closest wire was >30 with values used + // to indicate no wire hit. + for (int ilayer=0; ilayer<6; ilayer++){ + features[29+3*ilayer] = -1000.0; + features[30+3*ilayer] = 1000000; + features[31+3*ilayer] = 0; + } + if (fmwpcparms!=nullptr){ + for (unsigned int i=0;idLayers.size();i++){ + if (fmwpcparms->dDists[i]<30){ + int ilayer=fmwpcparms->dLayers[i]-1; + features[29+3*ilayer] = fmwpcparms->dClosestWires[i]; + features[30+3*ilayer] = fmwpcparms->dDists[i]; + features[31+3*ilayer] = fmwpcparms->dNhits[i]; + } + } + } + // These are values Nikhil sent that were used for normalizing the // features before training the model. static const float feature_min[] = {2.0,0.0,2.0,0.0,2.0,0.0,0.0,0.0,-1000.0,0.0,0.0,-1000.0,0.0,0.0,-1000.0,0.0,0.0,-1000.0,0.0,0.0,-1000.0,0.0,0.0,-1000.0,0.0,0.0,0.0,0.0,0.0,-1000.0,0.0,0.0,-1000.0,0.0,0.0,-1000.0,0.0,0.0,-1000.0,0.0,0.0,-1000.0,0.0,0.0,-1000.0,0.0,0.0,0.0}; static const float feature_max[] = {6.0,10.0,20.0,94.0,8.0,3.924656391143799,5.177245497703552,5.349521217867732,144.0,1000000.0,39.0,144.0,1000000.0,17.0,144.0,1000000.0,12.0,144.0,1000000.0,11.0,144.0,1000000.0,8.0,144.0,1000000.0,7.0,4.154212951660156,5.578885164111853,5.9553504548966885,144.0,1000000.0,39.0,144.0,1000000.0,32.0,144.0,1000000.0,14.0,144.0,1000000.0,35.0,144.0,1000000.0,7.0,144.0,1000000.0,11.0,1.0}; - for(int i=0; i<48; i++){ + for(int i=0; i<47; i++){ features[i] = (features[i] - feature_min[i])/(feature_max[i]-feature_min[i]); } diff --git a/src/libraries/FMWPC/DCPPEpEm_factory.h b/src/libraries/FMWPC/DCPPEpEm_factory.h index 4712d6c542..d957f01c2c 100644 --- a/src/libraries/FMWPC/DCPPEpEm_factory.h +++ b/src/libraries/FMWPC/DCPPEpEm_factory.h @@ -28,6 +28,7 @@ #include #include #include +#include class ReadMLPMinus; @@ -56,7 +57,7 @@ void DoKinematicFit(const DBeamPhoton *beamphoton, bool VetoNeutrals(double t0_rf,const DVector3 &vect, vector&neutrals) const; -bool PiMuFillFeatures(jana::JEventLoop *loop, const DTrackTimeBased *piplus, const DTrackTimeBased *piminus, float *features); + bool PiMuFillFeatures(jana::JEventLoop *loop, unsigned int nChargedTracks,const DChargedTrackHypothesis *piplus, const DChargedTrackHypothesis *piminus, float *features); double SPLIT_CUT,FCAL_THRESHOLD,BCAL_THRESHOLD,GAMMA_DT_CUT; string PIMU_MODEL_FILE; diff --git a/src/libraries/FMWPC/DCTOFHit_factory.cc b/src/libraries/FMWPC/DCTOFHit_factory.cc index 235aa85570..6e5ab2ebce 100644 --- a/src/libraries/FMWPC/DCTOFHit_factory.cc +++ b/src/libraries/FMWPC/DCTOFHit_factory.cc @@ -73,7 +73,7 @@ jerror_t DCTOFHit_factory::evnt(JEventLoop *loop, uint64_t eventnumber) vector tdcdigihits; loop->Get(tdcdigihits); - for(unsigned int i=0; i members; ///< DFMWPCHits that make up this cluster int layer; ///< #1-6 FMWPC layer + int orientation; ///< Vertical/Horizontal + float xoffset,yoffset; ///< x and y offsets of wires float q; ///< total charge in the cluster float u; ///< center of gravity of cluster in wire coordinates int first_wire; ///< first wire in cluster 1-144 int last_wire; ///< last wire in cluster 1-144 int Nhits; ///< Number of wire hits in cluster - DVector3 pos; ///< position (x,y,z) in global coodinates + DVector3 pos; ///< position (x,y,z) in global coordinates float t; // time in ns // This method is used primarily for pretty printing // the second argument to AddString is printf style format void toStrings(vector > &items)const{ AddString(items, "layer", "%d", layer); + AddString(items, "orientation", "%d", orientation); AddString(items, "q", "%10.2f", q); AddString(items, "u", "%3.4f", u); AddString(items, "first_wire", "%3d", first_wire); diff --git a/src/libraries/FMWPC/DFMWPCCluster_factory.cc b/src/libraries/FMWPC/DFMWPCCluster_factory.cc index bf57b2a105..c99e87a447 100644 --- a/src/libraries/FMWPC/DFMWPCCluster_factory.cc +++ b/src/libraries/FMWPC/DFMWPCCluster_factory.cc @@ -184,6 +184,9 @@ void DFMWPCCluster_factory::pique(vector& H) // global coordinate system // set to -777 for not measured coordinate auto orientation = fmwpc_wire_orientation[newCluster->layer-1]; + newCluster->orientation=orientation; + newCluster->xoffset=xvec[newCluster->layer-1]; + newCluster->yoffset=yvec[newCluster->layer-1]; double x = (orientation==DGeometry::kFMWPC_WIRE_ORIENTATION_VERTICAL ) ? xvec[newCluster->layer-1]+(newCluster->u-72.5)*FMWPC_WIRE_SPACING : -777 ; double y = (orientation==DGeometry::kFMWPC_WIRE_ORIENTATION_HORIZONTAL) ? yvec[newCluster->layer-1]+(newCluster->u-72.5)*FMWPC_WIRE_SPACING : -777 ; double z = zvec[newCluster->layer-1]; diff --git a/src/libraries/FMWPC/DFMWPCHit.h b/src/libraries/FMWPC/DFMWPCHit.h index 44fe7a4b6f..5c7d7acbc5 100644 --- a/src/libraries/FMWPC/DFMWPCHit.h +++ b/src/libraries/FMWPC/DFMWPCHit.h @@ -22,6 +22,7 @@ class DFMWPCHit:public JObject{ float amp; // peak amplitude float t; // time in ns int QF; // quality factor + float ped; // pedestal void toStrings(vector >&items) const { AddString(items, "layer", "%d", layer); @@ -30,6 +31,7 @@ class DFMWPCHit:public JObject{ AddString(items, "amp", "%10.2f", amp); AddString(items, "t", "%3.3f", t); AddString(items, "QF", "%d", QF); + AddString(items, "ped", "%10.2f", ped); } }; diff --git a/src/libraries/FMWPC/DFMWPCHit_factory.cc b/src/libraries/FMWPC/DFMWPCHit_factory.cc index a1637bdf49..13dff01653 100644 --- a/src/libraries/FMWPC/DFMWPCHit_factory.cc +++ b/src/libraries/FMWPC/DFMWPCHit_factory.cc @@ -16,8 +16,6 @@ using namespace std; using namespace jana; -static int FMWPC_HIT_THRESHOLD = 700; - //#define ENABLE_UPSAMPLING //------------------ @@ -26,9 +24,11 @@ static int FMWPC_HIT_THRESHOLD = 700; jerror_t DFMWPCHit_factory::init(void) { - gPARMS->SetDefaultParameter("FMWPC:FMWPC_HIT_THRESHOLD", FMWPC_HIT_THRESHOLD, - "Remove FMWPC Hits with peak amplitudes smaller than FMWPC_HIT_THRESHOLD"); - + hit_threshold = 0.; + + t_raw_min = -10000.; + t_raw_max = 10000.; + // default values a_scale = 0.; t_scale = 0.; @@ -66,9 +66,35 @@ jerror_t DFMWPCHit_factory::brun(jana::JEventLoop *eventLoop, int32_t runnumber) } pthread_mutex_unlock(&print_mutex); - // load geometry from XML here!! - + // Read in calibration constants + if(print_messages) jout << "In DFMWPCHit_factory, loading constants..." << std::endl; + + if (eventLoop->GetCalib("/FMWPC/hit_threshold", hit_threshold)){ + hit_threshold = 0.; + jout << "Error loading /FMWPC/hit_threshold ! set default value to 0." << endl; + } else { + jout << "FMWPC Hit Threshold: " << hit_threshold << endl; + } + + gPARMS->SetDefaultParameter("FMWPC:FMWPC_HIT_THRESHOLD", hit_threshold, + "Remove FMWPC Hits with peak amplitudes smaller than FMWPC_HIT_THRESHOLD"); + + vector fmwpc_timing_cuts; + + if (eventLoop->GetCalib("/FMWPC/timing_cut", fmwpc_timing_cuts)){ + t_raw_min = -60.; + t_raw_max = 900.; + jout << "Error loading /FMWPC/timing_cut ! set default values -60. and 900." << endl; + } else { + t_raw_min = fmwpc_timing_cuts[0]; + t_raw_max = fmwpc_timing_cuts[1]; + jout << "FMWPC Timing Cuts: " << t_raw_min << " ... " << t_raw_max << endl; + } + + gPARMS->SetDefaultParameter("FMWPCHit:t_raw_min", t_raw_min,"Minimum acceptable FMWPC hit time"); + gPARMS->SetDefaultParameter("FMWPCHit:t_raw_max", t_raw_max, "Maximum acceptable FMWPC hit time"); + // load scale factors map scale_factors; @@ -178,7 +204,7 @@ jerror_t DFMWPCHit_factory::evnt(JEventLoop *loop, uint64_t eventnumber) const DFMWPCDigiHit *digihit = digihits[i]; //if ( (digihit->QF & 0x1) != 0 ) continue; // Cut bad timing quality factor hits... (should check effect on efficiency) - if ( digihit->QF != 0 ) continue; // Cut bad timing quality factor hits... (should check effect on efficiency) + //if ( digihit->QF != 0 ) continue; // Cut bad timing quality factor hits... (should check effect on efficiency) const int &layer = digihit->layer; const int &wire = digihit->wire; @@ -199,14 +225,15 @@ jerror_t DFMWPCHit_factory::evnt(JEventLoop *loop, uint64_t eventnumber) // Grab the pedestal from the digihit since this should be consistent between the old and new formats int raw_ped = digihit->pedestal; int maxamp = digihit->pulse_peak; - int nsamples_integral = 0; // actual number computed below using config info + // int nsamples_integral = 0; // actual number computed below using config info // There are a few values from the new data type that are critical for the interpretation of the data - uint16_t IBIT = 0; // 2^{IBIT} Scale factor for integral - uint16_t ABIT = 0; // 2^{ABIT} Scale factor for amplitude - uint16_t PBIT = 0; // 2^{PBIT} Scale factor for pedestal - uint16_t NW = 0; + // uint16_t IBIT = 0; // 2^{IBIT} Scale factor for integral + // uint16_t ABIT = 0; // 2^{ABIT} Scale factor for amplitude + // uint16_t PBIT = 0; // 2^{PBIT} Scale factor for pedestal + // uint16_t NW = 0; + /* COMMENTED OUT TO WRITE UNCALIBRATED HITS TO REST // Configuration data needed to interpret the hits is stored in the data stream vector configs; digihit->Get(configs); @@ -220,13 +247,13 @@ jerror_t DFMWPCHit_factory::evnt(JEventLoop *loop, uint64_t eventnumber) } else { // Set some constants to defaults until they appear correctly in the config words in the future const Df125Config *config = configs[0]; - IBIT = config->IBIT == 0xffff ? 4 : config->IBIT; + // IBIT = config->IBIT == 0xffff ? 4 : config->IBIT; ABIT = config->ABIT == 0xffff ? 3 : config->ABIT; PBIT = config->PBIT == 0xffff ? 0 : config->PBIT; - NW = config->NW == 0xffff ? 200 : config->NW; + // NW = config->NW == 0xffff ? 200 : config->NW; } - nsamples_integral = (NW - (digihit->pulse_time / 10)); + // nsamples_integral = (NW - (digihit->pulse_time / 10)); // Complete the pedestal subtraction here since we should know the correct number of samples. int scaled_ped = raw_ped << PBIT; @@ -235,14 +262,15 @@ jerror_t DFMWPCHit_factory::evnt(JEventLoop *loop, uint64_t eventnumber) if (maxamp <= scaled_ped) continue; maxamp = maxamp - scaled_ped; + */ - if (maxamppulse_time); - if (t_raw < 250 || t_raw > 450) + if (t_raw <= t_raw_min || t_raw >= t_raw_max) continue; // Scale factor to account for gain variation @@ -255,8 +283,13 @@ jerror_t DFMWPCHit_factory::evnt(JEventLoop *loop, uint64_t eventnumber) // continue; // double q = a_scale *gain * double((digihit->pulse_integral<pulse_integral); + double amp = gain*double(maxamp); + double ped = double(raw_ped); double t = t_scale * t_raw - time_offsets[layer_i][wire_i] + t_base; @@ -271,6 +304,7 @@ jerror_t DFMWPCHit_factory::evnt(JEventLoop *loop, uint64_t eventnumber) hit->t = t; // hit->d = 0.0; hit->QF = digihit->QF; + hit->ped = ped; // hit->itrack = -1; // hit->ptype = 0; diff --git a/src/libraries/FMWPC/DFMWPCHit_factory.h b/src/libraries/FMWPC/DFMWPCHit_factory.h index bf2cc923d6..7c8da02eb8 100644 --- a/src/libraries/FMWPC/DFMWPCHit_factory.h +++ b/src/libraries/FMWPC/DFMWPCHit_factory.h @@ -28,6 +28,13 @@ class DFMWPCHit_factory:public jana::JFactory{ ~DFMWPCHit_factory(){}; // const char* Tag(void){return "";} + // hit threshold + double hit_threshold; + + // timing cut limits + double t_raw_min; + double t_raw_max; + // overall scale factors. double a_scale, amp_a_scale; double t_scale; diff --git a/src/libraries/HDDM/DEventHitStatistics.h b/src/libraries/HDDM/DEventHitStatistics.h index 8f54c38397..7368228a6e 100644 --- a/src/libraries/HDDM/DEventHitStatistics.h +++ b/src/libraries/HDDM/DEventHitStatistics.h @@ -20,6 +20,7 @@ class DEventHitStatistics:public jana::JObject{ int fdc_pseudos; int bcal_cells; int fcal_blocks; + int ecal_blocks; int ccal_blocks; int tof_paddles; int dirc_PMTs; @@ -30,6 +31,7 @@ class DEventHitStatistics:public jana::JObject{ AddString(items, "fdc pseudo-hits", "%d", fdc_pseudos); AddString(items, "bcal cells hit", "%d", bcal_cells); AddString(items, "fcal blocks hit", "%d", fcal_blocks); + AddString(items, "ecal blocks hit", "%d", ecal_blocks); AddString(items, "ccal blocks hit", "%d", ccal_blocks); AddString(items, "tof paddle hits","%d", tof_paddles); AddString(items, "dirc PMT hits","%d", dirc_PMTs); diff --git a/src/libraries/HDDM/DEventHitStatistics_factory.cc b/src/libraries/HDDM/DEventHitStatistics_factory.cc index 3a88979541..3e5c6f9a4c 100644 --- a/src/libraries/HDDM/DEventHitStatistics_factory.cc +++ b/src/libraries/HDDM/DEventHitStatistics_factory.cc @@ -15,6 +15,7 @@ #include #include #include +#include #include #include @@ -77,6 +78,11 @@ jerror_t DEventHitStatistics_factory::evnt(JEventLoop *loop, uint64_t eventnumbe loop->Get(hits); stats->fcal_blocks = hits.size(); } + { + vector hits; + loop->Get(hits); + stats->ecal_blocks = hits.size(); + } { vector hits; loop->Get(hits); diff --git a/src/libraries/HDDM/DEventSourceHDDM.cc b/src/libraries/HDDM/DEventSourceHDDM.cc index a6e85d999e..1bcb118622 100644 --- a/src/libraries/HDDM/DEventSourceHDDM.cc +++ b/src/libraries/HDDM/DEventSourceHDDM.cc @@ -14,6 +14,7 @@ // June 22, 2015 J. Stevens: changed RICH -> DIRC and remove CERE // May 7, 2017 R. Dzhygadlo: added DDIRCTruthPmtHit DDIRCTruthBarHit // Oct 20, 2017 A. Somov: Added fields for the DPSHit/DPSCHit +// Jan 16, 2024 A. Somov: Added functions for ECAL // // DEventSourceHDDM methods // @@ -39,6 +40,8 @@ using namespace std; #include #include #include +#include +#include //------------------------------------------------------------------ @@ -404,6 +407,15 @@ jerror_t DEventSourceHDDM::GetObjects(JEvent &event, JFactory_base *factory) dynamic_cast*>(factory), tag, event.GetJEventLoop()); + if (dataClassName == "DECALTruthShower") + return Extract_DECALTruthShower(record, + dynamic_cast*>(factory), tag); + + if (dataClassName == "DECALHit") + return Extract_DECALHit(record, + dynamic_cast*>(factory), tag, + event.GetJEventLoop()); + if (dataClassName == "DCCALTruthShower") return Extract_DCCALTruthShower(record, dynamic_cast*>(factory), tag); @@ -600,6 +612,7 @@ jerror_t DEventSourceHDDM::Extract_DMCTrackHit(hddm_s::HDDM *record, GetTOFTruthHits(record, data); GetCherenkovTruthHits(record, data); GetFCALTruthHits(record, data); + GetECALTruthHits(record, data); GetSCTruthHits(record, data); // It has happened that some CDC hits have "nan" for the drift time @@ -788,6 +801,33 @@ jerror_t DEventSourceHDDM::GetFCALTruthHits(hddm_s::HDDM *record, return NOERROR; } +//------------------- +// GetECALTruthHits +//------------------- +jerror_t DEventSourceHDDM::GetECALTruthHits(hddm_s::HDDM *record, + vector& data) +{ + const hddm_s::EcalTruthShowerList &points = record->getEcalTruthShowers(); + hddm_s::EcalTruthShowerList::iterator iter; + for (iter = points.begin(); iter != points.end(); ++iter) { + float x = iter->getX(); + float y = iter->getY(); + DMCTrackHit *mctrackhit = new DMCTrackHit; + mctrackhit->r = sqrt(x*x + y*y); + mctrackhit->phi = atan2(y,x); + mctrackhit->z = iter->getZ(); + mctrackhit->track = iter->getTrack(); + mctrackhit->primary = iter->getPrimary(); + mctrackhit->ptype = iter->getPtype(); + mctrackhit->system = SYS_ECAL; + const hddm_s::TrackIDList &ids = iter->getTrackIDs(); + mctrackhit->itrack = (ids.size())? ids.begin()->getItrack() : 0; + data.push_back(mctrackhit); + } + + return NOERROR; +} + //------------------- // GetCCALTruthHits //------------------- @@ -1742,6 +1782,146 @@ jerror_t DEventSourceHDDM::Extract_DFCALHit(hddm_s::HDDM *record, return NOERROR; } + +///------------------ +// Extract_DECALTruthShower +//------------------ +jerror_t DEventSourceHDDM::Extract_DECALTruthShower(hddm_s::HDDM *record, + JFactory *factory, + string tag) +{ + /// Copies the data from the given hddm_s structure. This is called + /// from JEventSourceHDDM::GetObjects. If factory is NULL, this + /// returns OBJECT_NOT_AVAILABLE immediately. + + if (factory == NULL) + return OBJECT_NOT_AVAILABLE; + if (tag != "") + return OBJECT_NOT_AVAILABLE; + + vector data; + JObject::oid_t id=1; + + const hddm_s::EcalTruthShowerList &shows = record->getEcalTruthShowers(); + hddm_s::EcalTruthShowerList::iterator iter; + for (iter = shows.begin(); iter != shows.end(); ++iter) { + const hddm_s::TrackIDList &ids = iter->getTrackIDs(); + int itrack = (ids.size())? ids.begin()->getItrack() : 0; + DECALTruthShower *decaltruthshower = new DECALTruthShower( + id++, + iter->getX(), + iter->getY(), + iter->getZ(), + iter->getPx(), + iter->getPy(), + iter->getPz(), + iter->getE(), + iter->getT(), + iter->getPrimary(), + iter->getTrack(), + iter->getPtype(), + itrack + ); + data.push_back(decaltruthshower); + } + + // Copy into factory + factory->CopyTo(data); + + return NOERROR; +} + + +//------------------ +// Extract_DECALHit +//------------------ +jerror_t DEventSourceHDDM::Extract_DECALHit(hddm_s::HDDM *record, + JFactory *factory, string tag, + JEventLoop* eventLoop) +{ + /// Copies the data from the given hddm_s structure. This is called + /// from JEventSourceHDDM::GetObjects. If factory is NULL, this + /// returs OBJECT_NOT_AVAILABLE immediately. + + if (factory == NULL) + return OBJECT_NOT_AVAILABLE; + if (tag != "" && tag != "TRUTH") + return OBJECT_NOT_AVAILABLE; + + // extract the ECAL Geometry (for isBlockActive() and positionOnFace()) + vector ecalGeomVect; + eventLoop->Get( ecalGeomVect ); + if (ecalGeomVect.size() < 1) + return OBJECT_NOT_AVAILABLE; + const DECALGeometry& ecalGeom = *(ecalGeomVect[0]); + + vector data; + int hitId = 0; + + if (tag == "") { + + const hddm_s::EcalHitList &hits = record->getEcalHits(); + hddm_s::EcalHitList::iterator iter; + for (iter = hits.begin(); iter != hits.end(); ++iter) { + int row = iter->getRow(); + int column = iter->getColumn(); + + // Filter out non-physical blocks here + if (!ecalGeom.isBlockActive(row, column)) + continue; + + // Get position of blocks on front face. (This should really come from + // hdgeant directly so the poisitions can be shifted in mcsmear.) + DVector2 pos = ecalGeom.positionOnFace(row, column); + + DECALHit *mchit = new DECALHit(); + mchit->row = row; + mchit->column = column; + mchit->x = pos.X(); + mchit->y = pos.Y(); + mchit->E = iter->getE(); + mchit->t = iter->getT(); + mchit->id = hitId++; + mchit->intOverPeak = 5.; + data.push_back(mchit); + } + } + + else if (tag == "TRUTH") { + const hddm_s::EcalTruthHitList &hits = record->getEcalTruthHits(); + hddm_s::EcalTruthHitList::iterator iter; + for (iter = hits.begin(); iter != hits.end(); ++iter) { + int row = iter->getRow(); + int column = iter->getColumn(); + + // Filter out non-physical blocks here + if (!ecalGeom.isBlockActive(row, column)) + continue; + + // Get position of blocks on front face. (This should really come from + // hdgeant directly so the poisitions can be shifted in mcsmear.) + DVector2 pos = ecalGeom.positionOnFace(row, column); + + DECALHit *mchit = new DECALHit(); + mchit->row = row; + mchit->column = column; + mchit->x = pos.X(); + mchit->y = pos.Y(); + mchit->E = iter->getE(); + mchit->t = iter->getT(); + mchit->id = hitId++; + mchit->intOverPeak = 5.; + data.push_back(mchit); + } + } + + // Copy into factory + factory->CopyTo(data); + + return NOERROR; +} + + //------------------ // Extract_DCCALTruthShower //------------------ @@ -2915,6 +3095,7 @@ jerror_t DEventSourceHDDM::Extract_DCTOFHit(hddm_s::HDDM *record, JFactoryend = iter->getEnd(); hit->dE = iter->getDE(); hit->t = iter->getT(); + hit->t_adc = hit->t; data.push_back(hit); } diff --git a/src/libraries/HDDM/DEventSourceHDDM.h b/src/libraries/HDDM/DEventSourceHDDM.h index 98b76e3ca6..f52f26f5e6 100644 --- a/src/libraries/HDDM/DEventSourceHDDM.h +++ b/src/libraries/HDDM/DEventSourceHDDM.h @@ -10,6 +10,7 @@ // Oct 8, 2013 Yi Qiang: added dedicated object for RICH Truth Hit // June 22, 2015 J. Stevens: changed RICH -> DIRC and remove CERE // May 7, 2017 R. Dzhygadlo: added DDIRCTruthPmtHit DDIRCTruthBarHit +// Jan 16, 2024 A. Somov: added functions for ECAL #ifndef _JEVENT_SOURCEHDDM_H_ #define _JEVENT_SOURCEHDDM_H_ @@ -41,6 +42,8 @@ using namespace std; #include "FDC/DFDCHit.h" #include "FCAL/DFCALTruthShower.h" #include "FCAL/DFCALHit.h" +#include "ECAL/DECALTruthShower.h" +#include "ECAL/DECALHit.h" #include "CCAL/DCCALTruthShower.h" #include "CCAL/DCCALHit.h" #include "TOF/DTOFTruth.h" @@ -98,10 +101,11 @@ class DEventSourceHDDM:public JEventSource jerror_t GetTOFTruthHits(hddm_s::HDDM *record, vector& data); jerror_t GetCherenkovTruthHits(hddm_s::HDDM *record, vector& data); jerror_t GetFCALTruthHits(hddm_s::HDDM *record, vector& data); + jerror_t GetECALTruthHits(hddm_s::HDDM *record, vector& data); jerror_t GetCCALTruthHits(hddm_s::HDDM *record, vector& data); jerror_t GetSCTruthHits(hddm_s::HDDM *record, vector& data); - jerror_t Extract_DRFTime(hddm_s::HDDM *record, JFactory *factory, JEventLoop* locEventLoop); + jerror_t Extract_DRFTime(hddm_s::HDDM *record, JFactory *factory, JEventLoop* locEventLoop); jerror_t Extract_DBCALTruthShower(hddm_s::HDDM *record, JFactory *factory, string tag); jerror_t Extract_DBCALTruthCell(hddm_s::HDDM *record, JFactory *factory, string tag); jerror_t Extract_DBCALSiPMHit(hddm_s::HDDM *record, JFactory *factory, string tag); @@ -114,6 +118,8 @@ class DEventSourceHDDM:public JEventSource jerror_t Extract_DCDCHit(JEventLoop* locEventLoop, hddm_s::HDDM *record, JFactory *factory, string tag); jerror_t Extract_DFDCHit(hddm_s::HDDM *record, JFactory *factory, string tag); jerror_t Extract_DFCALTruthShower(hddm_s::HDDM *record, JFactory *factory, string tag); + jerror_t Extract_DECALHit(hddm_s::HDDM *record, JFactory *factory, string tag, JEventLoop* eventLoop); + jerror_t Extract_DECALTruthShower(hddm_s::HDDM *record, JFactory *factory, string tag); jerror_t Extract_DCCALHit(hddm_s::HDDM *record, JFactory *factory, string tag, JEventLoop* eventLoop); jerror_t Extract_DCCALTruthShower(hddm_s::HDDM *record, JFactory *factory, string tag); jerror_t Extract_DFCALHit(hddm_s::HDDM *record, JFactory *factory, string tag, JEventLoop* eventLoop); diff --git a/src/libraries/HDDM/DEventSourceREST.cc b/src/libraries/HDDM/DEventSourceREST.cc index bec097268e..277e4419f6 100644 --- a/src/libraries/HDDM/DEventSourceREST.cc +++ b/src/libraries/HDDM/DEventSourceREST.cc @@ -362,6 +362,10 @@ jerror_t DEventSourceREST::GetObjects(JEvent &event, JFactory_base *factory) return Extract_DTOFPoint(record, dynamic_cast*>(factory)); } + if (dataClassName =="DCTOFPoint") { + return Extract_DCTOFPoint(record, + dynamic_cast*>(factory)); + } if (dataClassName =="DSCHit") { return Extract_DSCHit(record, dynamic_cast*>(factory)); @@ -390,6 +394,10 @@ jerror_t DEventSourceREST::GetObjects(JEvent &event, JFactory_base *factory) return Extract_DDIRCPmtHit(record, dynamic_cast*>(factory), locEventLoop); } + if (dataClassName =="DFMWPCHit") { + return Extract_DFMWPCHit(record, + dynamic_cast*>(factory), locEventLoop); + } if (dataClassName =="DDetectorMatches") { return Extract_DDetectorMatches(locEventLoop, record, dynamic_cast*>(factory)); @@ -616,8 +624,6 @@ jerror_t DEventSourceREST::Extract_DBeamPhoton(hddm_r::HDDM *record, { if (locTAGMiter->getJtag() != tag) continue; - - DBeamPhoton* gamma = new DBeamPhoton(); // load the counter number (if it exists) and set the energy based on the counter unsigned int column = 0; @@ -650,12 +656,14 @@ jerror_t DEventSourceREST::Extract_DBeamPhoton(hddm_r::HDDM *record, continue; } - double Elo = tagmGeom->getElow(column); - double Ehi = tagmGeom->getEhigh(column); - double Ebeam = (Elo + Ehi)/2.; + DBeamPhoton* gamma = new DBeamPhoton(); + + double Elo_tagm = tagmGeom->getElow(column); + double Ehi_tagm = tagmGeom->getEhigh(column); + double Ebeam_tagm = (Elo_tagm + Ehi_tagm)/2.; // read the rest of the data from the REST file - DVector3 mom(0.0, 0.0, Ebeam); + DVector3 mom(0.0, 0.0, Ebeam_tagm); gamma->setPID(Gamma); gamma->setMomentum(mom); gamma->setPosition(pos); @@ -678,8 +686,6 @@ jerror_t DEventSourceREST::Extract_DBeamPhoton(hddm_r::HDDM *record, if (locTAGHiter->getJtag() != tag) continue; - DBeamPhoton* gamma = new DBeamPhoton(); - // load the counter number (if it exists) and set the energy based on the counter unsigned int counter = 0; hddm_r::TaghChannelList &locTaghChannelList = locTAGHiter->getTaghChannels(); @@ -687,7 +693,7 @@ jerror_t DEventSourceREST::Extract_DBeamPhoton(hddm_r::HDDM *record, // it's easy if the column is already set counter = locTaghChannelList().getCounter(); } else { - // if the TAGM column isn't saved in the REST file, then we do one of two things + // if the TAGH column isn't saved in the REST file, then we do one of two things // 1) if there's no special CCDB context associated with the file, we can just // reverse engineer the counter, assuming the latest CCDB // 2) If there is a special CCDB context specified, then use that instead @@ -711,7 +717,13 @@ jerror_t DEventSourceREST::Extract_DBeamPhoton(hddm_r::HDDM *record, continue; } - DVector3 mom(0.0, 0.0, locTAGHiter->getE()); + DBeamPhoton* gamma = new DBeamPhoton(); + + double Elo_tagh = taghGeom->getElow(counter); + double Ehi_tagh = taghGeom->getEhigh(counter); + double Ebeam_tagh = (Elo_tagh + Ehi_tagh)/2.; + + DVector3 mom(0.0, 0.0, Ebeam_tagh); gamma->setPID(Gamma); gamma->setMomentum(mom); gamma->setPosition(pos); @@ -877,6 +889,46 @@ jerror_t DEventSourceREST::Extract_DTOFPoint(hddm_r::HDDM *record, return NOERROR; } +//------------------ +// Extract_DCTOFPoint +//------------------ +jerror_t DEventSourceREST::Extract_DCTOFPoint(hddm_r::HDDM *record, + JFactory* factory) +{ + /// Copies the data from the ctofPoint hddm record. This is called + /// from JEventSourceREST::GetObjects. If factory is NULL, this + /// returns OBJECT_NOT_AVAILABLE immediately. + + if (factory==NULL) { + return OBJECT_NOT_AVAILABLE; + } + string tag = (factory->Tag())? factory->Tag() : ""; + + vector data; + + // loop over ctofPoint records + const hddm_r::CtofPointList &ctofs = record->getCtofPoints(); + hddm_r::CtofPointList::iterator iter; + for (iter = ctofs.begin(); iter != ctofs.end(); ++iter) { + if (iter->getJtag() != tag) { + continue; + } + DCTOFPoint *ctofpoint = new DCTOFPoint(); + ctofpoint->bar = iter->getBar(); + ctofpoint->pos = DVector3(iter->getX(),iter->getY(),iter->getZ()); + ctofpoint->t = iter->getT(); + ctofpoint->dE = iter->getDE(); + + data.push_back(ctofpoint); + } + + // Copy into factory + factory->CopyTo(data); + + return NOERROR; +} + + //------------------ // Extract_DSCHit //------------------ @@ -1537,7 +1589,10 @@ jerror_t DEventSourceREST::Extract_DDetectorMatches(JEventLoop* locEventLoop, hd locEventLoop->Get(locSCHits); vector locTOFPoints; - locEventLoop->Get(locTOFPoints); + locEventLoop->Get(locTOFPoints); + + vector locCTOFPoints; + locEventLoop->Get(locCTOFPoints); vector locBCALShowers; locEventLoop->Get(locBCALShowers); @@ -1648,7 +1703,16 @@ jerror_t DEventSourceREST::Extract_DDetectorMatches(JEventLoop* locEventLoop, hd locShowerMatchParams->dFlightTimeVariance = fcalIter->getTflightvar(); locShowerMatchParams->dPathLength = fcalIter->getPathlength(); locShowerMatchParams->dDOCAToShower = fcalIter->getDoca(); - + locShowerMatchParams->dEcenter=0.; + locShowerMatchParams->dE3x3=0.; + locShowerMatchParams->dE5x5=0.; + const hddm_r::FcalEnergyParamsList &fcalEnergyList = fcalIter->getFcalEnergyParamses(); + hddm_r::FcalEnergyParamsList::iterator fcalEnergyIter = fcalEnergyList.begin(); + for(; fcalEnergyIter != fcalEnergyList.end(); ++fcalEnergyIter){ + locShowerMatchParams->dEcenter=fcalEnergyIter->getEcenter(); + locShowerMatchParams->dE3x3=fcalEnergyIter->getE3x3(); + locShowerMatchParams->dE5x5=fcalEnergyIter->getE5x5(); + } locDetectorMatches->Add_Match(locTrackTimeBasedVector[locTrackIndex], locFCALShowers[locShowerIndex], std::const_pointer_cast(locShowerMatchParams)); } @@ -1744,6 +1808,43 @@ jerror_t DEventSourceREST::Extract_DDetectorMatches(JEventLoop* locEventLoop, hd } } + // Extract track matching data for FMPWCs + const hddm_r::FmwpcMatchParamsList &fmwpcList = iter->getFmwpcMatchParamses(); + hddm_r::FmwpcMatchParamsList::iterator fmwpcIter = fmwpcList.begin(); + for(; fmwpcIter != fmwpcList.end(); ++fmwpcIter) + { + size_t locTrackIndex = fmwpcIter->getTrack(); + const hddm_r::FmwpcDataList &fmwpcDataList = fmwpcIter->getFmwpcDatas(); + hddm_r::FmwpcDataList::iterator fmwpcDataIter = fmwpcDataList.begin(); + + auto locFMWPCMatchParams = std::make_shared(); + for(; fmwpcDataIter != fmwpcDataList.end(); ++fmwpcDataIter){ + locFMWPCMatchParams->dLayers.push_back(fmwpcDataIter->getLayer()); + locFMWPCMatchParams->dNhits.push_back(fmwpcDataIter->getNhits()); + locFMWPCMatchParams->dDists.push_back(fmwpcDataIter->getDist()); + locFMWPCMatchParams->dClosestWires.push_back(fmwpcDataIter->getClosestwire()); + } + locDetectorMatches->Add_Match(locTrackTimeBasedVector[locTrackIndex], std::const_pointer_cast(locFMWPCMatchParams)); + } + + // Extract track matching data for CTOF + const hddm_r::CtofMatchParamsList &ctofList = iter->getCtofMatchParamses(); + hddm_r::CtofMatchParamsList::iterator ctofIter = ctofList.begin(); + for(; ctofIter != ctofList.end(); ++ctofIter) + { + size_t locHitIndex = ctofIter->getHit(); + size_t locTrackIndex = ctofIter->getTrack(); + + auto locCTOFHitMatchParams = std::make_shared(); + locCTOFHitMatchParams->dCTOFPoint = locCTOFPoints[locHitIndex]; + locCTOFHitMatchParams->dEdx = ctofIter->getDEdx(); + locCTOFHitMatchParams->dFlightTime = ctofIter->getTflight(); + locCTOFHitMatchParams->dDeltaXToHit = ctofIter->getDeltax(); + locCTOFHitMatchParams->dDeltaYToHit = ctofIter->getDeltay(); + + locDetectorMatches->Add_Match(locTrackTimeBasedVector[locTrackIndex], locCTOFPoints[locHitIndex], std::const_pointer_cast(locCTOFHitMatchParams)); + } + const hddm_r::BcalDOCAtoTrackList &bcaldocaList = iter->getBcalDOCAtoTracks(); hddm_r::BcalDOCAtoTrackList::iterator bcaldocaIter = bcaldocaList.begin(); for(; bcaldocaIter != bcaldocaList.end(); ++bcaldocaIter) @@ -1885,6 +1986,49 @@ jerror_t DEventSourceREST::Extract_DDIRCPmtHit(hddm_r::HDDM *record, return NOERROR; } +//----------------------- +// Extract_DFMWPCHit +//----------------------- +jerror_t DEventSourceREST::Extract_DFMWPCHit(hddm_r::HDDM *record, + JFactory* factory, JEventLoop* locEventLoop) +{ + /// Copies the data from the fmwpc hit hddm record. This is + /// call from JEventSourceREST::GetObjects. If factory is NULL, this + /// returns OBJECT_NOT_AVAILABLE immediately. + + if (factory==NULL) { + return OBJECT_NOT_AVAILABLE; + } + string tag = (factory->Tag())? factory->Tag() : ""; + + vector data; + + // loop over fmwpc hit records + const hddm_r::FmwpcHitList &hits = + record->getFmwpcHits(); + hddm_r::FmwpcHitList::iterator iter; + for (iter = hits.begin(); iter != hits.end(); ++iter) { + if (iter->getJtag() != tag) + continue; + + DFMWPCHit *hit = new DFMWPCHit(); + hit->layer = iter->getLayer(); + hit->wire = iter->getWire(); + hit->q = iter->getQ(); + hit->amp = iter->getAmp(); + hit->t = iter->getT(); + hit->QF = iter->getQf(); + hit->ped = iter->getPed(); + + data.push_back(hit); + } + + // Copy into factory + factory->CopyTo(data); + + return NOERROR; +} + //---------------------------- // Extract_DEventHitStatistics //---------------------------- diff --git a/src/libraries/HDDM/DEventSourceREST.h b/src/libraries/HDDM/DEventSourceREST.h index 31d981cf3c..b1b698d66e 100644 --- a/src/libraries/HDDM/DEventSourceREST.h +++ b/src/libraries/HDDM/DEventSourceREST.h @@ -33,6 +33,8 @@ #include #include #include +#include +#include #include #include #include @@ -76,7 +78,9 @@ class DEventSourceREST:public JEventSource jerror_t Extract_DSCHit(hddm_r::HDDM *record, JFactory* factory); jerror_t Extract_DTOFPoint(hddm_r::HDDM *record, - JFactory* factory); + JFactory* factory); + jerror_t Extract_DCTOFPoint(hddm_r::HDDM *record, + JFactory* factory); jerror_t Extract_DFCALShower(hddm_r::HDDM *record, JFactory* factory); jerror_t Extract_DBCALShower(hddm_r::HDDM *record, @@ -95,6 +99,8 @@ class DEventSourceREST:public JEventSource #endif jerror_t Extract_DDIRCPmtHit(hddm_r::HDDM *record, JFactory* factory, JEventLoop* locEventLoop); + jerror_t Extract_DFMWPCHit(hddm_r::HDDM *record, + JFactory* factory, JEventLoop* locEventLoop); jerror_t Extract_DEventHitStatistics(hddm_r::HDDM *record, JFactory *factory); diff --git a/src/libraries/HDDM/DEventWriterHDDM.cc b/src/libraries/HDDM/DEventWriterHDDM.cc index 2f00e6923c..ff62379da7 100644 --- a/src/libraries/HDDM/DEventWriterHDDM.cc +++ b/src/libraries/HDDM/DEventWriterHDDM.cc @@ -67,6 +67,7 @@ bool DEventWriterHDDM::Write_HDDMEvent(JEventLoop* locEventLoop, string locOutpu vector CDCHits; vector TOFHits; vector FCALHits; + vector ECALHits; vector CCALHits; vector SCHits; vector BCALDigiHits; @@ -79,11 +80,14 @@ bool DEventWriterHDDM::Write_HDDMEvent(JEventLoop* locEventLoop, string locOutpu vector TPOLHits; vector RFtimes; vector DIRCPmtHits; + vector CTOFHits; + vector FMWPCHits; locEventLoop->Get(CDCHits, CDC_TAG.c_str()); locEventLoop->Get(FDCHits, FDC_TAG.c_str()); locEventLoop->Get(TOFHits); locEventLoop->Get(FCALHits); + locEventLoop->Get(ECALHits); locEventLoop->Get(CCALHits); locEventLoop->Get(BCALDigiHits); locEventLoop->Get(BCALTDCDigiHits); @@ -95,8 +99,10 @@ bool DEventWriterHDDM::Write_HDDMEvent(JEventLoop* locEventLoop, string locOutpu locEventLoop->Get(TPOLHits); locEventLoop->Get(RFtimes); locEventLoop->Get(DIRCPmtHits); + locEventLoop->Get(CTOFHits); + locEventLoop->Get(FMWPCHits); - if(CDCHits.size()== uint(0) && TOFHits.size()==uint(0) && FCALHits.size()==uint(0) && BCALDigiHits.size()==uint(0) && BCALTDCDigiHits.size()==uint(0) && SCHits.size()==uint(0) && PSHits.size()==uint(0) && PSCHits.size()==uint(0) && FDCHits.size()==uint(0) && TAGHHits.size()==uint(0) && TAGMHits.size()==uint(0) && TPOLHits.size()==uint(0) && RFtimes.size()==uint(0) && DIRCPmtHits.size()==uint(0) && CCALHits.size()==uint(0)) + if(CDCHits.size()== uint(0) && TOFHits.size()==uint(0) && FCALHits.size()==uint(0) && BCALDigiHits.size()==uint(0) && BCALTDCDigiHits.size()==uint(0) && SCHits.size()==uint(0) && PSHits.size()==uint(0) && PSCHits.size()==uint(0) && FDCHits.size()==uint(0) && TAGHHits.size()==uint(0) && TAGMHits.size()==uint(0) && TPOLHits.size()==uint(0) && RFtimes.size()==uint(0) && DIRCPmtHits.size()==uint(0) && CCALHits.size()==uint(0) && ECALHits.size()==uint(0) && CTOFHits.size()==uint(0) && FMWPCHits.size()==uint(0) ) { return false; } @@ -592,6 +598,51 @@ bool DEventWriterHDDM::Write_HDDMEvent(JEventLoop* locEventLoop, string locOutpu + //========================================ECAL========================================================= + + + for(uint i=0; iaddCrystalEcals(); + } + bool found = false; + //ECAL only has one hit per block per event so we need not search + hddm_s::EcalBlockList* ECAL_BlockList = &hitv->getCrystalEcal().getEcalBlocks(); + hddm_s::EcalBlockList::iterator ECAL_BlockIterator = ECAL_BlockList->begin(); + + for(ECAL_BlockIterator = ECAL_BlockList->begin(); ECAL_BlockIterator != ECAL_BlockList->end(); ECAL_BlockIterator++) + { + if(ECALHits[i]->row==ECAL_BlockIterator->getRow() && ECALHits[i]->column==ECAL_BlockIterator->getColumn()) + { + found=true; + break; + } + } + + if(found==false) + { + hitv->getCrystalEcal().addEcalBlocks(); + ECAL_BlockIterator=ECAL_BlockList->end()-1; + ECAL_BlockIterator->setColumn(ECALHits[i]->column); + ECAL_BlockIterator->setRow(ECALHits[i]->row); + } + + + ECAL_BlockIterator->addEcalHits(); + hddm_s::EcalHitList* ECAL_HitList = &ECAL_BlockIterator->getEcalHits(); + hddm_s::EcalHitList::iterator ECAL_HitIterator = ECAL_HitList->end()-1; + ECAL_HitIterator->setT(ECALHits[i]->t); + ECAL_HitIterator->setE(ECALHits[i]->E); + + + } + + + + + //========================================CCAL========================================================= for(uint i=0; isetT(DIRCPmtHits[i]->t); } + //=========================================CTOF======================================================= + + for(uint i=0; iaddCppTOFs(); + } + bool found = false; + hddm_s::CtofCounterList* CTOF_CounterList = &hitv->getCppTOF().getCtofCounters(); + hddm_s::CtofCounterList::iterator CTOF_CounterIterator = CTOF_CounterList->begin(); + for(CTOF_CounterIterator = CTOF_CounterList->begin(); CTOF_CounterIterator != CTOF_CounterList->end(); CTOF_CounterIterator++) + { + if(CTOFHits[i]->bar==CTOF_CounterIterator->getBar()) + { + found=true; + break; + } + } + if(found==false) + { + hitv->getCppTOF().addCtofCounters(); + CTOF_CounterIterator=CTOF_CounterList->end()-1; + CTOF_CounterIterator->setBar(CTOFHits[i]->bar); + } + CTOF_CounterIterator->addCtofHits(); + hddm_s::CtofHitList* ctofhitl=&CTOF_CounterIterator->getCtofHits(); + hddm_s::CtofHitList::iterator ctofhitit=ctofhitl->end()-1; + ctofhitit->setEnd(CTOFHits[i]->end); + ctofhitit->setT(CTOFHits[i]->t); + ctofhitit->setDE(CTOFHits[i]->dE); + } + //=============================================FMWPC================================================ + for(uint i=0;iaddForwardMWPCs(); + } + bool foundChamber=false; + hddm_s::FmwpcChamberList* FMWPC_ChamberList = &hitv->getForwardMWPC().getFmwpcChambers(); + hddm_s::FmwpcChamberList::iterator FMWPC_ChamberIterator = FMWPC_ChamberList->begin(); + for(FMWPC_ChamberIterator = FMWPC_ChamberList->begin(); FMWPC_ChamberIterator != FMWPC_ChamberList->end(); FMWPC_ChamberIterator++) + { + if(FMWPCHits[i]->layer == FMWPC_ChamberIterator->getLayer() && + FMWPCHits[i]->wire == FMWPC_ChamberIterator->getWire()) + { + foundChamber = true; + break; + } + } + if(foundChamber == false) + { + hitv->getForwardMWPC().addFmwpcChambers(); + FMWPC_ChamberIterator = FMWPC_ChamberList->end()-1; + FMWPC_ChamberIterator->setLayer(FMWPCHits[i]->layer); + FMWPC_ChamberIterator->setWire(FMWPCHits[i]->wire); + } + FMWPC_ChamberIterator->addFmwpcHits(); + hddm_s::FmwpcHitList* fmwpchitl=&FMWPC_ChamberIterator->getFmwpcHits(); + hddm_s::FmwpcHitList::iterator fmwpchitit=fmwpchitl->end()-1; + fmwpchitit->setT(FMWPCHits[i]->t); + } + + //*fout << *record; //stream the new record into the file // write the resulting record to the output stream @@ -758,6 +874,7 @@ bool DEventWriterHDDM::Write_HDDMEvent(JEventLoop* locEventLoop, string locOutpu CDCHits.clear(); TOFHits.clear(); FCALHits.clear(); + ECALHits.clear(); CCALHits.clear(); SCHits.clear(); BCALDigiHits.clear(); @@ -770,6 +887,8 @@ bool DEventWriterHDDM::Write_HDDMEvent(JEventLoop* locEventLoop, string locOutpu TPOLHits.clear(); RFtimes.clear(); DIRCPmtHits.clear(); + FMWPCHits.clear(); + CTOFHits.clear(); return locWriteStatus; } diff --git a/src/libraries/HDDM/DEventWriterHDDM.h b/src/libraries/HDDM/DEventWriterHDDM.h index 4aa98ea76f..961ec386ca 100644 --- a/src/libraries/HDDM/DEventWriterHDDM.h +++ b/src/libraries/HDDM/DEventWriterHDDM.h @@ -11,6 +11,7 @@ #include #include #include +#include #include #include #include @@ -23,6 +24,9 @@ #include #include #include +#include +#include + using namespace std; using namespace jana; diff --git a/src/libraries/HDDM/DEventWriterREST.cc b/src/libraries/HDDM/DEventWriterREST.cc index 069a40dd03..9ca81e1fa0 100644 --- a/src/libraries/HDDM/DEventWriterREST.cc +++ b/src/libraries/HDDM/DEventWriterREST.cc @@ -48,9 +48,16 @@ DEventWriterREST::DEventWriterREST(JEventLoop* locEventLoop, string locOutputFil REST_WRITE_DIRC_HITS = true; gPARMS->SetDefaultParameter("REST:WRITE_DIRC_HITS", REST_WRITE_DIRC_HITS); + REST_WRITE_FMWPC_HITS = true; + gPARMS->SetDefaultParameter("REST:WRITE_FMWPC_HITS", REST_WRITE_FMWPC_HITS); + REST_WRITE_CCAL_SHOWERS = true; gPARMS->SetDefaultParameter("REST:WRITE_CCAL_SHOWERS", REST_WRITE_CCAL_SHOWERS); + ADD_FCAL_DATA_FOR_CPP=false; + gPARMS->SetDefaultParameter("PID:ADD_FCAL_DATA_FOR_CPP",ADD_FCAL_DATA_FOR_CPP); + + CCDB_CONTEXT_STRING = ""; // if we can get the calibration context from the DANA interface, then save this as well DApplication *dapp = dynamic_cast(locEventLoop->GetJApplication()); @@ -92,6 +99,9 @@ bool DEventWriterREST::Write_RESTEvent(JEventLoop* locEventLoop, string locOutpu std::vector tofpoints; locEventLoop->Get(tofpoints); + std::vector ctofpoints; + locEventLoop->Get(ctofpoints); + std::vector starthits; locEventLoop->Get(starthits); @@ -104,6 +114,11 @@ bool DEventWriterREST::Write_RESTEvent(JEventLoop* locEventLoop, string locOutpu std::vector locDIRCPmtHits; locEventLoop->Get(locDIRCPmtHits); + std::vector fmwpchits; + if(REST_WRITE_FMWPC_HITS) { + locEventLoop->Get(fmwpchits); + } + std::vector hitStats; locEventLoop->Get(hitStats); @@ -343,7 +358,19 @@ bool DEventWriterREST::Write_RESTEvent(JEventLoop* locEventLoop, string locOutpu ccal().setDime(ccalshowers[i]->dime); ccal().setId(ccalshowers[i]->id); ccal().setIdmax(ccalshowers[i]->idmax); - } + } + + // push any DCTOFPoint objects to the output record + for (size_t i=0; i < ctofpoints.size(); i++) + { + hddm_r::CtofPointList ctof = res().addCtofPoints(1); + ctof().setBar(ctofpoints[i]->bar); + ctof().setX(ctofpoints[i]->pos(0)); + ctof().setY(ctofpoints[i]->pos(1)); + ctof().setZ(ctofpoints[i]->pos(2)); + ctof().setT(ctofpoints[i]->t); + ctof().setDE(ctofpoints[i]->dE); + } // push any DTOFPoint objects to the output record for (size_t i=0; i < tofpoints.size(); i++) @@ -386,6 +413,21 @@ bool DEventWriterREST::Write_RESTEvent(JEventLoop* locEventLoop, string locOutpu } } + if(REST_WRITE_FMWPC_HITS) { + // push any DFMWPCHit objects to the output record + for (size_t i=0; i < fmwpchits.size(); i++) + { + hddm_r::FmwpcHitList hit = res().addFmwpcHits(1); + hit().setLayer(fmwpchits[i]->layer); + hit().setWire(fmwpchits[i]->wire); + hit().setQ(fmwpchits[i]->q); + hit().setAmp(fmwpchits[i]->amp); + hit().setT(fmwpchits[i]->t); + hit().setQf(fmwpchits[i]->QF); + hit().setPed(fmwpchits[i]->ped); + } + } + // push any DTrackTimeBased objects to the output record for (size_t i=0; i < tracks.size(); ++i) { @@ -589,6 +631,19 @@ bool DEventWriterREST::Write_RESTEvent(JEventLoop* locEventLoop, string locOutpu fcalList().setPathlength(locFCALShowerMatchParamsVector[loc_k]->dPathLength); fcalList().setTflight(locFCALShowerMatchParamsVector[loc_k]->dFlightTime); fcalList().setTflightvar(locFCALShowerMatchParamsVector[loc_k]->dFlightTimeVariance); + // Additional energy information + if (ADD_FCAL_DATA_FOR_CPP){ + // Sanity check for this additional info + double myE5x5=locFCALShowerMatchParamsVector[loc_k]->dE5x5; + double myE3x3=locFCALShowerMatchParamsVector[loc_k]->dE3x3; + double myEcenter=locFCALShowerMatchParamsVector[loc_k]->dEcenter; + if (myEcenter>0. || myE3x3>0. || myE5x5>0.){ + hddm_r::FcalEnergyParamsList fcalEnergyParamsList = fcalList().addFcalEnergyParamses(1); + fcalEnergyParamsList().setEcenter(myEcenter); + fcalEnergyParamsList().setE3x3(myE3x3); + fcalEnergyParamsList().setE5x5(myE5x5); + } + } } vector> locFCALSingleHitMatchParamsVector; @@ -736,6 +791,46 @@ bool DEventWriterREST::Write_RESTEvent(JEventLoop* locEventLoop, string locOutpu correlationList().setSystem(SYS_START); correlationList().setCorrelation(locFlightTimePCorrelation); } + + //--------- The following are for CPP -------------// + vector> locFMWPCMatchParamsVector; + locDetectorMatches[loc_i]->Get_FMWPCMatchParams(tracks[loc_j], locFMWPCMatchParamsVector); + for(size_t loc_k = 0; loc_k < locFMWPCMatchParamsVector.size(); ++loc_k){ + hddm_r::FmwpcMatchParamsList fmwpcList = matches().addFmwpcMatchParamses(1); + fmwpcList().setTrack(loc_j); + vectorlocLayers=locFMWPCMatchParamsVector[loc_k]->dLayers; + vectorlocNhits=locFMWPCMatchParamsVector[loc_k]->dNhits; + vectorlocDists=locFMWPCMatchParamsVector[loc_k]->dDists; + vectorlocClosestWires=locFMWPCMatchParamsVector[loc_k]->dClosestWires; + for (size_t loc_m=0;loc_m> locCTOFHitMatchParamsVector; + locDetectorMatches[loc_i]->Get_CTOFMatchParams(tracks[loc_j], locCTOFHitMatchParamsVector); + for(size_t loc_k = 0; loc_k < locCTOFHitMatchParamsVector.size(); ++loc_k) + { + hddm_r::CtofMatchParamsList ctofList = matches().addCtofMatchParamses(1); + ctofList().setTrack(loc_j); + + size_t locCTOFindex = 0; + for(; locCTOFindex < ctofpoints.size(); ++locCTOFindex) + { + if(ctofpoints[locCTOFindex] == locCTOFHitMatchParamsVector[loc_k]->dCTOFPoint) + break; + } + ctofList().setHit(locCTOFindex); + ctofList().setDEdx(locCTOFHitMatchParamsVector[loc_k]->dEdx); + ctofList().setTflight(locCTOFHitMatchParamsVector[loc_k]->dFlightTime); + + ctofList().setDeltax(locCTOFHitMatchParamsVector[loc_k]->dDeltaXToHit); + ctofList().setDeltay(locCTOFHitMatchParamsVector[loc_k]->dDeltaYToHit); + } } for(size_t loc_j = 0; loc_j < bcalshowers.size(); ++loc_j) diff --git a/src/libraries/HDDM/DEventWriterREST.h b/src/libraries/HDDM/DEventWriterREST.h index 3af022d591..f70fc32392 100644 --- a/src/libraries/HDDM/DEventWriterREST.h +++ b/src/libraries/HDDM/DEventWriterREST.h @@ -27,6 +27,7 @@ #include "TRACKING/DTrackTimeBased.h" #include "TRIGGER/DTrigger.h" #include "DIRC/DDIRCPmtHit.h" +#include "FMWPC/DFMWPCHit.h" #include "HDDM/DEventHitStatistics.h" #include "RF/DRFTime.h" @@ -57,8 +58,10 @@ class DEventWriterREST : public JObject bool HDDM_USE_COMPRESSION; bool HDDM_USE_INTEGRITY_CHECKS; bool REST_WRITE_DIRC_HITS; + bool REST_WRITE_FMWPC_HITS; bool REST_WRITE_CCAL_SHOWERS; bool REST_WRITE_TRACK_EXIT_PARAMS; + bool ADD_FCAL_DATA_FOR_CPP; // metadata to save in the REST file // these should be consistent during program execution diff --git a/src/libraries/HDDM/SConscript b/src/libraries/HDDM/SConscript index 39b696bc20..b4ce2c029d 100644 --- a/src/libraries/HDDM/SConscript +++ b/src/libraries/HDDM/SConscript @@ -6,34 +6,17 @@ # # utilities used for generating files like hddm_s.c and hddm_s.h # from the input event.xml have their source in: -# src/programs/Utilities/hddm +# https://github.com/jeffersonlab/HDDM # # The HDDM library is made up of code maintained in the # src/libraries/HDDM directory as well as code generated # from XML files in that same directory using the above # utilities. # -# What this means is that we need to tell scons that a file like "hddm_s.c" -# depends on the utility "hddm-c" being made first. Because those live -# in very separate directories we have to somehow get the Node objects for -# both the utility and the source in one place so we can explicitly -# declare this dependency using the scons "Requires()" routine. The way -# this is done is by adding the list of dependent nodes to a special -# variable in the top-level build environment. (In this case two lists -# because the C and C++ interfaces must be handled independently.) -# These variables, "HDDMC_SRC" and "HDDMCPP_SRC" are lists of nodes that -# can be used in the src/programs/Utilities/hddm/SConscript file to -# declare this dependency. It is done there since the top-level SConstruct -# file sources this file (the one you're reading) first (via the -# libraries/SConscript file) and the one there second (via the -# programs/SConscript file). Thus, it is the only place where both the -# source Nodes and utility Nodes are both available. -# # To actually generate the C/C++ source from the XML we create two builders # (one for C and the other for C++) here. The builders run the utilities -# hddm-c and hddm-cpp from the variant dir tree. This path, relative to -# the top-level directory (the one containing SConstruct) is hardwired -# here (e.g. "#.%s/programs/Utilities/hddm/hddm-c"). To further complicate +# hddm-c and hddm-cpp from the external HDDM package, which are assumed +# to be found somewhere in the current PATH. To further complicate # matters, the output of hddm-c is two files (e.g. hddm_s.c and hddm_s.h) # which do not depend on the name of the input file ("event.xml"). We specify # two products of the input XML, but the value that $TARGET gets set to @@ -67,9 +50,6 @@ env.Decider('MD5-timestamp') #--------------- def HDDM_C(target, source, env): - # Get full path to tool - hddmc = str(env.File("#.%s/programs/Utilities/hddm/hddm-c" % osname)) - # Get basename with full path for target. # The first target should always be the header # file name to be generated so we just drop the @@ -77,7 +57,7 @@ def HDDM_C(target, source, env): target_base = re.sub('\.h$', '', str(target[0])) # Form command to be executed and execute it - cmd = [hddmc, '-o', target_base, str(source[0])] + cmd = ["hddm-c", '-o', target_base, str(source[0])] if( int(env['SHOWBUILD']) > 0): print(' '.join(cmd)) cmdout = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate() @@ -86,9 +66,6 @@ def HDDM_C(target, source, env): #--------------- def HDDM_CPP(target, source, env): - # Get full path to tool - hddmcpp = str(env.File("#.%s/programs/Utilities/hddm/hddm-cpp" % osname)) - # Get basename with full path for target. # The first target should always be the header # file name to be generated so we just drop the @@ -96,13 +73,7 @@ def HDDM_CPP(target, source, env): target_base = re.sub('\.hpp$', '', str(target[0])) # Form command to be executed and execute it - cmd = [hddmcpp, '-o', target_base, str(source[0])] - if( int(env['SHOWBUILD']) > 0): print(' '.join(cmd)) - cmdout = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate() - - # C++ interface must have source file names modified - # so as not to generate same .o filenames as their C counteparts - cmd = ['mv', '%s.cpp' % target_base, '%s++.cpp' % target_base] + cmd = ["hddm-cpp", '-o', target_base, str(source[0])] if( int(env['SHOWBUILD']) > 0): print(' '.join(cmd)) cmdout = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate() @@ -111,14 +82,11 @@ def HDDM_CPP(target, source, env): #--------------- def HDDM_PY(target, source, env): - # Get full path to tool - hddmpy = str(env.File("#.%s/programs/Utilities/hddm/hddm-py" % osname)) - # separate the target directory and basename target_base = re.sub('\.cpy$', '', str(target[1])) # Form command to be executed and execute it - cmd = [hddmpy, '-o', target_base, str(source[0])] + cmd = ["hddm-py", '-o', target_base, str(source[0])] if( int(env['SHOWBUILD']) > 0): print(' '.join(cmd)) cmdout = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate() @@ -145,25 +113,19 @@ env.Append(BUILDERS = {'HDDMC' : bldc}) env.Append(BUILDERS = {'HDDMCPP' : bldcpp}) env.Append(BUILDERS = {'HDDMPY' : bldpy}) - # Add the C/C++ HDDM (de)serializer source dependencies # by hand. The output file names depend on the class # tag defined inside the XML file. So, specifying the # inputs and outputs explicitly here is just easier. -# The HDDMC_SRC and HDDMCPP_SRC variables are used by -# the SConscript in src/programs/Utilities/hddm. -hddmc = str(env.File("#.%s/programs/Utilities/hddm/hddm-c" % osname)) -hddmcpp = str(env.File("#.%s/programs/Utilities/hddm/hddm-cpp" % osname)) -hddmpy = str(env.File("#.%s/programs/Utilities/hddm/hddm-py" % osname)) -env.AppendUnique(HDDMC_SRC = env.HDDMC(['hddm_s.h', 'hddm_s.c'], ['event.xml', hddmc])) -env.AppendUnique(HDDMC_SRC = env.HDDMC(['hddm_mc_s.h', 'hddm_mc_s.c'], ['mc.xml',hddmc])) -env.AppendUnique(HDDMC_SRC = env.HDDMC(['hddm_r.h', 'hddm_r.c'], ['rest.xml', hddmc])) -env.AppendUnique(HDDMCPP_SRC = env.HDDMCPP(['hddm_s.hpp', 'hddm_s++.cpp'], ['event.xml', hddmcpp])) -env.AppendUnique(HDDMCPP_SRC = env.HDDMCPP(['hddm_mc_s.hpp', 'hddm_mc_s++.cpp'], ['mc.xml', hddmcpp])) -env.AppendUnique(HDDMCPP_SRC = env.HDDMCPP(['hddm_r.hpp', 'hddm_r++.cpp'], ['rest.xml', hddmcpp])) -env.AppendUnique(HDDMPY_SRC = env.HDDMPY(['setup_hddm_s.py', 'pyhddm_s.cpy'], ['event.xml', hddmpy])) -env.AppendUnique(HDDMPY_SRC = env.HDDMPY(['setup_hddm_mc_s.py', 'pyhddm_mc_s.cpy'], ['mc.xml', hddmpy])) -env.AppendUnique(HDDMPY_SRC = env.HDDMPY(['setup_hddm_r.py', 'pyhddm_r.cpy'], ['rest.xml', hddmpy])) +env.AppendUnique(HDDMC_SRC = env.HDDMC(['hddm_s.h', 'hddm_s.c'], ['event.xml'])) +env.AppendUnique(HDDMC_SRC = env.HDDMC(['hddm_mc_s.h', 'hddm_mc_s.c'], ['mc.xml'])) +env.AppendUnique(HDDMC_SRC = env.HDDMC(['hddm_r.h', 'hddm_r.c'], ['rest.xml'])) +env.AppendUnique(HDDMCPP_SRC = env.HDDMCPP(['hddm_s.hpp', 'hddm_s++.cpp'], ['event.xml'])) +env.AppendUnique(HDDMCPP_SRC = env.HDDMCPP(['hddm_mc_s.hpp', 'hddm_mc_s++.cpp'], ['mc.xml'])) +env.AppendUnique(HDDMCPP_SRC = env.HDDMCPP(['hddm_r.hpp', 'hddm_r++.cpp'], ['rest.xml'])) +env.AppendUnique(HDDMPY_SRC = env.HDDMPY(['setup_hddm_s.py', 'pyhddm_s.cpy'], ['event.xml'])) +env.AppendUnique(HDDMPY_SRC = env.HDDMPY(['setup_hddm_mc_s.py', 'pyhddm_mc_s.cpy'], ['mc.xml'])) +env.AppendUnique(HDDMPY_SRC = env.HDDMPY(['setup_hddm_r.py', 'pyhddm_r.cpy'], ['rest.xml'])) # Additional dependencies in the generated module source files env.Depends(['setup_hddm_s.py', 'pyhddm_s.cpy'], ['hddm_s.hpp', 'hddm_s++.cpp']) diff --git a/src/libraries/HDDM/event.xml b/src/libraries/HDDM/event.xml index 2303a3dfd5..685882cb79 100644 --- a/src/libraries/HDDM/event.xml +++ b/src/libraries/HDDM/event.xml @@ -151,6 +151,15 @@ + + + + + + + + + @@ -160,6 +169,8 @@ + + diff --git a/src/libraries/HDDM/rest.xml b/src/libraries/HDDM/rest.xml index 57c2530c3b..9eb49daa43 100644 --- a/src/libraries/HDDM/rest.xml +++ b/src/libraries/HDDM/rest.xml @@ -88,6 +88,10 @@ + + @@ -101,6 +105,8 @@ + + tunit="ns" lunit="cm"> + + + + + + CrystalEcalpos; + jgeom->SetVerbose(0); // don't print error messages for optional detector elements + bool good = Get("//section/composition/posXYZ[@volume='CrystalECAL']/@X_Y_Z", CrystalEcalpos); + jgeom->SetVerbose(1); // reenable error messages + + if(!good){ + // NEED TO RETHINK ERROR REPORTING FOR OPTIONAL DETECTOR ELEMENTS + //_DBG_<<"Unable to retrieve ECAL position."< ComptonEMcalpos; jgeom->SetVerbose(0); // don't print error messages for optional detector elements - bool good = Get("//section/composition/posXYZ[@volume='ComptonEMcal']/@X_Y_Z", ComptonEMcalpos);\ + bool good = Get("//section/composition/posXYZ[@volume='ComptonEMcal']/@X_Y_Z", ComptonEMcalpos); jgeom->SetVerbose(1); // reenable error messages if(!good){ @@ -1791,9 +1814,11 @@ bool DGeometry::GetCCALZ(double &z_ccal) const bool DGeometry::GetCTOFZ(double &z) const { z=1000; // cm; initialize to a large value vector CppScintPos; + jgeom->SetVerbose(0); // don't print error messages for optional detector elements bool good = Get("//section/composition/posXYZ[@volume='CppScint']/@X_Y_Z", CppScintPos); + jgeom->SetVerbose(1); // reenable error messages if (!good){ - _DBG_<<"Unable to retrieve CPP scintillator position."<&posvec) const{ vectororigin; + jgeom->SetVerbose(0); // don't print error messages for optional detector elements bool good = Get("//section/composition/posXYZ[@volume='CppScint']/@X_Y_Z",origin); + jgeom->SetVerbose(1); // reenable error messages if (!good) return false; DVector3 pos(origin[0],origin[1],origin[2]); for (unsigned int paddle=1;paddle<5;paddle++){ @@ -1824,7 +1851,9 @@ bool DGeometry::GetCTOFPositions(vector&posvec) const{ bool DGeometry::GetFMWPCZ_vec(vector&zvec_fmwpc) const { vector ForwardMWPCpos; + jgeom->SetVerbose(0); // don't print error messages for optional detector elements bool good = Get("//section/composition/posXYZ[@volume='ForwardMWPC']/@X_Y_Z", ForwardMWPCpos); + jgeom->SetVerbose(1); // reenable error messages if (!good){ //_DBG_<<"Unable to retrieve ForwardMWPC position."<&zvec_fmwpc) const bool DGeometry::GetFMWPCXY_vec(vector&xvec_fmwpc, vector&yvec_fmwpc) const { vector ForwardMWPCpos; + jgeom->SetVerbose(0); // don't print error messages for optional detector elements bool good = Get("//section/composition/posXYZ[@volume='ForwardMWPC']/@X_Y_Z", ForwardMWPCpos); + jgeom->SetVerbose(1); // reenable error messages if (!good){ //_DBG_<<"Unable to retrieve ForwardMWPC position."<&xvec_fmwpc, vector&yvec_fm bool DGeometry::GetFMWPCSize(double &xy_fmwpc) const { vector ForwardMWPCdimensions; + jgeom->SetVerbose(0); // don't print error messages for optional detector elements bool good = Get("//section[@name='ForwardMWPC']/box[@name='CPPF']/@X_Y_Z", ForwardMWPCdimensions); + jgeom->SetVerbose(1); // reenable error messages if (!good){ xy_fmwpc=0.0; return false; @@ -1980,6 +2013,29 @@ bool DGeometry::GetFCALPosition(double &x,double &y,double &z) const } } +//--------------------------------- +// GetECALPosition +//--------------------------------- +bool DGeometry::GetECALPosition(double &x,double &y,double &z) const +{ + vector CrystalEcalpos; + jgeom->SetVerbose(0); // don't print error messages for optional detector elements + bool good = Get("//section/composition/posXYZ[@volume='CrystalECAL']/@X_Y_Z", CrystalEcalpos); + jgeom->SetVerbose(1); // reenable error messages + + if(!good){ + //_DBG_<<"Unable to retrieve ECAL position."< &z_trd) const return true; } +//--------------------------------- +// GetTOFZ +//--------------------------------- +bool DGeometry::GetTOFZ(double &CenterVPlane,double &CenterHPlane, + double &CenterMPlane) const{ + // Store the z position for both planes + vectortof_face; + if (!Get("//section/composition/posXYZ[@volume='ForwardTOF']/@X_Y_Z",tof_face)){ + return false; + } + vectortof_plane0; + Get("//composition[@name='ForwardTOF']/posXYZ[@volume='forwardTOF']/@X_Y_Z/plane[@value='0']", tof_plane0); + vectortof_plane1; + Get("//composition[@name='ForwardTOF']/posXYZ[@volume='forwardTOF']/@X_Y_Z/plane[@value='1']", tof_plane1); + CenterVPlane=tof_face[2]+tof_plane1[2]; + CenterHPlane=tof_face[2]+tof_plane0[2]; + // also save position midway between the two planes + CenterMPlane=0.5*(CenterHPlane+CenterVPlane); + + return true; +} //--------------------------------- // GetTOFZ @@ -2593,7 +2670,7 @@ bool DGeometry::GetStartCounterGeom(vector >&pos, dirvec.push_back(dir); posvec.push_back(DVector3(oldray.X()+dx,oldray.Y()+dy,oldray.Z()+z0)); } - posvec.push_back(DVector3(ray.X(),ray.Y(),ray.Z()+z0)); //SAVE THE ENDPOINT OF THE LAST PLANE + posvec.push_back(DVector3(ray.X()+dx,ray.Y()+dy,ray.Z()+z0)); //SAVE THE ENDPOINT OF THE LAST PLANE pos.push_back(posvec); norm.push_back(dirvec); diff --git a/src/libraries/HDGEOMETRY/DGeometry.h b/src/libraries/HDGEOMETRY/DGeometry.h index b4cf2c0518..73d07260d6 100644 --- a/src/libraries/HDGEOMETRY/DGeometry.h +++ b/src/libraries/HDGEOMETRY/DGeometry.h @@ -163,6 +163,8 @@ class DGeometry{ bool GetBCALDepth(float &bcal_depth) const; ///< depth (or height) of BCAL module in cm bool GetBCALPhiShift(float &bcal_phi_shift) const; ///< phi angle in degrees that first BCAL module is shifted from being centered at ph=0.0 + bool GetECALZ(double &z_ecal) const; /// z-location of front face of CCAL in cm + bool GetCCALZ(double &z_ccal) const; /// z-location of front face of CCAL in cm bool GetFCALZ(double &z_fcal) const; ///< z-location of front face of FCAL in cm @@ -176,6 +178,7 @@ class DGeometry{ bool GetDIRCZ(double &z_dirc) const; ///< z-location of DIRC in cm bool GetTOFZ(vector &z_tof) const; ///< z-location of front face of each of TOF in cm + bool GetTOFZ(double &CenterVPlane,double &CenterHPlane,double &CenterMPlane) const; ///< method used by DTOFPoint code, returning z-locations of centers of paddles bool GetTOFPaddlePerpPositions(vector &y_tof, vector &y_widths) const; bool GetTOFPaddleParameters(map &paddle_params) const; bool GetTargetZ(double &z_target) const; ///< z-location of center of target @@ -184,6 +187,7 @@ class DGeometry{ bool GetTRDZ(vector &z_trd) const; ///< z-locations for each of the TRD/GEM planes in cm bool GetFCALPosition(double &x,double &y,double &z) const; + bool GetECALPosition(double &x,double &y,double &z) const; bool GetCCALPosition(double &x,double &y,double &z) const; bool GetFCALInsertRowSize(int &insert_row_size) const; diff --git a/src/libraries/Makefile b/src/libraries/Makefile index bcad238d88..e7efa4620e 100644 --- a/src/libraries/Makefile +++ b/src/libraries/Makefile @@ -1,4 +1,4 @@ -DIRS += include HDDM BCAL CDC DANA FCAL CCAL PID KINFITTER ANALYSIS FDC START_COUNTER CERE DIRC +DIRS += include HDDM BCAL CDC DANA FCAL ECAL CCAL PID KINFITTER ANALYSIS FDC START_COUNTER CERE DIRC DIRS += HDGEOMETRY TAGGER TOF TRACKING TRIGGER TAC ifdef AMPTOOLS diff --git a/src/libraries/PID/DChargedTrackHypothesis.h b/src/libraries/PID/DChargedTrackHypothesis.h index 24f485b475..74e33c72a3 100644 --- a/src/libraries/PID/DChargedTrackHypothesis.h +++ b/src/libraries/PID/DChargedTrackHypothesis.h @@ -68,8 +68,8 @@ class DChargedTrackHypothesis : public DKinematicData shared_ptr Get_FCALShowerMatchParams(void) const{return dTrackingInfo->dFCALShowerMatchParams;} shared_ptr Get_FCALSingleHitMatchParams(void) const{return dTrackingInfo->dFCALSingleHitMatchParams;} shared_ptr Get_DIRCMatchParams(void) const{return dTrackingInfo->dDIRCMatchParams;} - - + shared_ptr Get_CTOFHitMatchParams(void) const{return dTrackingInfo->dCTOFHitMatchParams;} + shared_ptr Get_FMWPCMatchParams(void) const{return dTrackingInfo->dFMWPCMatchParams;} //SETTERS @@ -92,7 +92,9 @@ class DChargedTrackHypothesis : public DKinematicData void Set_BCALShowerMatchParams(shared_ptr locMatchParams){dTrackingInfo->dBCALShowerMatchParams = locMatchParams;} void Set_FCALShowerMatchParams(shared_ptr locMatchParams){dTrackingInfo->dFCALShowerMatchParams = locMatchParams;} void Set_FCALSingleHitMatchParams(shared_ptr locMatchParams){dTrackingInfo->dFCALSingleHitMatchParams = locMatchParams;} - void Set_DIRCMatchParams(shared_ptr locMatchParams){dTrackingInfo->dDIRCMatchParams = locMatchParams;} + void Set_DIRCMatchParams(shared_ptr locMatchParams){dTrackingInfo->dDIRCMatchParams = locMatchParams;} + void Set_CTOFHitMatchParams(shared_ptr locMatchParams){dTrackingInfo->dCTOFHitMatchParams = locMatchParams;} + void Set_FMWPCMatchParams(shared_ptr locMatchParams){dTrackingInfo->dFMWPCMatchParams = locMatchParams;} void toStrings(vector > &items) const { @@ -169,7 +171,9 @@ class DChargedTrackHypothesis : public DKinematicData shared_ptr dBCALShowerMatchParams = nullptr; shared_ptr dFCALShowerMatchParams = nullptr; shared_ptr dFCALSingleHitMatchParams = nullptr; - shared_ptr dDIRCMatchParams = nullptr; + shared_ptr dDIRCMatchParams = nullptr; + shared_ptr dCTOFHitMatchParams = nullptr; + shared_ptr dFMWPCMatchParams=nullptr; }; private: @@ -404,10 +408,12 @@ inline void DChargedTrackHypothesis::DTrackingInfo::Reset(void) dTrackTimeBased = nullptr; dSCHitMatchParams = nullptr; dTOFHitMatchParams = nullptr; + dCTOFHitMatchParams = nullptr; dBCALShowerMatchParams = nullptr; dFCALShowerMatchParams = nullptr; dFCALSingleHitMatchParams = nullptr; dDIRCMatchParams = nullptr; + dFMWPCMatchParams = nullptr; } inline void DChargedTrackHypothesis::DEOverPInfo::Reset(void) diff --git a/src/libraries/PID/DChargedTrackHypothesis_factory.cc b/src/libraries/PID/DChargedTrackHypothesis_factory.cc index 8384a1091e..de1f163fbf 100644 --- a/src/libraries/PID/DChargedTrackHypothesis_factory.cc +++ b/src/libraries/PID/DChargedTrackHypothesis_factory.cc @@ -269,7 +269,8 @@ DChargedTrackHypothesis* DChargedTrackHypothesis_factory::Create_ChargedTrackHyp shared_ptr locTOFHitMatchParams; shared_ptr locFCALShowerMatchParams; shared_ptr locFCALSingleHitMatchParams; - shared_ptr locDIRCMatchParams; + shared_ptr locDIRCMatchParams; + shared_ptr locCTOFHitMatchParams; if(dPIDAlgorithm->Get_BestBCALMatchParams(locTrackTimeBased, locDetectorMatches, locBCALShowerMatchParams)) locChargedTrackHypothesis->Set_BCALShowerMatchParams(locBCALShowerMatchParams); if(dPIDAlgorithm->Get_BestTOFMatchParams(locTrackTimeBased, locDetectorMatches, locTOFHitMatchParams)) @@ -280,6 +281,14 @@ DChargedTrackHypothesis* DChargedTrackHypothesis_factory::Create_ChargedTrackHyp locChargedTrackHypothesis->Set_FCALSingleHitMatchParams(locFCALSingleHitMatchParams); if(dPIDAlgorithm->Get_DIRCMatchParams(locTrackTimeBased, locDetectorMatches, locDIRCMatchParams)) locChargedTrackHypothesis->Set_DIRCMatchParams(locDIRCMatchParams); + if(dPIDAlgorithm->Get_BestCTOFMatchParams(locTrackTimeBased, locDetectorMatches, locCTOFHitMatchParams)) + locChargedTrackHypothesis->Set_CTOFHitMatchParams(locCTOFHitMatchParams); + // Matching to CPP wire chambers + vector > locFMWPCMatchParamsVec; + if (locDetectorMatches->Get_FMWPCMatchParams(locTrackTimeBased, + locFMWPCMatchParamsVec)){ + locChargedTrackHypothesis->Set_FMWPCMatchParams(locFMWPCMatchParamsVec[0]); + } //PID if(locChargedTrackHypothesis->t1_detector() == SYS_BCAL) diff --git a/src/libraries/PID/DDetectorMatches.h b/src/libraries/PID/DDetectorMatches.h index 0b5358fe4c..d957b6dd68 100644 --- a/src/libraries/PID/DDetectorMatches.h +++ b/src/libraries/PID/DDetectorMatches.h @@ -15,6 +15,8 @@ #include #include +#include +#include #include #include #include @@ -63,7 +65,7 @@ class DFCALShowerMatchParams { public: DFCALShowerMatchParams(void) : dFCALShower(NULL), - dx(0.0), dFlightTime(0.0), dFlightTimeVariance(0.0), dPathLength(0.0), dDOCAToShower(0.0){} + dx(0.0), dFlightTime(0.0), dFlightTimeVariance(0.0), dPathLength(0.0), dDOCAToShower(0.0), dE5x5(0.0), dE3x3(0.0), dEcenter(0.0){} const DFCALShower* dFCALShower; @@ -72,8 +74,31 @@ class DFCALShowerMatchParams double dFlightTimeVariance; double dPathLength; //path length from DKinematicData::position() to the shower double dDOCAToShower; //DOCA of track to shower + double dE5x5; // energy sum over 5x5 array centered on track projection + double dE3x3; // energy sum over 3x3 array centered on track projection + double dEcenter; // energy in "center" block }; +class DCTOFHitMatchParams +{ + public: + DCTOFHitMatchParams(void) : dCTOFPoint(NULL),dEdx(0.0),dFlightTime(0.0), + dDeltaXToHit(0.0), dDeltaYToHit(0.0){} + + const DCTOFPoint* dCTOFPoint; + + double dEdx; //dE: the energy lost by the track, dx: the distance the track traveled through the detector + double dFlightTime; //flight time from DKinematicData::position() to the hit + double dDeltaXToHit; //between track and hit + double dDeltaYToHit; //between track and hit + + double Get_DistanceToTrack(void) const + { + return sqrt(dDeltaXToHit*dDeltaXToHit + dDeltaYToHit*dDeltaYToHit); + } +}; + + class DTOFHitMatchParams { public: @@ -134,6 +159,15 @@ class DDIRCMatchParams double dExtrapolatedTime; }; +class DFMWPCMatchParams +{ + public: + vectordLayers; + vectordNhits; + vectordDists; + vectordClosestWires; +}; + class DDetectorMatches : public JObject { public: @@ -144,9 +178,11 @@ class DDetectorMatches : public JObject inline bool Get_FCALSingleHitMatchParams(const DTrackingData* locTrack, vector >& locMatchParams) const; inline bool Get_FCALMatchParams(const DTrackingData* locTrack, vector >& locMatchParams) const; inline bool Get_TOFMatchParams(const DTrackingData* locTrack, vector >& locMatchParams) const; + inline bool Get_CTOFMatchParams(const DTrackingData* locTrack, vector >& locMatchParams) const; + inline bool Get_FMWPCMatchParams(const DTrackingData* locTrack, vector >& locMatchParams) const; inline bool Get_SCMatchParams(const DTrackingData* locTrack, vector >& locMatchParams) const; inline bool Get_DIRCMatchParams(const DTrackingData* locTrack, shared_ptr& locMatchParams) const; - + inline bool Get_IsMatchedToTrack(const DBCALShower* locBCALShower) const; inline bool Get_IsMatchedToTrack(const DFCALShower* locFCALShower) const; inline bool Get_IsMatchedToHit(const DTrackingData* locTrack) const; @@ -157,6 +193,7 @@ class DDetectorMatches : public JObject inline bool Get_TrackMatchParams(const DTOFPoint* locTOFPoint, vector >& locMatchParams) const; inline bool Get_TrackMatchParams(const DSCHit* locSCHit, vector >& locMatchParams) const; inline bool Get_DIRCTrackMatchParamsMap(map, vector >& locDIRCTrackMatchParamsMap); + inline bool Get_TrackMatchParams(const DCTOFPoint* locCTOFPoint, vector >& locMatchParams) const; inline bool Get_DistanceToNearestTrack(const DBCALShower* locBCALShower, double& locDistance) const; inline bool Get_DistanceToNearestTrack(const DBCALShower* locBCALShower, double& locDeltaPhi, double& locDeltaZ) const; @@ -170,14 +207,21 @@ class DDetectorMatches : public JObject inline size_t Get_NumTrackTOFMatches(void) const; inline size_t Get_NumTrackSCMatches(void) const; inline size_t Get_NumTrackDIRCMatches(void) const; + inline size_t Get_NumTrackCTOFMatches(void) const; + inline size_t Get_NumTrackFMWPCMatches(void) const; + //SETTERS: inline void Add_Match(const DTrackingData* locTrack, const DBCALShower* locBCALShower, const shared_ptr& locShowerMatchParams); inline void Add_Match(const DTrackingData* locTrack, const shared_ptr& locFCALSingleHitMatchParams); inline void Add_Match(const DTrackingData* locTrack, const DFCALShower* locFCALShower, const shared_ptr& locShowerMatchParams); inline void Add_Match(const DTrackingData* locTrack, const DTOFPoint* locTOFPoint, const shared_ptr& locHitMatchParams); + inline void Add_Match(const DTrackingData* locTrack, const DCTOFPoint* locCTOFPoint, const shared_ptr& locHitMatchParams); inline void Add_Match(const DTrackingData* locTrack, const DSCHit* locSCHit, const shared_ptr& locHitMatchParams); inline void Add_Match(const DTrackingData* locTrack, const shared_ptr& locDIRCMatchParams); + inline void Add_Match(const DTrackingData *locTrack, + const shared_ptr& locFMWPCMatchParams); + inline void Set_DistanceToNearestTrack(const DBCALShower* locBCALShower, double locDeltaPhi, double locDeltaZ); inline void Set_DistanceToNearestTrack(const DFCALShower* locFCALShower, double locDistanceToNearestTrack); inline void Set_FlightTimePCorrelation(const DTrackingData* locTrack, DetectorSystem_t locDetectorSystem, double locCorrelation); @@ -188,7 +232,9 @@ class DDetectorMatches : public JObject AddString(items, "#_Track_FCAL_Matches", "%d", Get_NumTrackFCALMatches()); AddString(items, "#_Track_TOF_Matches", "%d", Get_NumTrackTOFMatches()); AddString(items, "#_Track_SC_Matches", "%d", Get_NumTrackSCMatches()); - AddString(items, "#_Track_DIRC_Matches", "%d", Get_NumTrackDIRCMatches()); + AddString(items, "#_Track_DIRC_Matches", "%d", Get_NumTrackDIRCMatches()); + AddString(items, "#_Track_CTOF_Matches", "%d", Get_NumTrackCTOFMatches()); + AddString(items, "#_Track_FMWPC_Matches", "%d", Get_NumTrackFMWPCMatches()); } private: @@ -198,6 +244,8 @@ class DDetectorMatches : public JObject map > > dTrackFCALSingleHitMatchParams; map > > dTrackFCALMatchParams; map > > dTrackTOFMatchParams; + map > > dTrackCTOFMatchParams; + map > > dTrackFMWPCMatchParams; map > > dTrackSCMatchParams; map > dTrackDIRCMatchParams; @@ -205,6 +253,7 @@ class DDetectorMatches : public JObject map > > dBCALTrackMatchParams; map > > dFCALTrackMatchParams; map > > dTOFTrackMatchParams; + map > > dCTOFTrackMatchParams; map > > dSCTrackMatchParams; map, vector > dDIRCTrackMatchParams; @@ -247,6 +296,26 @@ inline bool DDetectorMatches::Get_FCALMatchParams(const DTrackingData* locTrack, return true; } +inline bool DDetectorMatches::Get_CTOFMatchParams(const DTrackingData* locTrack, vector >& locMatchParams) const +{ + locMatchParams.clear(); + auto locIterator = dTrackCTOFMatchParams.find(locTrack); + if(locIterator == dTrackCTOFMatchParams.end()) + return false; + locMatchParams = locIterator->second; + return true; +} + +inline bool DDetectorMatches::Get_FMWPCMatchParams(const DTrackingData* locTrack, vector >& locMatchParams) const +{ + locMatchParams.clear(); + auto locIterator = dTrackFMWPCMatchParams.find(locTrack); + if(locIterator == dTrackFMWPCMatchParams.end()) + return false; + locMatchParams = locIterator->second; + return true; +} + inline bool DDetectorMatches::Get_TOFMatchParams(const DTrackingData* locTrack, vector >& locMatchParams) const { locMatchParams.clear(); @@ -309,6 +378,10 @@ inline bool DDetectorMatches::Get_IsMatchedToDetector(const DTrackingData* locTr return (dTrackTOFMatchParams.find(locTrack) != dTrackTOFMatchParams.end()); else if(locDetectorSystem == SYS_START) return (dTrackSCMatchParams.find(locTrack) != dTrackSCMatchParams.end()); + else if(locDetectorSystem == SYS_CTOF) + return (dTrackCTOFMatchParams.find(locTrack) != dTrackCTOFMatchParams.end()); + else if(locDetectorSystem == SYS_FMWPC) + return (dTrackFMWPCMatchParams.find(locTrack) != dTrackFMWPCMatchParams.end()); else return false; } @@ -333,6 +406,16 @@ inline bool DDetectorMatches::Get_TrackMatchParams(const DFCALShower* locFCALSho return true; } +inline bool DDetectorMatches::Get_TrackMatchParams(const DCTOFPoint* locCTOFPoint, vector >& locMatchParams) const +{ + locMatchParams.clear(); + auto locIterator = dCTOFTrackMatchParams.find(locCTOFPoint); + if(locIterator == dCTOFTrackMatchParams.end()) + return false; + locMatchParams = locIterator->second; + return true; +} + inline bool DDetectorMatches::Get_TrackMatchParams(const DTOFPoint* locTOFPoint, vector >& locMatchParams) const { locMatchParams.clear(); @@ -429,6 +512,24 @@ inline size_t DDetectorMatches::Get_NumTrackTOFMatches(void) const return locNumTrackMatches; } +inline size_t DDetectorMatches::Get_NumTrackCTOFMatches(void) const +{ + auto locIterator = dTrackCTOFMatchParams.begin(); + unsigned int locNumTrackMatches = 0; + for(; locIterator != dTrackCTOFMatchParams.end(); ++locIterator) + locNumTrackMatches += locIterator->second.size(); + return locNumTrackMatches; +} + +inline size_t DDetectorMatches::Get_NumTrackFMWPCMatches(void) const +{ + auto locIterator = dTrackFMWPCMatchParams.begin(); + unsigned int locNumTrackMatches = 0; + for(; locIterator != dTrackFMWPCMatchParams.end(); ++locIterator) + locNumTrackMatches += locIterator->second.size(); + return locNumTrackMatches; +} + inline size_t DDetectorMatches::Get_NumTrackSCMatches(void) const { auto locIterator = dTrackSCMatchParams.begin(); @@ -462,6 +563,15 @@ inline void DDetectorMatches::Add_Match(const DTrackingData* locTrack, const DTO dTrackTOFMatchParams[locTrack].push_back(locHitMatchParams); dTOFTrackMatchParams[locTOFPoint].push_back(locHitMatchParams); } +inline void DDetectorMatches::Add_Match(const DTrackingData* locTrack, const DCTOFPoint* locCTOFPoint, const shared_ptr& locHitMatchParams) +{ + dTrackCTOFMatchParams[locTrack].push_back(locHitMatchParams); + dCTOFTrackMatchParams[locCTOFPoint].push_back(locHitMatchParams); +} +inline void DDetectorMatches::Add_Match(const DTrackingData* locTrack, const shared_ptr& locHitMatchParams) +{ + dTrackFMWPCMatchParams[locTrack].push_back(locHitMatchParams); +} inline void DDetectorMatches::Add_Match(const DTrackingData* locTrack, const DSCHit* locSCHit, const shared_ptr& locHitMatchParams) { dTrackSCMatchParams[locTrack].push_back(locHitMatchParams); diff --git a/src/libraries/PID/DDetectorMatches_factory.cc b/src/libraries/PID/DDetectorMatches_factory.cc index 64608d0214..50f9e778ca 100644 --- a/src/libraries/PID/DDetectorMatches_factory.cc +++ b/src/libraries/PID/DDetectorMatches_factory.cc @@ -66,6 +66,12 @@ DDetectorMatches* DDetectorMatches_factory::Create_DDetectorMatches(jana::JEvent vector locDIRCBarHits; locEventLoop->Get(locDIRCBarHits); + vector locCTOFPoints; + locEventLoop->Get(locCTOFPoints); + + vector locFMWPCClusters; + locEventLoop->Get(locFMWPCClusters); + DDetectorMatches* locDetectorMatches = new DDetectorMatches(); //Match tracks to showers/hits @@ -76,6 +82,10 @@ DDetectorMatches* DDetectorMatches_factory::Create_DDetectorMatches(jana::JEvent MatchToFCAL(locParticleID, locTrackTimeBasedVector[loc_i], locFCALShowers, locDetectorMatches); MatchToSC(locParticleID, locTrackTimeBasedVector[loc_i], locSCHits, locDetectorMatches); MatchToDIRC(locParticleID, locTrackTimeBasedVector[loc_i], locDIRCHits, locDetectorMatches, locDIRCBarHits); + if (locTrackTimeBasedVector[loc_i]->PID()<10){ // GEANT ids; ignore proton=14 and kaons=11+12 + MatchToCTOF(locParticleID, locTrackTimeBasedVector[loc_i], locCTOFPoints, locDetectorMatches); + MatchToFMWPC(locTrackTimeBasedVector[loc_i], locFMWPCClusters, locDetectorMatches); + } } //Find nearest tracks to showers @@ -137,6 +147,92 @@ void DDetectorMatches_factory::MatchToBCAL(const DParticleID* locParticleID, con } } +void DDetectorMatches_factory::MatchToFMWPC(const DTrackTimeBased* locTrackTimeBased, const vector& locFMWPCClusters, DDetectorMatches* locDetectorMatches) const{ + auto fmwpc_projections=locTrackTimeBased->extrapolations.at(SYS_FMWPC); + if (fmwpc_projections.size()==0) return; + + // Loop over projections filling in arrays of matching info + vectorlocLayers; + vectorlocNhits; + vectorlocDists; + vectorlocClosestWires; + const double FMWPC_WIRE_SPACING=1.016; //cm + bool got_match=false; + for( int layer=1; layer<=(int)fmwpc_projections.size(); layer++){ + auto proj = fmwpc_projections[layer-1]; + // x and y projections from track + double xpos=proj.position.x(); + double ypos=proj.position.y(); + + // Loop over DFMWPCClusters and find closest match to this projection + int min_dist = 1000000; + int wire_trk_proj=0; + const DFMWPCCluster* closest_fmwpc_cluster= nullptr; + for(auto fmwpccluster : locFMWPCClusters){ + if( fmwpccluster->layer != layer ) continue; + + // Convert into local coordinates so we can work with wire numbers + double s=fmwpccluster->orientation==DGeometry::kFMWPC_WIRE_ORIENTATION_VERTICAL ? xpos+fmwpccluster->xoffset : ypos+fmwpccluster->yoffset; + wire_trk_proj = round(71.5 + s/FMWPC_WIRE_SPACING) + 1; // 1-144 + + // If the projection is outside of the wire range then bail now + if( (wire_trk_proj<1) || (wire_trk_proj>144) ) continue; + + int dist=1000000; + if( wire_trk_proj >= fmwpccluster->first_wire ){ + dist = wire_trk_proj - fmwpccluster->last_wire; // distance beyond last wire (will be negative if inside cluster) + if( dist < 0 ) dist = 0; // force dist to 0 if inside cluster + }else{ + dist = fmwpccluster->first_wire - wire_trk_proj; // distance before first wire + } + + if( dist < min_dist ){ + min_dist = dist; + closest_fmwpc_cluster = fmwpccluster; + } + } + + // If a DFMWPCCluster was found, add the match info to the track + if( closest_fmwpc_cluster ){ + int closest_wire=wire_trk_proj; + if (wire_trk_proj < closest_fmwpc_cluster->first_wire ) { + closest_wire = closest_fmwpc_cluster->first_wire; + } + else if (wire_trk_proj > closest_fmwpc_cluster->last_wire){ + closest_wire = closest_fmwpc_cluster->last_wire; + } + locLayers.push_back(layer); + locNhits.push_back(closest_fmwpc_cluster->Nhits); + locDists.push_back(min_dist); + locClosestWires.push_back(closest_wire); + + got_match=true; + } + } + if (got_match){ + shared_ptrlocFMWPCMatchParams=std::make_shared(); + locFMWPCMatchParams->dLayers=locLayers; + locFMWPCMatchParams->dNhits=locNhits; + locFMWPCMatchParams->dDists=locDists; + locFMWPCMatchParams->dClosestWires=locClosestWires; + locDetectorMatches->Add_Match(locTrackTimeBased,locFMWPCMatchParams); + } +} + +void DDetectorMatches_factory::MatchToCTOF(const DParticleID* locParticleID, const DTrackTimeBased* locTrackTimeBased, const vector& locCTOFPoints, DDetectorMatches* locDetectorMatches) const +{ + vector extrapolations=locTrackTimeBased->extrapolations.at(SYS_CTOF); + if (extrapolations.size()==0) return; + + double locInputStartTime = locTrackTimeBased->t0(); + for(size_t loc_i = 0; loc_i < locCTOFPoints.size(); ++loc_i) + { + shared_ptr locCTOFHitMatchParams; + if(locParticleID->Cut_MatchDistance(extrapolations, locCTOFPoints[loc_i], locInputStartTime, locCTOFHitMatchParams)) + locDetectorMatches->Add_Match(locTrackTimeBased, locCTOFPoints[loc_i], locCTOFHitMatchParams); + } +} + void DDetectorMatches_factory::MatchToTOF(const DParticleID* locParticleID, const DTrackTimeBased* locTrackTimeBased, const vector& locTOFPoints, DDetectorMatches* locDetectorMatches) const { vector extrapolations=locTrackTimeBased->extrapolations.at(SYS_TOF); diff --git a/src/libraries/PID/DDetectorMatches_factory.h b/src/libraries/PID/DDetectorMatches_factory.h index ef2a443fce..38324eac7c 100644 --- a/src/libraries/PID/DDetectorMatches_factory.h +++ b/src/libraries/PID/DDetectorMatches_factory.h @@ -17,6 +17,8 @@ #include #include #include +#include +#include #include #include #include @@ -46,6 +48,8 @@ class DDetectorMatches_factory : public jana::JFactory void MatchToFCAL(const DParticleID* locParticleID, const DTrackTimeBased* locTrackTimeBased, const vector& locFCALShowers, DDetectorMatches* locDetectorMatches) const; void MatchToSC(const DParticleID* locParticleID, const DTrackTimeBased* locTrackTimeBased, const vector& locSCHits, DDetectorMatches* locDetectorMatches) const; void MatchToDIRC(const DParticleID* locParticleID, const DTrackTimeBased* locTrackTimeBased, const vector& locDIRCHits, DDetectorMatches* locDetectorMatches, const vector& locDIRCBarHits) const; + void MatchToCTOF(const DParticleID* locParticleID, const DTrackTimeBased* locTrackTimeBased, const vector& locCTOFPoints, DDetectorMatches* locDetectorMatches) const; + void MatchToFMWPC(const DTrackTimeBased* locTrackTimeBased, const vector& locFMWPCClusters, DDetectorMatches* locDetectorMatches) const; void MatchToFCAL(const DParticleID* locParticleID, const DTrackTimeBased *locTrackTimeBased, diff --git a/src/libraries/PID/DParticleID.cc b/src/libraries/PID/DParticleID.cc index 38da759da1..017f172e45 100644 --- a/src/libraries/PID/DParticleID.cc +++ b/src/libraries/PID/DParticleID.cc @@ -46,6 +46,8 @@ DParticleID::DParticleID(JEventLoop *loop) CDC_TRUNCATE_DEDX = true; gPARMS->SetDefaultParameter("PID:CDC_TRUNCATE_DEDX",CDC_TRUNCATE_DEDX); + ADD_FCAL_DATA_FOR_CPP=false; + gPARMS->SetDefaultParameter("PID:ADD_FCAL_DATA_FOR_CPP",ADD_FCAL_DATA_FOR_CPP); DApplication* dapp = dynamic_cast(loop->GetJApplication()); if(!dapp){ @@ -140,6 +142,9 @@ DParticleID::DParticleID(JEventLoop *loop) BCAL_PHI_CUT_PAR3 = 0.8; gPARMS->SetDefaultParameter("BCAL:PHI_CUT_PAR3",BCAL_PHI_CUT_PAR3); + gPARMS->SetDefaultParameter("CTOF:MATCH_X_CUT",CTOF_MATCH_X_CUT); + gPARMS->SetDefaultParameter("CTOF:MATCH_Y_CUT",CTOF_MATCH_Y_CUT); + double locSCCutPar = 8.0; gPARMS->SetDefaultParameter("SC:SC_CUT_PAR1",locSCCutPar); dSCCutPars_TimeBased.push_back(locSCCutPar); @@ -1299,6 +1304,37 @@ bool DParticleID::Distance_ToTrack(const vector & locShowerMatchParams->dPathLength = locPathLength; locShowerMatchParams->dDOCAToShower = d; + // The following additional information is needed for CPP ML mu/pi separation + if (ADD_FCAL_DATA_FOR_CPP){ + // Row/column corresponding to projected position + auto row = dFCALGeometry->row( (float)locProjPos.y() ); + auto col = dFCALGeometry->column( (float)locProjPos.x() ); + if (row>=0 && col>=0){ + locShowerMatchParams->dE5x5=0.; + locShowerMatchParams->dE3x3=0.; + locShowerMatchParams->dEcenter=0.; + // Get the list of hits from the cluster associated with the shower + const DFCALCluster*cluster=NULL; + locFCALShower->GetSingle(cluster); + if (cluster){ + vectorhits=cluster->GetHits(); + for( auto hit : hits ){ + auto delta_row = abs( dFCALGeometry->row(hit.ch) - row ); + auto delta_col = abs( dFCALGeometry->column(hit.ch) - col ); + if( (delta_row<=2) && (delta_col<=2) ){ + locShowerMatchParams->dE5x5 += hit.E; + if( (delta_row<=1) && (delta_col<=1) ){ + locShowerMatchParams->dE3x3 += hit.E; + if( (delta_row==0) && (delta_col==0) ){ + locShowerMatchParams->dEcenter = hit.E; + } + } + } + } + } + } + } // for CPP + return true; } bool DParticleID::Distance_ToTrack(const vector&extrapolations, const DTOFPoint* locTOFPoint, double locInputStartTime,shared_ptr& locTOFHitMatchParams, DVector3* locOutputProjPos, DVector3* locOutputProjMom) const @@ -1357,6 +1393,46 @@ bool DParticleID::Distance_ToTrack(const vector&e return true; } +bool DParticleID::Distance_ToTrack(const vector&extrapolations, const DCTOFPoint* locCTOFPoint, double locInputStartTime,shared_ptr& locCTOFHitMatchParams, DVector3* locOutputProjPos, DVector3* locOutputProjMom) const +{ + if(extrapolations.size()==0) + return false; + + // Find the track projection to the CTOF + DVector3 locProjPos=extrapolations[0].position; + DVector3 locProjMom=extrapolations[0].momentum; + double locFlightTime=extrapolations[0].t; + + double locHitTime = locCTOFPoint->t; + // Check that the hit is not out of time with respect to the track + double locDeltaT = locHitTime - locFlightTime - locInputStartTime; + if(fabs(locDeltaT) > OUT_OF_TIME_CUT) + return false; + + if(locOutputProjMom != nullptr) + { + *locOutputProjPos = locProjPos; + *locOutputProjMom = locProjMom; + } + + double locDeltaX = locCTOFPoint->pos.X() - locProjPos.X(); + double locDeltaY = locCTOFPoint->pos.Y() - locProjPos.Y(); + + //SET MATCHING INFORMATION + if(locCTOFHitMatchParams == nullptr) + locCTOFHitMatchParams = std::make_shared(); + + locCTOFHitMatchParams->dCTOFPoint = locCTOFPoint; + double dx = 1.27*locProjMom.Mag()/locProjMom.Dot(DVector3(0.0,0.,1.)); + locCTOFHitMatchParams->dEdx = locCTOFPoint->dE/dx; + locCTOFHitMatchParams->dFlightTime = locFlightTime; + locCTOFHitMatchParams->dDeltaXToHit = locDeltaX; + locCTOFHitMatchParams->dDeltaYToHit = locDeltaY; + + return true; +} + + bool DParticleID::Distance_ToTrack(const vector &extrapolations, const DSCHit* locSCHit, double locInputStartTime,shared_ptr& locSCHitMatchParams, DVector3* locOutputProjPos, DVector3* locOutputProjMom) const { if(extrapolations.size()==0) @@ -1795,6 +1871,27 @@ bool DParticleID::Cut_MatchDistance(const vector return true; } +bool DParticleID::Cut_MatchDistance(const vector &extrapolations, const DCTOFPoint* locCTOFPoint, double locInputStartTime,shared_ptr& locCTOFHitMatchParams, DVector3 *locOutputProjPos, DVector3 *locOutputProjMom) const +{ + DVector3 locProjPos, locProjMom; + if(!Distance_ToTrack(extrapolations, locCTOFPoint, locInputStartTime, locCTOFHitMatchParams, &locProjPos, &locProjMom)) + return false; + + if(locOutputProjMom != nullptr) + { + *locOutputProjPos = locProjPos; + *locOutputProjMom = locProjMom; + } + + double locDeltaX = locCTOFHitMatchParams->dDeltaXToHit; + if (fabs(locDeltaX)>CTOF_MATCH_X_CUT) return false; + + double locDeltaY = locCTOFHitMatchParams->dDeltaYToHit; + if (fabs(locDeltaY)>CTOF_MATCH_Y_CUT) return false; + + return true; +} + bool DParticleID::Cut_MatchDistance(const vector &extrapolations, const DSCHit* locSCHit, double locInputStartTime,shared_ptr& locSCHitMatchParams, bool locIsTimeBased, DVector3 *locOutputProjPos, DVector3 *locOutputProjMom) const { DVector3 locProjPos, locProjMom; @@ -1898,6 +1995,33 @@ shared_ptr DParticleID::Get_BestSCMatchParams(vector& locBestMatchParams) const +{ + //choose the "best" hit to use for computing quantities + vector > locCTOFHitMatchParams; + if(!locDetectorMatches->Get_CTOFMatchParams(locTrack, locCTOFHitMatchParams)) + return false; + + locBestMatchParams = Get_BestCTOFMatchParams(locCTOFHitMatchParams); + return true; +} + +shared_ptr DParticleID::Get_BestCTOFMatchParams(vector >& locCTOFHitMatchParams) const +{ + double locMinDistance = 9.9E9; + shared_ptr locBestMatchParams; + for(size_t loc_i = 0; loc_i < locCTOFHitMatchParams.size(); ++loc_i) + { + double locDeltaR = locCTOFHitMatchParams[loc_i]->Get_DistanceToTrack(); + if(locDeltaR >= locMinDistance) + continue; + locMinDistance = locDeltaR; + locBestMatchParams = locCTOFHitMatchParams[loc_i]; + } + return locBestMatchParams; +} + + bool DParticleID::Get_BestTOFMatchParams(const DTrackingData* locTrack, const DDetectorMatches* locDetectorMatches, shared_ptr& locBestMatchParams) const { //choose the "best" hit to use for computing quantities diff --git a/src/libraries/PID/DParticleID.h b/src/libraries/PID/DParticleID.h index c66ac88faf..5602c296b0 100644 --- a/src/libraries/PID/DParticleID.h +++ b/src/libraries/PID/DParticleID.h @@ -29,6 +29,7 @@ #include #include #include +#include #include #include #include @@ -129,6 +130,7 @@ class DParticleID:public jana::JObject const DVector3 &locProjPos) const; bool Distance_ToTrack(const vector &extrapolations, const DFCALShower* locFCALShower, double locInputStartTime, shared_ptr& locShowerMatchParams, DVector3* locOutputProjPos=nullptr, DVector3* locOutputProjMom=nullptr) const; bool Distance_ToTrack(const vector&extrapolations, const DTOFPoint* locTOFPoint, double locInputStartTime,shared_ptr& locTOFHitMatchParams, DVector3* locOutputProjPos=nullptr, DVector3* locOutputProjMom=nullptr) const; + bool Distance_ToTrack(const vector&extrapolations, const DCTOFPoint* locCTOFPoint, double locInputStartTime,shared_ptr& locCTOFHitMatchParams, DVector3* locOutputProjPos=nullptr, DVector3* locOutputProjMom=nullptr) const; bool Distance_ToTrack(const vector &extrapolations, const DSCHit* locSCHit, double locInputStartTime,shared_ptr& locSCHitMatchParams, DVector3* locOutputProjPos=nullptr, DVector3* locOutputProjMom=nullptr) const; bool Distance_ToTrack(const vector &extrapolations, const DBCALShower* locBCALShower, double locInputStartTime,shared_ptr& locShowerMatchParams, DVector3* locOutputProjPos=nullptr, DVector3* locOutputProjMom=nullptr) const; bool Distance_ToTrack(double locStartTime,const DTrackFitter::Extrapolation_t &extrapolation,const DFCALHit *locFCALHit,double &locDOCA,double &locHitTime) const; @@ -143,7 +145,8 @@ class DParticleID:public jana::JObject bool Cut_MatchDistance(const vector &extrapolations, const DBCALShower* locBCALShower, double locInputStartTime,shared_ptr& locShowerMatchParams, DVector3 *locOutputProjPos=nullptr, DVector3 *locOutputProjMom=nullptr) const; bool Cut_MatchDistance(const vector &extrapolations, const DFCALShower* locFCALShower, double locInputStartTime,shared_ptr& locShowerMatchParams, DVector3 *locOutputProjPos=nullptr, DVector3 *locOutputProjMom=nullptr) const; - bool Cut_MatchDistance(const vector &extrapolations, const DTOFPoint* locTOFPoint, double locInputStartTime,shared_ptr& locTOFHitMatchParams, DVector3 *locOutputProjPos=nullptr, DVector3 *locOutputProjMom=nullptr) const; + bool Cut_MatchDistance(const vector &extrapolations, const DTOFPoint* locTOFPoint, double locInputStartTime,shared_ptr& locTOFHitMatchParams, DVector3 *locOutputProjPos=nullptr, DVector3 *locOutputProjMom=nullptr) const; + bool Cut_MatchDistance(const vector &extrapolations, const DCTOFPoint* locCTOFPoint, double locInputStartTime,shared_ptr& locCTOFHitMatchParams, DVector3 *locOutputProjPos=nullptr, DVector3 *locOutputProjMom=nullptr) const; bool Cut_MatchDistance(const vector &extrapolations, const DSCHit* locSCHit, double locInputStartTime,shared_ptr& locSCHitMatchParams, bool locIsTimeBased, DVector3 *locOutputProjPos=nullptr, DVector3 *locOutputProjMom=nullptr) const; bool Cut_MatchDIRC(const vector &extrapolations, const vector locDIRCHits, double locInputStartTime, Particle_t locPID, shared_ptr& locDIRCMatchParams, const vector locDIRCBarHits, map, vector >& locDIRCTrackMatchParams, DVector3 *locOutputProjPos=nullptr, DVector3 *locOutputProjMom=nullptr) const; @@ -152,7 +155,8 @@ class DParticleID:public jana::JObject // Wrappers bool Get_BestBCALMatchParams(const DTrackingData* locTrack, const DDetectorMatches* locDetectorMatches, shared_ptr& locBestMatchParams) const; bool Get_BestSCMatchParams(const DTrackingData* locTrack, const DDetectorMatches* locDetectorMatches, shared_ptr& locBestMatchParams) const; - bool Get_BestTOFMatchParams(const DTrackingData* locTrack, const DDetectorMatches* locDetectorMatches, shared_ptr& locBestMatchParams) const; + bool Get_BestTOFMatchParams(const DTrackingData* locTrack, const DDetectorMatches* locDetectorMatches, shared_ptr& locBestMatchParams) const; + bool Get_BestCTOFMatchParams(const DTrackingData* locTrack, const DDetectorMatches* locDetectorMatches, shared_ptr& locBestMatchParams) const; bool Get_BestFCALMatchParams(const DTrackingData* locTrack, const DDetectorMatches* locDetectorMatches, shared_ptr& locBestMatchParams) const; bool Get_BestFCALSingleHitMatchParams(const DTrackingData* locTrack, const DDetectorMatches* locDetectorMatches, shared_ptr& locBestMatchParams) const; bool Get_DIRCMatchParams(const DTrackingData* locTrack, const DDetectorMatches* locDetectorMatches, shared_ptr& locBestMatchParams) const; @@ -161,6 +165,7 @@ class DParticleID:public jana::JObject shared_ptr Get_BestBCALMatchParams(DVector3 locMomentum, vector >& locShowerMatchParams) const; shared_ptr Get_BestSCMatchParams(vector >& locSCHitMatchParams) const; shared_ptr Get_BestTOFMatchParams(vector >& locTOFHitMatchParams) const; + shared_ptr Get_BestCTOFMatchParams(vector >& locCTOFHitMatchParams) const; shared_ptr Get_BestFCALMatchParams(vector >& locShowerMatchParams) const; shared_ptr Get_BestFCALSingleHitMatchParams(vector >& locMatchParams) const; @@ -259,6 +264,7 @@ class DParticleID:public jana::JObject double dA_CDC; double dA_FDC; + double CTOF_MATCH_X_CUT=20.,CTOF_MATCH_Y_CUT=20.0; double BCAL_Z_CUT,BCAL_PHI_CUT_PAR1,BCAL_PHI_CUT_PAR2, BCAL_PHI_CUT_PAR3; double FCAL_CUT_PAR1,FCAL_CUT_PAR2,FCAL_CUT_PAR3; double TOF_CUT_PAR1, TOF_CUT_PAR2, TOF_CUT_PAR3, TOF_CUT_PAR4; @@ -327,6 +333,7 @@ class DParticleID:public jana::JObject double CDC_TIME_CUT_FOR_DEDX; bool CDC_TRUNCATE_DEDX; // dE/dx truncation: ignore hits with highest dE + bool ADD_FCAL_DATA_FOR_CPP; double dTargetZCenter; diff --git a/src/libraries/SConscript b/src/libraries/SConscript index 8801cf1a45..6b81e2f049 100644 --- a/src/libraries/SConscript +++ b/src/libraries/SConscript @@ -6,7 +6,7 @@ import os Import('env osname') # Loop over libraries, building each -subdirs = ['include', 'BCAL', 'FCAL', 'DANA', 'TAGGER', 'HDGEOMETRY', 'TRACKING'] +subdirs = ['include', 'BCAL', 'FCAL', 'ECAL', 'DANA', 'TAGGER', 'HDGEOMETRY', 'TRACKING'] subdirs.extend(['CCAL', 'START_COUNTER', 'RF', 'TRIGGER', 'CDC', 'FDC', 'PID', 'KINFITTER', 'ANALYSIS']) subdirs.extend(['CERE', 'DIRC', 'HDDM', 'TOF', 'PAIR_SPECTROMETER', 'TPOL', 'FMWPC', 'TAC', 'TRD']) subdirs.extend(['DAQ', 'TTAB', 'EVENTSTORE']) diff --git a/src/libraries/TAGGER/DTAGHHit_factory_Calib.cc b/src/libraries/TAGGER/DTAGHHit_factory_Calib.cc index 55615eb037..baca7c4606 100644 --- a/src/libraries/TAGGER/DTAGHHit_factory_Calib.cc +++ b/src/libraries/TAGGER/DTAGHHit_factory_Calib.cc @@ -211,6 +211,11 @@ jerror_t DTAGHHit_factory_Calib::evnt(JEventLoop *loop, uint64_t eventnumber) for (unsigned int i=0; i < tdcdigihits.size(); i++) { const DTAGHTDCDigiHit *digihit = tdcdigihits[i]; + // throw away hits from bad or noisy counters + int quality = counter_quality[digihit->counter_id]; + if (quality == k_counter_dead || quality == k_counter_bad || quality == k_counter_noisy) + continue; + // Apply calibration constants here int counter = digihit->counter_id; double T = locTTabUtilities->Convert_DigiTimeToNs_F1TDC(digihit) - tdc_time_offsets[counter] + t_tdc_base; diff --git a/src/libraries/TAGGER/DTAGMHit_factory_Calib.cc b/src/libraries/TAGGER/DTAGMHit_factory_Calib.cc index bf5093f786..74e1f8e1f9 100644 --- a/src/libraries/TAGGER/DTAGMHit_factory_Calib.cc +++ b/src/libraries/TAGGER/DTAGMHit_factory_Calib.cc @@ -242,6 +242,11 @@ jerror_t DTAGMHit_factory_Calib::evnt(JEventLoop *loop, uint64_t eventnumber) for (unsigned int i=0; i < tdcdigihits.size(); i++) { const DTAGMTDCDigiHit *digihit = tdcdigihits[i]; + // throw away hits from bad or noisy fibers + int quality = fiber_quality[digihit->row][digihit->column]; + if (quality == k_fiber_dead || quality == k_fiber_bad || quality == k_fiber_noisy) + continue; + // Apply calibration constants here int row = digihit->row; int column = digihit->column; diff --git a/src/libraries/TOF/DTOFHit_factory.cc b/src/libraries/TOF/DTOFHit_factory.cc index 342997c8d4..a0502c7fcd 100644 --- a/src/libraries/TOF/DTOFHit_factory.cc +++ b/src/libraries/TOF/DTOFHit_factory.cc @@ -166,6 +166,8 @@ jerror_t DTOFHit_factory::brun(jana::JEventLoop *eventLoop, int32_t runnumber) vector raw_adc_offsets; vector raw_tdc_offsets; vector raw_adc2E; + vector raw_adc_bad_channels; + vector raw_tdc_bad_channels; if(print_messages) jout << "In DTOFHit_factory, loading constants..." << endl; @@ -244,6 +246,13 @@ jerror_t DTOFHit_factory::brun(jana::JEventLoop *eventLoop, int32_t runnumber) string locTOFADCTimeOffetsTable = tofGeom.Get_CCDB_DirectoryName() + "/adc_timing_offsets"; if(eventLoop->GetCalib(locTOFADCTimeOffetsTable.c_str(), raw_adc_offsets)) jout << "Error loading " << locTOFADCTimeOffetsTable << " !" << endl; + + string locADCBadChannelsTable = tofGeom.Get_CCDB_DirectoryName() + "/adc_bad_channels"; + if(eventLoop->GetCalib(locADCBadChannelsTable.c_str(), raw_adc_bad_channels)) + jout << "Error loading " << locADCBadChannelsTable << " !" << endl; + string locTDCBadChannelsTable = tofGeom.Get_CCDB_DirectoryName() + "/tdc_bad_channels"; + if(eventLoop->GetCalib(locTDCBadChannelsTable.c_str(), raw_tdc_bad_channels)) + jout << "Error loading " << locTDCBadChannelsTable << " !" << endl; // check which walk correction to use: string locTOFWalkCorrectionType = tofGeom.Get_CCDB_DirectoryName() + "/walkcorr_type"; @@ -322,6 +331,8 @@ jerror_t DTOFHit_factory::brun(jana::JEventLoop *eventLoop, int32_t runnumber) FillCalibTable(adc_gains, raw_adc_gains, tofGeom); FillCalibTable(adc_time_offsets, raw_adc_offsets, tofGeom); FillCalibTable(tdc_time_offsets, raw_tdc_offsets, tofGeom); + FillCalibTable(adc_bad_channels, raw_adc_bad_channels, tofGeom); + FillCalibTable(tdc_bad_channels, raw_tdc_bad_channels, tofGeom); string locTOFADC2ETable = tofGeom.Get_CCDB_DirectoryName() + "/adc2E"; @@ -368,12 +379,20 @@ jerror_t DTOFHit_factory::evnt(JEventLoop *loop, uint64_t eventnumber) const DTTabUtilities* locTTabUtilities = NULL; loop->GetSingle(locTTabUtilities); - + + // // First, make hits out of all fADC250 hits + // vector digihits; loop->Get(digihits); for(unsigned int i=0; i 0 ) continue; // Error checking for pre-Fall 2016 firmware if(digihit->datasource == 1) { @@ -497,7 +516,7 @@ jerror_t DTOFHit_factory::evnt(JEventLoop *loop, uint64_t eventnumber) hit->has_fADC=true; hit->has_TDC=false; - + /* cout << "TOF ADC hit = (" << hit->plane << "," << hit->bar << "," << hit->end << ") " << t_scale << " " << T << " " @@ -508,7 +527,7 @@ jerror_t DTOFHit_factory::evnt(JEventLoop *loop, uint64_t eventnumber) hit->AddAssociatedObject(digihit); _data.push_back(hit); - } + } // looping over all fADC hits done //Get the TDC hits vector tdcdigihits; @@ -521,6 +540,12 @@ jerror_t DTOFHit_factory::evnt(JEventLoop *loop, uint64_t eventnumber) for(unsigned int i=0; iConvert_DigiTimeToNs_CAEN1290TDC(digihit); @@ -534,9 +559,8 @@ jerror_t DTOFHit_factory::evnt(JEventLoop *loop, uint64_t eventnumber) << T << " " << GetConstant(tdc_time_offsets, digihit) << endl; */ - // Look for existing hits to see if there is a match - // or create new one if there is no match DTOFHit *hit = FindMatch(digihit->plane, digihit->bar, digihit->end, T); + //DTOFHit *hit = FindMatch(digihit->plane, hit->bar, hit->end, T); if(!hit){ continue; // Do not use unmatched TDC hits @@ -552,7 +576,8 @@ jerror_t DTOFHit_factory::evnt(JEventLoop *loop, uint64_t eventnumber) _data.push_back(hit); */ - } else if (hit->has_TDC) { // this tof ADC hit has already a matching TDC, make new tof ADC hit + } else if (hit->has_TDC) { + // found matching ADC hit but this ADC hit has already a matching TDC, make new tof ADC hit DTOFHit *newhit = new DTOFHit; newhit->plane = hit->plane; newhit->bar = hit->bar; @@ -568,9 +593,10 @@ jerror_t DTOFHit_factory::evnt(JEventLoop *loop, uint64_t eventnumber) _data.push_back(newhit); hit = newhit; } + hit->has_TDC=true; hit->t_TDC=T; - + if (hit->dE>0.){ // time walk correction @@ -600,8 +626,10 @@ jerror_t DTOFHit_factory::evnt(JEventLoop *loop, uint64_t eventnumber) T -= tcorr; } + // save the walk corrected TDC time hit->t=T; + hit->AddAssociatedObject(digihit); } @@ -627,7 +655,9 @@ DTOFHit* DTOFHit_factory::FindMatch(int plane, int bar, int end, double T) /// in ns. The default time window is 20ns. DTOFHit* best_match = NULL; - + double MatchWindow = (double )DELTA_T_ADC_TDC_MAX; + + // Loop over existing hits (from fADC) and look for a match // in both the sector and the time. @@ -641,7 +671,7 @@ DTOFHit* DTOFHit_factory::FindMatch(int plane, int bar, int end, double T) //double delta_T = fabs(hit->t - T); double delta_T = fabs(T - hit->t); - if(delta_T > DELTA_T_ADC_TDC_MAX) continue; + if(delta_T > MatchWindow) continue; // if there are multiple hits, pick the one that is closest in time if(best_match != NULL) { diff --git a/src/libraries/TOF/DTOFHit_factory.h b/src/libraries/TOF/DTOFHit_factory.h index ff76a278be..44d1f4d60f 100644 --- a/src/libraries/TOF/DTOFHit_factory.h +++ b/src/libraries/TOF/DTOFHit_factory.h @@ -65,8 +65,8 @@ class DTOFHit_factory:public jana::JFactory{ // Timing Cut Values double TimeCenterCut; ///< timing cut values to select in time hits double TimeWidthCut; ///< timing cut values to select in time hits - double hi_time_cut; ///< timing cut values to select in time hits - double lo_time_cut; ///< timing cut values to select in time hits + double hi_time_cut=100.; ///< timing cut values to select in time hits + double lo_time_cut=-100.; ///< timing cut values to select in time hits // ADC to Energy conversion for individual PMT channels vector adc2E; ///< ADC to energy converstion values (loaded from CCDB) @@ -82,6 +82,8 @@ class DTOFHit_factory:public jana::JFactory{ tof_digi_constants_t adc_gains; tof_digi_constants_t adc_time_offsets; tof_digi_constants_t tdc_time_offsets; + tof_digi_constants_t adc_bad_channels; + tof_digi_constants_t tdc_bad_channels; vector >timewalk_parameters; ///< walk parameters for walk correction v0 vector >timewalk_parameters_AMP; ///< walk parameters for walk correction v1 diff --git a/src/libraries/TOF/DTOFPaddleHit_factory.cc b/src/libraries/TOF/DTOFPaddleHit_factory.cc index 76e7e6a746..7c0dd85108 100644 --- a/src/libraries/TOF/DTOFPaddleHit_factory.cc +++ b/src/libraries/TOF/DTOFPaddleHit_factory.cc @@ -37,6 +37,9 @@ using namespace std; #include "DTOFHit.h" #include "DTOFHitMC.h" #include "DTOFPaddleHit.h" +#include +#include + #include //#define NaN std::numeric_limits::quiet_NaN() @@ -51,16 +54,26 @@ jerror_t DTOFPaddleHit_factory::brun(JEventLoop *loop, int32_t runnumber) /// values like the number of bars in a plane the length of the bars, the effective /// speed of light in the bars and attenuation lengths. - + DApplication* dapp = dynamic_cast(loop->GetJApplication()); + const DGeometry *geom = dapp->GetDGeometry(runnumber); + // load values from geometry - loop->Get(TOFGeom); - TOF_NUM_PLANES = TOFGeom[0]->Get_NPlanes(); - TOF_NUM_BARS = TOFGeom[0]->Get_NBars(); - HALFPADDLE = TOFGeom[0]->Get_HalfLongBarLength(); - - - map tofparms; - string locTOFParmsTable = TOFGeom[0]->Get_CCDB_DirectoryName() + "/tof_parms"; + map paddle_params; + geom->GetTOFPaddleParameters(paddle_params); + TOF_NUM_BARS=paddle_params["NLONGBARS"]+paddle_params["NSHORTBARS"]/2; + TOF_NUM_PLANES=2; // not likely to change... + HALFPADDLE=paddle_params["HALFLONGBARLENGTH"]; + FirstShortBar = paddle_params["FIRSTSHORTBAR"]; + LastShortBar = paddle_params["LASTSHORTBAR"]; + + map tofparms; + string ccdb_directory_name; + if(TOF_NUM_BARS == 46) { + ccdb_directory_name="TOF2"; + } else { + ccdb_directory_name="TOF"; + } + string locTOFParmsTable = ccdb_directory_name + "/tof_parms"; if( !loop->GetCalib(locTOFParmsTable.c_str(), tofparms)) { //cout<<"DTOFPaddleHit_factory: loading values from TOF data base"<Get_CCDB_DirectoryName() + "/propagation_speed"; + string locTOFPropSpeedTable = ccdb_directory_name + "/propagation_speed"; if(eventLoop->GetCalib(locTOFPropSpeedTable.c_str(), propagation_speed)) jout << "Error loading " << locTOFPropSpeedTable << " !" << endl; - string locTOFAttenLengthTable = TOFGeom[0]->Get_CCDB_DirectoryName() + "/attenuation_lengths"; + string locTOFAttenLengthTable = ccdb_directory_name + "/attenuation_lengths"; if(eventLoop->GetCalib(locTOFAttenLengthTable.c_str(), AttenuationLengths)) jout << "Error loading " << locTOFAttenLengthTable << " !" << endl; @@ -166,7 +179,7 @@ jerror_t DTOFPaddleHit_factory::evnt(JEventLoop *loop, uint64_t eventnumber) int bar = P1hitsL[i]->bar; - if ((bar < TOFGeom[0]->Get_FirstShortBar() ) || (bar > TOFGeom[0]->Get_LastShortBar())) { + if ((bar < FirstShortBar) || (bar > LastShortBar)) { // we are dealing with double ended readout paddles: for (unsigned int j=0; jbar; int found = 0; - if ((bar < TOFGeom[0]->Get_FirstShortBar()) || (bar > TOFGeom[0]->Get_LastShortBar())) { + if ((bar < FirstShortBar) || (bar > LastShortBar)) { for (unsigned int j=0; jbar){ found = 1; @@ -228,7 +241,7 @@ jerror_t DTOFPaddleHit_factory::evnt(JEventLoop *loop, uint64_t eventnumber) int bar = P1hitsR[i]->bar; int found = 0; - if ((bar < TOFGeom[0]->Get_FirstShortBar()) || (bar > TOFGeom[0]->Get_LastShortBar())) { + if ((bar < FirstShortBar) || (bar > LastShortBar)) { for (unsigned int j=0; jbar){ found = 1; @@ -256,7 +269,7 @@ jerror_t DTOFPaddleHit_factory::evnt(JEventLoop *loop, uint64_t eventnumber) // now the same thing for plane 2 for (unsigned int i=0; ibar; - if ((bar < TOFGeom[0]->Get_FirstShortBar()) || (bar > TOFGeom[0]->Get_LastShortBar() )){ + if ((bar < FirstShortBar) || (bar > LastShortBar )){ for (unsigned int j=0; jbar && fabs(P2hitsR[j]->t-P2hitsL[i]->t)bar; int found = 0; - if ((bar < TOFGeom[0]->Get_FirstShortBar()) || (bar > TOFGeom[0]->Get_LastShortBar())) { + if ((bar < FirstShortBar) || (bar > LastShortBar)) { for (unsigned int j=0; jbar){ found = 1; @@ -313,7 +326,7 @@ jerror_t DTOFPaddleHit_factory::evnt(JEventLoop *loop, uint64_t eventnumber) int bar = P2hitsR[i]->bar; int found = 0; - if ((bar < TOFGeom[0]->Get_FirstShortBar()) || (bar > TOFGeom[0]->Get_LastShortBar())) { + if ((bar < FirstShortBar) || (bar > LastShortBar)) { for (unsigned int j=0; jbar){ found = 1; diff --git a/src/libraries/TOF/DTOFPaddleHit_factory.h b/src/libraries/TOF/DTOFPaddleHit_factory.h index e9e182400f..6a6214873e 100644 --- a/src/libraries/TOF/DTOFPaddleHit_factory.h +++ b/src/libraries/TOF/DTOFPaddleHit_factory.h @@ -21,7 +21,6 @@ #include "JANA/JParameterManager.h" #include "JANA/JEventLoop.h" #include "DTOFPaddleHit.h" -#include "DTOFGeometry.h" #include "TMath.h" using namespace jana; @@ -46,12 +45,12 @@ class DTOFPaddleHit_factory:public JFactory{ int TOF_NUM_PLANES; ///< number of TOF planes is 2 int TOF_NUM_BARS; ///< number of paddles in a plane 44 ( 46 for TOF2) + int FirstShortBar,LastShortBar; vector propagation_speed; ///< effective speed of light in paddle (each paddle separate) from CCDB vector < vector > AttenuationLengths; ///< attenuation length in paddle from CCDB - vector TOFGeom; ///< tof geometry class (vector has only one element) protected: //jerror_t init(void); ///< Called once at program start. diff --git a/src/libraries/TOF/DTOFPoint_factory.cc b/src/libraries/TOF/DTOFPoint_factory.cc index ba6100540f..acc98c1612 100644 --- a/src/libraries/TOF/DTOFPoint_factory.cc +++ b/src/libraries/TOF/DTOFPoint_factory.cc @@ -19,6 +19,8 @@ using namespace std; #include "DTOFPoint_factory.h" +#include +#include bool Compare_TOFSpacetimeHitMatches_Distance(const DTOFPoint_factory::tof_spacetimehitmatch_t& locTOFSpacetimeHitMatch1, const DTOFPoint_factory::tof_spacetimehitmatch_t& locTOFSpacetimeHitMatch2) { @@ -36,10 +38,35 @@ bool Compare_TOFPoint_Time(const DTOFPoint *locTOFPoint1, const DTOFPoint *locTO //------------------ jerror_t DTOFPoint_factory::brun(JEventLoop *loop, int32_t runnumber) { - loop->GetSingle(dTOFGeometry); - + DApplication* dapp = dynamic_cast(loop->GetJApplication()); + const DGeometry *geom = dapp->GetDGeometry(runnumber); + + // load values from geometry + vector YWIDTH; ///> y (perpendicular) bar width per bar number + geom->GetTOFPaddlePerpPositions(YPOS, YWIDTH); + geom->GetTOFZ(CenterVertPlane,CenterHorizPlane,CenterMidPlane); + + map paddle_params; + geom->GetTOFPaddleParameters(paddle_params); + + FirstShortBar = paddle_params["FIRSTSHORTBAR"]; + LastShortBar = paddle_params["LASTSHORTBAR"]; + HALFPADDLE = paddle_params["HALFLONGBARLENGTH"]; + HALFPADDLE_ONESIDED = paddle_params["HALFSHORTBARLENGTH"]; + double locBeamHoleWidth = paddle_params["LONGBARLENGTH"] + - 2.0*paddle_params["SHORTBARLENGTH"]; + ONESIDED_PADDLE_MIDPOINT_MAG = HALFPADDLE_ONESIDED + locBeamHoleWidth/2.0; + NUM_BARS = paddle_params["NLONGBARS"]+paddle_params["NSHORTBARS"]/2; + + string ccdb_directory_name; + if (NUM_BARS == 46) { + ccdb_directory_name="TOF2"; + } else { + ccdb_directory_name="TOF"; + } + map tofparms; - string locTOFParmsTable = dTOFGeometry->Get_CCDB_DirectoryName() + "/tof_parms"; + string locTOFParmsTable = ccdb_directory_name + "/tof_parms"; if( !loop->GetCalib(locTOFParmsTable.c_str(), tofparms)) { //cout<<"DTOFPoint_factory: loading values from TOF data base"<Get_CCDB_DirectoryName() + "/propagation_speed"; + string locTOFPropSpeedTable = ccdb_directory_name + "/propagation_speed"; if(eventLoop->GetCalib(locTOFPropSpeedTable.c_str(), propagation_speed)) jout << "Error loading " << locTOFPropSpeedTable << " !" << endl; - string locTOFPaddleResolTable = dTOFGeometry->Get_CCDB_DirectoryName() + "/paddle_resolutions"; + string locTOFPaddleResolTable = ccdb_directory_name + "/paddle_resolutions"; if(eventLoop->GetCalib(locTOFPaddleResolTable.c_str(), paddle_resolutions)) jout << "Error loading " << locTOFPaddleResolTable << " !" << endl; // for applying attentuation to half lenfgth paddles - string locTOFAttenLengthTable = dTOFGeometry->Get_CCDB_DirectoryName() + "/attenuation_lengths"; + string locTOFAttenLengthTable = ccdb_directory_name + "/attenuation_lengths"; if(eventLoop->GetCalib(locTOFAttenLengthTable.c_str(), AttenuationLengths)) jout << "Error loading " << locTOFAttenLengthTable << " !" << endl; - - - HALFPADDLE = dTOFGeometry->Get_HalfLongBarLength(); - HALFPADDLE_ONESIDED = dTOFGeometry->Get_HalfShortBarLength(); - double locBeamHoleWidth = dTOFGeometry->Get_LongBarLength() - 2.0*dTOFGeometry->Get_ShortBarLength(); - ONESIDED_PADDLE_MIDPOINT_MAG = HALFPADDLE_ONESIDED + locBeamHoleWidth/2.0; - - NUM_BARS = dTOFGeometry->Get_NBars(); - + dPositionMatchCut_DoubleEnded = 9.0; //1.5*BARWIDTH // dTimeMatchCut_PositionWellDefined = 1.0; dTimeMatchCut_PositionWellDefined = 10.0; @@ -199,11 +218,11 @@ DTOFPoint_factory::tof_spacetimehit_t* DTOFPoint_factory::Build_TOFSpacetimeHit_ int id = NUM_BARS + locTOFHit->bar - 1; double v = propagation_speed[id]; - if((locTOFHit->bar < dTOFGeometry->Get_FirstShortBar()) || (locTOFHit->bar > dTOFGeometry->Get_LastShortBar())) //double-ended bars + if((locTOFHit->bar < FirstShortBar) || (locTOFHit->bar >LastShortBar)) //double-ended bars { locTOFSpacetimeHit->dIsDoubleEndedBar = true; locTOFSpacetimeHit->dIsSingleEndedNorthPaddle = false; - locTOFSpacetimeHit->y = dTOFGeometry->bar2y(bar); + locTOFSpacetimeHit->y = bar2y(bar); if(locTOFHit->meantime != locTOFHit->meantime) { //NaN: only one energy hit above threshold on the double-ended bar @@ -239,14 +258,14 @@ DTOFPoint_factory::tof_spacetimehit_t* DTOFPoint_factory::Build_TOFSpacetimeHit_ if(locTOFHit->t_south != 0.) { locTOFSpacetimeHit->dIsSingleEndedNorthPaddle = false; - locTOFSpacetimeHit->y = dTOFGeometry->bar2y(bar,1); + locTOFSpacetimeHit->y = bar2y(bar,1); locTOFSpacetimeHit->x = -1.0*ONESIDED_PADDLE_MIDPOINT_MAG; locTOFSpacetimeHit->t = locTOFHit->t_south - HALFPADDLE_ONESIDED/v; } else { locTOFSpacetimeHit->dIsSingleEndedNorthPaddle = true; - locTOFSpacetimeHit->y = dTOFGeometry->bar2y(bar,0); + locTOFSpacetimeHit->y = bar2y(bar,0); locTOFSpacetimeHit->x = ONESIDED_PADDLE_MIDPOINT_MAG; locTOFSpacetimeHit->t = locTOFHit->t_north - HALFPADDLE_ONESIDED/v; } @@ -264,12 +283,12 @@ DTOFPoint_factory::tof_spacetimehit_t* DTOFPoint_factory::Build_TOFSpacetimeHit_ int id = locTOFHit->bar - 1; double v = propagation_speed[id]; - if((locTOFHit->bar < dTOFGeometry->Get_FirstShortBar()) || (locTOFHit->bar > dTOFGeometry->Get_LastShortBar())) + if((locTOFHit->bar < FirstShortBar) || (locTOFHit->bar > LastShortBar)) { //double-ended bars locTOFSpacetimeHit->dIsDoubleEndedBar = true; locTOFSpacetimeHit->dIsSingleEndedNorthPaddle = false; - locTOFSpacetimeHit->x = dTOFGeometry->bar2y(bar); + locTOFSpacetimeHit->x = bar2y(bar); if(locTOFHit->meantime != locTOFHit->meantime) { //NaN: only one energy hit above threshold on the double-ended bar @@ -303,14 +322,14 @@ DTOFPoint_factory::tof_spacetimehit_t* DTOFPoint_factory::Build_TOFSpacetimeHit_ if(locTOFHit->t_south != 0.) { locTOFSpacetimeHit->dIsSingleEndedNorthPaddle = false; - locTOFSpacetimeHit->x = dTOFGeometry->bar2y(bar,0); + locTOFSpacetimeHit->x = bar2y(bar,0); locTOFSpacetimeHit->y = -1.0*ONESIDED_PADDLE_MIDPOINT_MAG; locTOFSpacetimeHit->t = locTOFHit->t_south - HALFPADDLE_ONESIDED/v; } else { locTOFSpacetimeHit->dIsSingleEndedNorthPaddle = true; - locTOFSpacetimeHit->x = dTOFGeometry->bar2y(bar,1); + locTOFSpacetimeHit->x = bar2y(bar,1); locTOFSpacetimeHit->y = ONESIDED_PADDLE_MIDPOINT_MAG; locTOFSpacetimeHit->t = locTOFHit->t_north - HALFPADDLE_ONESIDED/v; } @@ -332,13 +351,13 @@ bool DTOFPoint_factory::Match_Hits(tof_spacetimehit_t* locTOFSpacetimeHit_Horizo if(locTOFSpacetimeHit_Horizontal->dIsSingleEndedNorthPaddle) { //horizontal is on north (+x) side - if(locTOFSpacetimeHit_Vertical->TOFHit->bar < dTOFGeometry->Get_FirstShortBar()) + if(locTOFSpacetimeHit_Vertical->TOFHit->bar < FirstShortBar) return false; //vertical is on south (-x) side: CANNOT MATCH } else { //horizontal is on south (-x) side - if(locTOFSpacetimeHit_Vertical->TOFHit->bar > dTOFGeometry->Get_LastShortBar()) + if(locTOFSpacetimeHit_Vertical->TOFHit->bar > LastShortBar) return false; //vertical is on north (+x) side: CANNOT MATCH } } @@ -348,13 +367,13 @@ bool DTOFPoint_factory::Match_Hits(tof_spacetimehit_t* locTOFSpacetimeHit_Horizo if(locTOFSpacetimeHit_Vertical->dIsSingleEndedNorthPaddle) { //vertical is on north (+y) side - if(locTOFSpacetimeHit_Horizontal->TOFHit->bar < dTOFGeometry->Get_FirstShortBar()) + if(locTOFSpacetimeHit_Horizontal->TOFHit->bar < FirstShortBar) return false; //horizontal is on south (-y) side: CANNOT MATCH } else { //vertical is on south (-y) side - if(locTOFSpacetimeHit_Horizontal->TOFHit->bar > dTOFGeometry->Get_LastShortBar()) + if(locTOFSpacetimeHit_Horizontal->TOFHit->bar > LastShortBar) return false; //horizontal is on north (+y) side: CANNOT MATCH } } @@ -407,7 +426,7 @@ void DTOFPoint_factory::Create_MatchedTOFPoint(const tof_spacetimehit_t* locTOFS //is x/y resolution from energy calibration better than x/y resolution from paddle edges? locMatchX = locTOFSpacetimeHit_Horizontal->x; locMatchY = locTOFSpacetimeHit_Vertical->y; - locMatchZ = dTOFGeometry->Get_CenterMidPlane(); //z: midpoint between tof planes + locMatchZ = CenterMidPlane; //z: midpoint between tof planes locMatchT = 0.5*(locTOFSpacetimeHit_Horizontal->t + locTOFSpacetimeHit_Vertical->t); locMatchdE = 0.5*(locTOFHit_Horizontal->dE + locTOFHit_Vertical->dE); locMatchTErr = 0.5 * sqrt(locVMatchTErr*locVMatchTErr + locHMatchTErr*locHMatchTErr); @@ -422,7 +441,7 @@ void DTOFPoint_factory::Create_MatchedTOFPoint(const tof_spacetimehit_t* locTOFS locMatchX = locTOFSpacetimeHit_Horizontal->x; locMatchY = locTOFSpacetimeHit_Horizontal->y; locMatchT = locTOFSpacetimeHit_Horizontal->t; - locMatchZ = dTOFGeometry->Get_CenterHorizPlane(); //z: center of horizontal plane + locMatchZ = CenterHorizPlane; //z: center of horizontal plane locMatchdE = locTOFHit_Horizontal->dE; locMatchTErr = locHMatchTErr; locMatchdE2 = locTOFHit_Horizontal->dE; @@ -459,7 +478,7 @@ void DTOFPoint_factory::Create_MatchedTOFPoint(const tof_spacetimehit_t* locTOFS locMatchX = locTOFSpacetimeHit_Vertical->x; locMatchY = locTOFSpacetimeHit_Vertical->y; locMatchT = locTOFSpacetimeHit_Vertical->t; - locMatchZ = dTOFGeometry->Get_CenterVertPlane(); //z: center of vertical plane + locMatchZ = CenterVertPlane; //z: center of vertical plane locMatchdE = locTOFHit_Vertical->dE; locMatchTErr = locVMatchTErr; locMatchdE1 = locTOFHit_Vertical->dE; @@ -518,7 +537,7 @@ void DTOFPoint_factory::Create_UnMatchedTOFPoint(const tof_spacetimehit_t* locTO { const DTOFPaddleHit* locPaddleHit = locTOFSpacetimeHit->TOFHit; bool locIsHorizontalBarFlag = (locPaddleHit->orientation == 1); - float locPointZ = locIsHorizontalBarFlag ? dTOFGeometry->Get_CenterHorizPlane() : dTOFGeometry->Get_CenterVertPlane(); + float locPointZ = locIsHorizontalBarFlag ? CenterHorizPlane : CenterVertPlane; int id_vert = locPaddleHit->bar - 1; int id_horiz = NUM_BARS + locPaddleHit->bar - 1; @@ -557,10 +576,12 @@ void DTOFPoint_factory::Create_UnMatchedTOFPoint(const tof_spacetimehit_t* locTO } else { - //position not well defined: save anyway: + return; + + //position not well defined: save anyway: //Will use track matching to define position in the other direction //Then, will update the hit energy and time based on that position - + /* DTOFPoint* locTOFPoint = new DTOFPoint; locTOFPoint->AddAssociatedObject(locPaddleHit); @@ -589,6 +610,7 @@ void DTOFPoint_factory::Create_UnMatchedTOFPoint(const tof_spacetimehit_t* locTO return; _data.push_back(locTOFPoint); + */ } } diff --git a/src/libraries/TOF/DTOFPoint_factory.h b/src/libraries/TOF/DTOFPoint_factory.h index e92fe8f311..66f7fdebcc 100644 --- a/src/libraries/TOF/DTOFPoint_factory.h +++ b/src/libraries/TOF/DTOFPoint_factory.h @@ -19,7 +19,6 @@ #define _DTOFPoint_factory_ #include "JANA/JFactory.h" -#include "DTOFGeometry_factory.h" #include "DTOFPoint.h" #include "DTOFPaddleHit.h" #include "DTOFHit.h" @@ -50,9 +49,7 @@ class DTOFPoint_factory : public JFactory int NUM_BARS; vector < vector > AttenuationLengths; - - const DTOFGeometry* dTOFGeometry; - + class tof_spacetimehit_t { public: @@ -95,6 +92,21 @@ class DTOFPoint_factory : public JFactory float dPositionMatchCut_DoubleEnded; float dTimeMatchCut_PositionWellDefined; float dTimeMatchCut_PositionNotWellDefined; + + float bar2y(int bar, int end=0) const + ///> convert bar number to the + ///> position of the center of the + ///> bar in local coordinations + { + float y; + y = YPOS.at(bar); + + // handle position of short bars + if (bar>=FirstShortBar && bar<=LastShortBar && end != 0) y *= -1.0; + + return y; + } + size_t MAX_TOFSpacetimeHitPoolSize; deque dTOFSpacetimeHitPool_All; @@ -104,6 +116,11 @@ class DTOFPoint_factory : public JFactory vector propagation_speed; vector paddle_resolutions; + // Geometrical variables and indexes for bars + vector YPOS; ///> y (perpendicular) position for bar number + double CenterHorizPlane,CenterVertPlane,CenterMidPlane; + int FirstShortBar,LastShortBar; + }; #endif // _DTOFPoint_factory_ diff --git a/src/libraries/TRACKING/DTrackTimeBased_factory.cc b/src/libraries/TRACKING/DTrackTimeBased_factory.cc index 7c7bac84a3..6838e9aa01 100644 --- a/src/libraries/TRACKING/DTrackTimeBased_factory.cc +++ b/src/libraries/TRACKING/DTrackTimeBased_factory.cc @@ -235,7 +235,9 @@ jerror_t DTrackTimeBased_factory::brun(jana::JEventLoop *loop, int32_t runnumber // Get CDC wire geometry data geom->GetCDCWires(cdcwires); // geom->GetCDCRmid(cdc_rmid); // THIS ISN'T IMPLEMENTED!! + // extract the "mean" radius of each ring from the wire data + cdc_rmid.clear(); for(uint ring=0; ringorigin.Perp() ); diff --git a/src/libraries/TRIGGER/DL1MCTrigger_factory.cc b/src/libraries/TRIGGER/DL1MCTrigger_factory.cc index e9c3d7585d..cbf3be5263 100644 --- a/src/libraries/TRIGGER/DL1MCTrigger_factory.cc +++ b/src/libraries/TRIGGER/DL1MCTrigger_factory.cc @@ -67,8 +67,12 @@ jerror_t DL1MCTrigger_factory::init(void) BCAL_OFFSET = 2; + SC_OFFSET = 6; + SIMU_BASELINE = 1; - SIMU_GAIN = 1; + SIMU_GAIN = 0; + + VERBOSE = 0; simu_baseline_fcal = 1; @@ -123,7 +127,9 @@ jerror_t DL1MCTrigger_factory::init(void) gPARMS->SetDefaultParameter("TRIG:BCAL_OFFSET", BCAL_OFFSET, "Timing offset between BCAL and FCAL energies at GTP (sampels)"); - + + gPARMS->SetDefaultParameter("TRIG:SC_OFFSET", SC_OFFSET, + "Timing offset between SC and FCAL and BCAL energies at GTP (sampels)"); // Allows to switch off gain and baseline fluctuations gPARMS->SetDefaultParameter("TRIG:SIMU_BASELINE", SIMU_BASELINE, @@ -131,6 +137,9 @@ jerror_t DL1MCTrigger_factory::init(void) gPARMS->SetDefaultParameter("TRIG:SIMU_GAIN", SIMU_GAIN, "Enable simulation of gain variations"); + + gPARMS->SetDefaultParameter("TRIG:VERBOSE", VERBOSE, + "Enable more verbose output"); BCAL_ADC_PER_MEV_CORRECT = 22.7273; @@ -189,10 +198,10 @@ jerror_t DL1MCTrigger_factory::brun(jana::JEventLoop *eventLoop, int32_t runnumb if(getenv("JANA_CALIB_CONTEXT") != NULL ){ JANA_CALIB_CONTEXT = getenv("JANA_CALIB_CONTEXT"); - cout << " ---------DL1MCTrigger (Brun): JANA_CALIB_CONTEXT =" << JANA_CALIB_CONTEXT << endl; + if(print_messages) cout << " ---------DL1MCTrigger (Brun): JANA_CALIB_CONTEXT =" << JANA_CALIB_CONTEXT << endl; if ( (JANA_CALIB_CONTEXT.find("mc_generic") != string::npos) || (JANA_CALIB_CONTEXT.find("mc_cpp") != string::npos) ){ - cout << " ---------DL1MCTrigger (Brun): JANA_CALIB_CONTEXT found mc_generic or mc_cpp" << endl; + if(print_messages) cout << " ---------DL1MCTrigger (Brun): JANA_CALIB_CONTEXT found mc_generic or mc_cpp" << endl; use_rcdb = 0; // Don't simulate baseline fluctuations for mc_generic simu_baseline_fcal = 0; @@ -203,7 +212,7 @@ jerror_t DL1MCTrigger_factory::brun(jana::JEventLoop *eventLoop, int32_t runnumb } } else { - cout << " ---------**** DL1MCTrigger (Brun): JANA_CALIB_CONTEXT = NULL" << endl; + if(print_messages) cout << " ---------**** DL1MCTrigger (Brun): JANA_CALIB_CONTEXT = NULL" << endl; } // runnumber = 30942; @@ -351,9 +360,11 @@ jerror_t DL1MCTrigger_factory::evnt(JEventLoop *loop, uint64_t eventnumber){ vector fcal_hits; vector bcal_hits; + vector sc_hits; loop->Get(fcal_hits); loop->Get(bcal_hits); + loop->Get(sc_hits); DRandom2 gDRandom(0); // declared extern in DRandom2.h @@ -503,7 +514,8 @@ jerror_t DL1MCTrigger_factory::evnt(JEventLoop *loop, uint64_t eventnumber){ for(unsigned int ii = 0; ii < fcal_merged_hits.size(); ii++) for(int jj = 0; jj < sample; jj++) - fcal_hit_adc_en += fcal_merged_hits[ii].adc_amp[jj]; + if( (fcal_merged_hits[ii].adc_amp[jj] - TRIG_BASELINE) > 0.) + fcal_hit_adc_en += (fcal_merged_hits[ii].adc_amp[jj] - TRIG_BASELINE); status += FADC_SSP(fcal_merged_hits, 1); @@ -626,8 +638,8 @@ jerror_t DL1MCTrigger_factory::evnt(JEventLoop *loop, uint64_t eventnumber){ // Search for triggers - l1_found = FindTriggers(trigger); - + l1_found = FindTriggers(trigger,sc_hits); + if(l1_found){ int fcal_gtp_max = 0; @@ -939,7 +951,7 @@ int DL1MCTrigger_factory::Read_RCDB(int32_t runnumber, bool print_messages) } catch(...){ - if(print_messages) cout << "Exception: FCAL channel is not in the translation table " << " Crate = " << 10 + crate << " Slot = " << slot << + if(VERBOSE && print_messages) cout << "Exception: FCAL channel is not in the translation table " << " Crate = " << 10 + crate << " Slot = " << slot << " Channel = " << ch << endl; continue; } @@ -953,6 +965,9 @@ int DL1MCTrigger_factory::Read_RCDB(int32_t runnumber, bool print_messages) tmp.row = channel_info.fcal.row; tmp.col = channel_info.fcal.col; + if(VERBOSE) + cout << " MASKED CHANNEL = " << tmp.row << " " << tmp.col << endl; + fcal_trig_mask.push_back(tmp); } @@ -964,6 +979,7 @@ int DL1MCTrigger_factory::Read_RCDB(int32_t runnumber, bool print_messages) } // Loop over crates + if(VERBOSE) cout << " NUMBER OF MASKED CHANNELS = " << fcal_trig_mask.size() << endl; // Load BCAL Trigger Masks @@ -1326,15 +1342,33 @@ void DL1MCTrigger_factory::PrintTriggers(){ -int DL1MCTrigger_factory::FindTriggers(DL1MCTrigger *trigger){ +int DL1MCTrigger_factory::FindTriggers(DL1MCTrigger *trigger, vector & sc_hits){ + int debug1 = 0; + int trig_found = 0; // Main production trigger for(unsigned int ii = 0; ii < triggers_enabled.size(); ii++){ - if(triggers_enabled[ii].bit == 0){ // Main production trigger found - + if(debug1) + cout << "Trigger Type = " << triggers_enabled[ii].type << endl; + + if(triggers_enabled[ii].type == 3){ // FCAL & BCAL trigger + + int en_bit = triggers_enabled[ii].bit; + + int fcal_bcal_st = 0; + + for(unsigned int jj = 0; jj < triggers_enabled.size(); jj++){ // Check if other triggers are enabled with the same bit + + int en_bit1 = triggers_enabled[jj].bit; + + if(ii != jj) + if( (en_bit == en_bit1) && triggers_enabled[jj].type == 4 ) fcal_bcal_st = 1; + } + + int gtp_energy = 0; int bcal_energy = 0; @@ -1349,35 +1383,63 @@ int DL1MCTrigger_factory::FindTriggers(DL1MCTrigger *trigger){ } else{ bcal_energy = bcal_gtp[bcal_samp]; } - - + + gtp_energy = triggers_enabled[ii].gtp.fcal*fcal_gtp[samp] + triggers_enabled[ii].gtp.bcal*bcal_energy; + if(debug1) + cout << " GTP energy = " << gtp_energy << " " << triggers_enabled[ii].gtp.en_thr << endl; + + if(gtp_energy >= triggers_enabled[ii].gtp.en_thr){ - if(triggers_enabled[ii].gtp.fcal_min > 0) { // FCAL > 0 - if(fcal_gtp[samp] > triggers_enabled[ii].gtp.fcal_min){ - trigger->trig_mask = (trigger->trig_mask | 0x1); - trigger->trig_time[0] = samp - 25; + if(fcal_gtp[samp] > triggers_enabled[ii].gtp.fcal_min){ // FCAL > fcal_min + + int fcal_bcal_st_found = 0; + + if(fcal_bcal_st == 1){ // FCAL & BCAL & ST + for(unsigned int sc_hit = 0; sc_hit < sc_hits.size(); sc_hit++){ + + int sc_time = sc_hits[sc_hit]->t/time_stamp + 0.5 + SC_OFFSET; + int fcal_bcal_time = samp - 25; + + if(debug1){ + cout << sc_time << " " << " Trigger time " << fcal_bcal_time << endl; + cout << " ABS (DT) " << abs(fcal_bcal_time - sc_time) << endl; + } + + if(abs(fcal_bcal_time - sc_time) < 3){ // Coincidence between FCAL, BCAL, and SC found + trigger->trig_mask = (trigger->trig_mask | (1 << en_bit) ); + trigger->trig_time[0] = samp - 25; + trig_found++; + fcal_bcal_st_found = 1; + break; + } + } // Loop over SC hits + + if(fcal_bcal_st_found == 1) break; // Break from loop over samples + + } else { // FCAL & BCAL + trigger->trig_mask = (trigger->trig_mask | (1 << en_bit) ); + trigger->trig_time[0] = samp - 25; trig_found++; + break; } - } else { - - trigger->trig_mask = (trigger->trig_mask | 0x1); - trigger->trig_time[0] = samp - 25; - trig_found++; - } - - break; - } // Check energy threshold - } - } // Trigger Bit 0 + + } // Check fcal energy threshold + } // Check global energy threshold + + + } // Loop over samples + } // FCAL & BCAL triggers - if(triggers_enabled[ii].bit == 2){ // BCAL trigger found - + if(triggers_enabled[ii].type == 2){ // BCAL trigger + + int en_bit = triggers_enabled[ii].bit; + int gtp_energy = 0; int bcal_energy = 0; @@ -1392,12 +1454,12 @@ int DL1MCTrigger_factory::FindTriggers(DL1MCTrigger *trigger){ } else{ bcal_energy = bcal_gtp[bcal_samp]; } - + gtp_energy = triggers_enabled[ii].gtp.bcal*bcal_energy; - + if(gtp_energy >= triggers_enabled[ii].gtp.en_thr){ - trigger->trig_mask = (trigger->trig_mask | 0x4); + trigger->trig_mask = (trigger->trig_mask | (1 << en_bit)); trigger->trig_time[2] = samp - 25; trig_found++; @@ -1405,7 +1467,7 @@ int DL1MCTrigger_factory::FindTriggers(DL1MCTrigger *trigger){ } // Energy threshold } - } // Trigger Bit 3 + } // BCAL trigger } // Loop over triggers found in the config file diff --git a/src/libraries/TRIGGER/DL1MCTrigger_factory.h b/src/libraries/TRIGGER/DL1MCTrigger_factory.h index f93cc18e14..0f6945b983 100644 --- a/src/libraries/TRIGGER/DL1MCTrigger_factory.h +++ b/src/libraries/TRIGGER/DL1MCTrigger_factory.h @@ -13,6 +13,8 @@ #include +#include "START_COUNTER/DSCHit.h" + #include #include @@ -174,9 +176,13 @@ class DL1MCTrigger_factory:public jana::JFactory{ int ST_NHIT; int BCAL_OFFSET; - + + int SC_OFFSET; + int SIMU_BASELINE; int SIMU_GAIN; + + int VERBOSE; double time_shift; @@ -201,7 +207,7 @@ class DL1MCTrigger_factory:public jana::JFactory{ template int FADC_SSP(vector merged_hits, int detector); int GTP(int detector); - int FindTriggers(DL1MCTrigger *trigger); + int FindTriggers(DL1MCTrigger *trigger, vector &sc_hits); void PrintTriggers(); float BCAL_ADC_PER_MEV_CORRECT; diff --git a/src/libraries/TRIGGER/DTrigger_factory.cc b/src/libraries/TRIGGER/DTrigger_factory.cc index 9a350dd6d8..6132dbdf1a 100644 --- a/src/libraries/TRIGGER/DTrigger_factory.cc +++ b/src/libraries/TRIGGER/DTrigger_factory.cc @@ -12,7 +12,7 @@ jerror_t DTrigger_factory::init(void) EMULATE_FCAL_LED_TRIGGER = false; EMULATE_BCAL_LED_TRIGGER = false; - EMULATE_CAL_ENERGY_SUMS = false; + EMULATE_CAL_ENERGY_SUMS = true; BCAL_LED_NHITS_THRESHOLD = 200; FCAL_LED_NHITS_THRESHOLD = 200; diff --git a/src/libraries/TTAB/DTranslationTable.cc b/src/libraries/TTAB/DTranslationTable.cc index 7c867a4f3a..48dee79cb4 100644 --- a/src/libraries/TTAB/DTranslationTable.cc +++ b/src/libraries/TTAB/DTranslationTable.cc @@ -286,6 +286,7 @@ void DTranslationTable::SetSystemsToParse(string systems, int systems_to_parse_f rocid_map[name_to_id[ "BCAL"]] = {31, 32, 33, 34, 35 ,36, 37, 38, 39, 40, 41, 42}; rocid_map[name_to_id[ "CDC"]] = {25, 26, 27, 28}; rocid_map[name_to_id[ "FCAL"]] = {11, 12, 13, 14 ,15, 16, 17, 18, 19, 20, 21, 22}; + rocid_map[name_to_id[ "ECAL"]] = {111, 112, 113, 114 ,115, 116, 117}; rocid_map[name_to_id["FDC_CATHODES"]] = {52, 53, 55, 56, 57, 58, 59, 60, 61, 62}; rocid_map[name_to_id[ "FDC_WIRES"]] = {51, 54, 63, 64}; rocid_map[name_to_id[ "PS"]] = {83, 84}; @@ -408,6 +409,7 @@ void DTranslationTable::ApplyTranslationTable(JEventLoop *loop) const switch (chaninfo.det_sys) { case BCAL: MakeBCALDigiHit(chaninfo.bcal, pi, pt, pp); break; case FCAL: MakeFCALDigiHit(chaninfo.fcal, pi, pt, pp); break; + case ECAL: MakeECALDigiHit(chaninfo.ecal, pi, pt, pp); break; case CCAL: MakeCCALDigiHit(chaninfo.ccal, pi, pt, pp); break; case CCAL_REF: MakeCCALRefDigiHit(chaninfo.ccal_ref, pi, pt, pp); break; case SC: MakeSCDigiHit( chaninfo.sc, pi, pt, pp); break; @@ -454,6 +456,7 @@ void DTranslationTable::ApplyTranslationTable(JEventLoop *loop) const switch (chaninfo.det_sys) { case BCAL: MakeBCALDigiHit( chaninfo.bcal, pd); break; case FCAL: MakeFCALDigiHit( chaninfo.fcal, pd); break; + case ECAL: MakeECALDigiHit( chaninfo.ecal, pd); break; case CCAL: MakeCCALDigiHit( chaninfo.ccal, pd); break; case CCAL_REF: MakeCCALRefDigiHit( chaninfo.ccal_ref, pd); break; case SC: MakeSCDigiHit( chaninfo.sc, pd); break; @@ -826,6 +829,7 @@ void DTranslationTable::ApplyTranslationTable(JEventLoop *loop) const if(CALL_STACK){ Addf250ObjectsToCallStack(loop, "DBCALDigiHit"); Addf250ObjectsToCallStack(loop, "DFCALDigiHit"); + Addf250ObjectsToCallStack(loop, "DECALDigiHit"); Addf250ObjectsToCallStack(loop, "DCCALDigiHit"); Addf250ObjectsToCallStack(loop, "DCCALRefDigiHit"); Addf250ObjectsToCallStack(loop, "DSCDigiHit"); @@ -890,6 +894,35 @@ DFCALDigiHit* DTranslationTable::MakeFCALDigiHit(const FCALIndex_t &idx, return h; } + +//--------------------------------- +// MakeECALDigiHit +//--------------------------------- +DECALDigiHit* DTranslationTable::MakeECALDigiHit(const ECALIndex_t &idx, + const Df250PulseData *pd) const +{ + DECALDigiHit *h = new DECALDigiHit(); + CopyDf250Info(h, pd); + + // The ECAL coordinate system: (column,row) = (0,0) in the bottom right corner + + if(idx.col < 0) + h->column = idx.col + 20; + else if(idx.col > 0) + h->column = idx.col + 19; + + if(idx.row < 0) + h->row = idx.row + 20; + else if(idx.row > 0) + h->row = idx.row + 19; + + vDECALDigiHit.push_back(h); + + return h; +} + + + //--------------------------------- // MakeCCALDigiHit //--------------------------------- @@ -1101,6 +1134,34 @@ DFCALDigiHit* DTranslationTable::MakeFCALDigiHit(const FCALIndex_t &idx, return h; } +//--------------------------------- +// MakeECALDigiHit +//--------------------------------- +DECALDigiHit* DTranslationTable::MakeECALDigiHit(const ECALIndex_t &idx, + const Df250PulseIntegral *pi, + const Df250PulseTime *pt, + const Df250PulsePedestal *pp) const +{ + DECALDigiHit *h = new DECALDigiHit(); + CopyDf250Info(h, pi, pt, pp); + + if(idx.col < 0) + h->column = idx.col + 20; + else if(idx.col > 0) + h->column = idx.col + 19; + + if(idx.row < 0) + h->row = idx.row + 20; + else if(idx.row > 0) + h->row = idx.row + 19; + + vDECALDigiHit.push_back(h); + + return h; +} + + + //--------------------------------- // MakeCCALDigiHit //--------------------------------- @@ -1881,6 +1942,10 @@ const DTranslationTable::csc_t if ( det_channel.fcal == in_channel.fcal ) found = true; break; + case DTranslationTable::ECAL: + if ( det_channel.ecal == in_channel.ecal ) + found = true; + break; case DTranslationTable::CCAL: if ( det_channel.ccal == in_channel.ccal ) found = true; @@ -1992,6 +2057,9 @@ string DTranslationTable::Channel2Str(const DChannelInfo &in_channel) const case DTranslationTable::FCAL: ss << "row = " << in_channel.fcal.row << " column = " << in_channel.fcal.col; break; + case DTranslationTable::ECAL: + ss << "row = " << in_channel.ecal.row << " column = " << in_channel.ecal.col; + break; case DTranslationTable::CCAL: ss << "row = " << in_channel.ccal.row << " column = " << in_channel.ccal.col; break; @@ -2319,7 +2387,9 @@ DTranslationTable::Detector_t DetectorStr2DetID(string &type) } else if ( type == "cdc" ) { return DTranslationTable::CDC; } else if ( type == "fcal" ) { - return DTranslationTable::FCAL; + return DTranslationTable::FCAL; + } else if ( type == "ecal" ) { + return DTranslationTable::ECAL; } else if ( type == "ccal" ) { return DTranslationTable::CCAL; } else if ( type == "ccal_ref" ) { @@ -2573,6 +2643,10 @@ void StartElement(void *userData, const char *xmlname, const char **atts) ci.fcal.row = row; ci.fcal.col = column; break; + case DTranslationTable::ECAL: + ci.ecal.row = row; + ci.ecal.col = column; + break; case DTranslationTable::CCAL: ci.ccal.row = row; ci.ccal.col = column; diff --git a/src/libraries/TTAB/DTranslationTable.h b/src/libraries/TTAB/DTranslationTable.h index 57c4409e83..ac04e0458c 100644 --- a/src/libraries/TTAB/DTranslationTable.h +++ b/src/libraries/TTAB/DTranslationTable.h @@ -49,6 +49,7 @@ using namespace jana; #include #include #include +#include #include #include #include @@ -82,6 +83,7 @@ using namespace jana; X(DBCALTDCDigiHit) \ X(DCDCDigiHit) \ X(DFCALDigiHit) \ + X(DECALDigiHit) \ X(DCCALDigiHit) \ X(DCCALRefDigiHit) \ X(DFDCCathodeDigiHit) \ @@ -114,6 +116,7 @@ using namespace jana; X(DBCALDigiHit) \ X(DCDCDigiHit) \ X(DFCALDigiHit) \ + X(DECALDigiHit) \ X(DCCALDigiHit) \ X(DCCALRefDigiHit) \ X(DFDCCathodeDigiHit) \ @@ -178,6 +181,7 @@ class DTranslationTable:public jana::JObject{ FMWPC, CTOF, HELI, + ECAL, NUM_DETECTOR_TYPES }; @@ -186,6 +190,7 @@ class DTranslationTable:public jana::JObject{ case BCAL: return "BCAL"; case CDC: return "CDC"; case FCAL: return "FCAL"; + case ECAL: return "ECAL"; case CCAL: return "CCAL"; case CCAL_REF: return "CCAL_REF"; case FDC_CATHODES: return "FDC_CATHODES"; @@ -243,6 +248,16 @@ class DTranslationTable:public jana::JObject{ } }; + class ECALIndex_t{ + public: + int row; + int col; + + inline bool operator==(const ECALIndex_t &rhs) const { + return (row==rhs.row) && (col==rhs.col); + } + }; + class CCALIndex_t{ public: int row; @@ -443,6 +458,7 @@ class DTranslationTable:public jana::JObject{ TPOLSECTORIndex_t tpolsector; TACIndex_t tac; CCALIndex_t ccal; + ECALIndex_t ecal; CCALRefIndex_t ccal_ref; DIRCIndex_t dirc; TRDIndex_t trd; @@ -532,6 +548,7 @@ class DTranslationTable:public jana::JObject{ // fADC250 -- Fall 2016 -> ? DBCALDigiHit* MakeBCALDigiHit( const BCALIndex_t &idx, const Df250PulseData *pd) const; DFCALDigiHit* MakeFCALDigiHit( const FCALIndex_t &idx, const Df250PulseData *pd) const; + DECALDigiHit* MakeECALDigiHit( const ECALIndex_t &idx, const Df250PulseData *pd) const; DCCALDigiHit* MakeCCALDigiHit( const CCALIndex_t &idx, const Df250PulseData *pd) const; DCCALRefDigiHit* MakeCCALRefDigiHit( const CCALRefIndex_t &idx, const Df250PulseData *pd) const; DSCDigiHit* MakeSCDigiHit( const SCIndex_t &idx, const Df250PulseData *pd) const; @@ -550,6 +567,7 @@ class DTranslationTable:public jana::JObject{ // fADC250 -- commissioning -> Fall 2016 DBCALDigiHit* MakeBCALDigiHit(const BCALIndex_t &idx, const Df250PulseIntegral *pi, const Df250PulseTime *pt, const Df250PulsePedestal *pp) const; DFCALDigiHit* MakeFCALDigiHit(const FCALIndex_t &idx, const Df250PulseIntegral *pi, const Df250PulseTime *pt, const Df250PulsePedestal *pp) const; + DECALDigiHit* MakeECALDigiHit(const ECALIndex_t &idx, const Df250PulseIntegral *pi, const Df250PulseTime *pt, const Df250PulsePedestal *pp) const; DCCALDigiHit* MakeCCALDigiHit(const CCALIndex_t &idx, const Df250PulseIntegral *pi, const Df250PulseTime *pt, const Df250PulsePedestal *pp) const; DCCALRefDigiHit* MakeCCALRefDigiHit(const CCALRefIndex_t &idx, const Df250PulseIntegral *pi, const Df250PulseTime *pt, const Df250PulsePedestal *pp) const; DSCDigiHit* MakeSCDigiHit( const SCIndex_t &idx, const Df250PulseIntegral *pi, const Df250PulseTime *pt, const Df250PulsePedestal *pp) const; diff --git a/src/libraries/include/GlueX.h b/src/libraries/include/GlueX.h index 874df08cc8..6f9989f1a9 100644 --- a/src/libraries/include/GlueX.h +++ b/src/libraries/include/GlueX.h @@ -5,6 +5,7 @@ // Creator: davidl (on Darwin Harriet.local 7.8.0 powerpc) // Modified: yqiang, Oct 10 2012, add RICH // Modified: jrsteven, June 22 2015, move RICH -> DIRC and remove CERE +// Modified: somov, Jan 16 2024, added ECAL // #ifndef _GlueX_ @@ -26,6 +27,8 @@ enum DetectorSystem_t{ SYS_DIRC = 0x0200, SYS_CCAL = 0x0400, SYS_CCAL_REF = 0x0500, + SYS_ECAL = 0x0600, + SYS_ECAL_REF = 0x0700, SYS_TAGH = 0x0800, SYS_RF = 0x1000, SYS_PS = 0x2000, @@ -77,6 +80,12 @@ inline const char* SystemName(DetectorSystem_t sys) case SYS_DIRC: return "DIRC"; break; + case SYS_ECAL: + return "ECAL"; + break; + case SYS_ECAL_REF: + return "ECAL_REF"; + break; case SYS_CCAL: return "CCAL"; break; @@ -142,6 +151,10 @@ inline DetectorSystem_t NameToSystem(const char* locSystemName) return SYS_START; else if(strcmp(locSystemName, "DIRC") == 0) return SYS_DIRC; + else if(strcmp(locSystemName, "ECAL") == 0) + return SYS_ECAL; + else if(strcmp(locSystemName, "ECAL_REF") == 0) + return SYS_ECAL_REF; else if(strcmp(locSystemName, "CCAL") == 0) return SYS_CCAL; else if(strcmp(locSystemName, "CCAL_REF") == 0) diff --git a/src/libraries/include/particleType.h b/src/libraries/include/particleType.h index 290b276bbd..c10cbc9033 100644 --- a/src/libraries/include/particleType.h +++ b/src/libraries/include/particleType.h @@ -167,6 +167,7 @@ typedef enum { AntiD0 = 194, DMinus = 195, DstarMinus = 196, + Sigma_cPlusPlus = 197, /* These are defined in pythia-geant.map in bggen */ @@ -446,6 +447,8 @@ inline static char* ParticleType(Particle_t p) return (char*)"D*-"; case Lambda_c: return (char*)"LambdaC"; + case Sigma_cPlusPlus: + return (char*)"SigmaC++"; default: return (char*)"Unknown"; } @@ -705,6 +708,8 @@ inline static char* EnumString(Particle_t p) return (char*)"DstarMinus"; case Lambda_c: return (char*)"Lambda_c"; + case Sigma_cPlusPlus: + return (char*) "Sigma_cPlusPlus"; default: return (char*)"Unknown"; } @@ -964,6 +969,8 @@ inline static char* EvtGenString(Particle_t p) return (char*)"D*-"; case Lambda_c: return (char*)"Lambda_c0"; + case Sigma_cPlusPlus: + return (char*)"Sigma_c++"; default: return (char*)"Unknown"; } @@ -1191,6 +1198,8 @@ inline static char* ShortName(Particle_t locPID) return (char*)"dsm"; case Lambda_c: return (char*)"lambc"; + case Sigma_cPlusPlus: + return (char*)"sigcpp"; //not really supported case Rho0: @@ -1481,6 +1490,8 @@ inline static Particle_t ParticleEnum(const char* locParticleName) return DstarMinus; else if(strcmp(locParticleName, "LambdaC") == 0) return Lambda_c; + else if(strcmp(locParticleName, "SigmaC++") == 0) + return Sigma_cPlusPlus; else return Unknown; } @@ -1594,6 +1605,7 @@ inline static unsigned short int IsFixedMass(Particle_t p) case DstarPlus: return 1; case DstarMinus: return 1; case Lambda_c: return 1; + case Sigma_cPlusPlus: return 1; default: return 0; } } @@ -1900,6 +1912,8 @@ inline static char* ParticleName_ROOT(Particle_t p) return (char*)"D^{*-}"; case Lambda_c: return (char*)"#Lambda_{c}"; + case Sigma_cPlusPlus: + return (char*)"#Sigma_{c}^{++}"; default: return (char*)"X"; @@ -2035,6 +2049,7 @@ inline static double ParticleMass(Particle_t p) case DstarPlus: return 2.01026; case DstarMinus: return 2.01026; case Lambda_c: return 2.28646; + case Sigma_cPlusPlus: return 2.45397; default: fprintf(stderr,"ParticleMass: Error: Unknown particle type %d,",p); fprintf(stderr," returning HUGE_VAL...\n"); @@ -2171,6 +2186,7 @@ inline static int ParticleCharge(Particle_t p) case DstarPlus: return 1; case DstarMinus: return -1; case Lambda_c: return 1; + case Sigma_cPlusPlus: return 2; default: fprintf(stderr,"ParticleCharge: Error: Unknown particle type %d,",p); @@ -2308,6 +2324,7 @@ inline static int PDGtype(Particle_t p) case DstarPlus: return 413; case DstarMinus: return -413; case Lambda_c: return 4122; + case Sigma_cPlusPlus: return 4222; default: return 0; } } @@ -2438,6 +2455,7 @@ inline static Particle_t PDGtoPType(int locPDG_PID) case 413: return DstarPlus; case -413: return DstarMinus; case 4122: return Lambda_c; + case 4222: return Sigma_cPlusPlus; default: return Unknown; } } @@ -2735,6 +2753,8 @@ inline static char* Get_ShortName(Particle_t locPID) return (char*)"dm"; case Lambda_c: return (char*)"lambc"; + case Sigma_cPlusPlus: + return (char*)"sigcpp"; default: return (char*)"Unknown"; @@ -2816,6 +2836,7 @@ inline static int ParticleMultiplexPower(Particle_t locPID) case AntiD0: return 47; case DMinus: return 48; case DstarMinus: return 49; + case Sigma_cPlusPlus: return 50; default: return -1; } } @@ -2900,6 +2921,7 @@ inline static Particle_t DemultiplexPID(int locBit, int locIsDecayingFlag) case 47: return AntiD0; case 48: return DMinus; case 49: return DstarMinus; + case 50: return Sigma_cPlusPlus; default: return Unknown; } } diff --git a/src/plugins/Alignment/FDC_t0_alignment/README.md b/src/plugins/Alignment/FDC_t0_alignment/README.md new file mode 100644 index 0000000000..c9b2526245 --- /dev/null +++ b/src/plugins/Alignment/FDC_t0_alignment/README.md @@ -0,0 +1,62 @@ +Scripts for FDC t0 calibration. + + +# Preparation + +## Two input files should be prepared. +* input parameter file (see `input_example`) +* run-list file (see `runlist_example`) + +## Directives in input parameter file (`input_example`) +`path_to_input_ccdb_sqlite` absolute path to CCDB SQLite file used for the reconstruction (Mille plugin) + +`path_to_version_xml` absolute path to version XML file for the reconstruction + +`path_to_output_dir` absolute path to ouput directory for .mil files (outputs of Mille plugin) + +`path_to_swif2_output_dir` absolute path to swif2 (standard and error) outputs + +`path_to_pede` absolute path to the executable `pede`. See https://www.desy.de/~kleinwrt/MP2/doc/html/index.html to install Millepede (=`pede`). + +`path_to_output_ccdb_sqlite` absolute path to CCDB SQLite file for output results. This can be the same as `path_to_input_ccdb_sqlite`. + +`is_straight` true or false. true for field-on analysis, and false for field-off (=straight track) analysis. + +`num_of_events` Number of events which will be analyzed by Mille plugin. + + +# Scripts and how to use + +## mille.py +script for Mille plugin. + +.mil file is the main output which is necessary for the next `pede` step. + +This script is for run-by-run analysis. Use `swif2.py` to analyze multiple runs. + +Make sure raw data files (.evio files) are on the `/cache` disk before running this script (use `jcache get` command if necessary). + +`./mille.py your_input_parameter_file 120297` + +## swif2.py +script for swif2 job which runs multiple `mille.py` scripts. + +Again, make sure raw data files (.evio files) are on the `/cache` disk before running this script (use `jcache get` command if necessary). + +`./swif2.py your_input_parameter_file your_run_list_file` + +## pede.py +wrapper script for `pede` command. + +.mil files are necessary as inputs for this pede.py, so use `swif2.py` (or `mille.py`) before this script. + +This is for run-by-run fitting (new FDC t0 constants in output CCDB SQLite file will be set run-by-run). + +`./pede.py your_input_parameter_file 120297` + +## update_official_ccdb.py +script to update the officiaal CCDB. + +This script should be used after `pede.py`. + +`./update_official_ccdb.py your_ccdb.sqlite 120297` diff --git a/src/plugins/Alignment/FDC_t0_alignment/input_example b/src/plugins/Alignment/FDC_t0_alignment/input_example new file mode 100644 index 0000000000..63130f3117 --- /dev/null +++ b/src/plugins/Alignment/FDC_t0_alignment/input_example @@ -0,0 +1,17 @@ +# paths for mille.py +path_to_input_ccdb_sqlite /path/to/your/input/ccdb.sqlite +path_to_version_xml /group/halld/www/halldweb/html/halld_versions/version.xml +path_to_output_dir /path/to/your/output/directory/ + +# paths for swif2.py +path_to_swif2_output_dir /path/to/your/swif2/output/directory/ + +# paths for pede.py +path_to_pede /path/to/your/pede +path_to_output_ccdb_sqlite /path/to/your/output/ccdb.sqlite + +# B-field ON (MilleFieldOn) or OFF (MilleFieldOff)? true .. FieldOn analysis, false .. FieldOff analysis +is_straight false + +# Number of events analyzed. Negative number means full analysis. +num_of_events 1000000 diff --git a/src/plugins/Alignment/FDC_t0_alignment/mille.py b/src/plugins/Alignment/FDC_t0_alignment/mille.py new file mode 100755 index 0000000000..652fba8fc7 --- /dev/null +++ b/src/plugins/Alignment/FDC_t0_alignment/mille.py @@ -0,0 +1,127 @@ +#! /usr/bin/python +# coding:utf-8 + +import sys +import os +import glob +import shlex +import subprocess + + +def main(): + args = sys.argv + if len(args) != 3: + print('usage: ./mille.py input_parameter_file runnum') + exit(1) + + input_par_file = args[1] + runnum = int(args[2]) + + par = get_par(input_par_file) + + ver_xml = par['path_to_version_xml'] + ccdb_path = par['path_to_input_ccdb_sqlite'] + output_dir = par['path_to_output_dir'].rstrip('/') + '/' + is_straight = True if par['is_straight'].upper().startswith('T') else False + num_of_events = int(par['num_of_events']) + + gxenv(ver_xml) + run_period = get_runperiod(runnum) + evio_path = get_evio_path(run_period, runnum) + + # Checks if the output file already exists. + output_file = output_dir + '%06d.root' % runnum + if os.path.exists(output_file): + print('Error: file exists') + print(output_file) + exit(1) + + workingDir = os.getcwd() + if workingDir.find("slurm")!=-1: + cp_command = "cp " + ccdb_path + " " + workingDir + "/ccdb.sqlite" + os.system(cp_command) + ccdb_path = workingDir + "/ccdb.sqlite" + + sqlite_str = 'sqlite:///' + ccdb_path + os.environ['CCDB_CONNECTION'] = sqlite_str + os.environ['JANA_CALIB_URL'] = sqlite_str +# os.environ['JANA_GEOMETRY_URL'] = 'ccdb:///GEOMETRY/cpp_HDDS.xml' + + cmd_list = ['hd_root'] + if is_straight: + cmd_list.append('-PPLUGINS=MilleFieldOff,TrackingPulls_straight') + cmd_list.append('-PBFIELD_TYPE=NoField') + else: + cmd_list.append('-PPLUGINS=MilleFieldOn,TrackingPulls') + cmd_list.append('-PTRACKINGPULLS:MAKE_TREE=1') + cmd_list.append('-PTRACKINGPULLS:TREEFILE=%stree%06d.root' % (output_dir, runnum)) + cmd_list.append('-PTRKFIT:ALIGNMENT=1') + cmd_list.append('-PNTHREADS=24') + cmd_list.append('-PJANA:BATCH_MODE=1') + if num_of_events > 0: + cmd_list.append('-PEVENTS_TO_KEEP=%d' % num_of_events) + cmd_list.append(evio_path) + cmd_list.append('-o') + cmd_list.append(output_file) + subprocess.call(cmd_list) + + +def get_evio_path(run_period, runnum): + for br in range(10): + candidate = '/cache/halld/%s/rawdata/Run%06d/hd_rawdata_%06d_%03d.evio' % (run_period, runnum, runnum, br) + if os.path.exists(candidate): + print('Found:', candidate) + return candidate + + print('[Error] cannot find evio files') + exit(1) + + +def get_runperiod(runnum): + dir_list = glob.glob('/mss/halld/RunPeriod-*/rawdata/Run%06d' % runnum) + if len(dir_list) != 1: + print('Error in get_runperiod', dir_list) + exit(1) + run_period = '' + for x in dir_list[0].split('/'): + if 'RunPeriod' in x: + run_period = x + return run_period + + +# copied from https://stackoverflow.com/questions/3503719/emulating-bash-source-in-python +def source(source_command): + command = shlex.split("env -i bash -c '" + source_command + " && env'") + proc = subprocess.Popen(command, stdout = subprocess.PIPE) + for line in proc.stdout: + str_line = line.decode().strip() + i = str_line.find('=') + if i <= 0: + continue + key = str_line[:i] + value = str_line[i + 1:] + os.environ[key] = value + proc.communicate() + +def gxenv(ver_xml): + bs_save = os.environ['BUILD_SCRIPTS'] + source('source ' + bs_save + '/gluex_env_clean.sh') + os.environ['BUILD_SCRIPTS'] = bs_save + source('source ' + bs_save + '/gluex_env_jlab.sh ' + ver_xml) + + +def get_par(input_par_file): + with open(input_par_file) as f: + l0 = f.readlines() + + mydict = {} + for x in l0: + if x.strip().startswith('#') or len(x.strip().split()) < 2: + continue + mydict[x.strip().split()[0]] = x.strip().split()[1] + + return mydict + + +if __name__ == '__main__': + main() diff --git a/src/plugins/Alignment/FDC_t0_alignment/pede.py b/src/plugins/Alignment/FDC_t0_alignment/pede.py new file mode 100755 index 0000000000..ed7014bcdc --- /dev/null +++ b/src/plugins/Alignment/FDC_t0_alignment/pede.py @@ -0,0 +1,495 @@ +#! /apps/bin/python3 +# coding:utf-8 + +import os +import sys +import ccdb +import math +import subprocess + + +def main(): + args = sys.argv + if len(args) != 3: + print('usage: ./pede.py input_parameter_file runnum') + exit(0) + + input_par_file = args[1] + runnum = int(args[2]) + + par = get_par(input_par_file) + + pede_path = par['path_to_pede'] + in_ccdb_path = par['path_to_input_ccdb_sqlite'] + out_ccdb_path = par['path_to_output_ccdb_sqlite'] + rt_dir = par['path_to_output_dir'].rstrip('/') + '/' + mil_list = [rt_dir + '%06d.mil' % runnum] + + # CCDB table list + table_list = [] + table_list.append('/FDC/wire_alignment') + table_list.append('/FDC/cathode_alignment') + table_list.append('/FDC/strip_pitches_v2') + table_list.append('/FDC/cell_offsets') + table_list.append('/FDC/cell_rotations') + table_list.append('/FDC/package1/wire_timing_offsets') + table_list.append('/FDC/package2/wire_timing_offsets') + table_list.append('/FDC/package3/wire_timing_offsets') + table_list.append('/FDC/package4/wire_timing_offsets') + table_list.append('/FDC/drift_function_parms') + table_list.append('/FDC/drift_function_ext') + table_list.append('/FDC/base_time_offset') + table_list.append('/CDC/global_alignment') + table_list.append('/CDC/wire_alignment') + table_list.append('/CDC/timing_offsets') + + dict0 = ccdb2dict(in_ccdb_path, runnum, table_list) + + # Runs pede. + generate_mp2str_txt(mil_list, dict0) + subprocess.call([pede_path, 'mp2str.txt']) + + add_res_to_dict(dict0) # Updates dict0. + if not os.path.exists(out_ccdb_path): + subprocess.call(['cp', in_ccdb_path, out_ccdb_path]) + dict2ccdb(out_ccdb_path, runnum, dict0) + + # Deletes temporary files. + for x in ['millepede.res', 'millepede.end', 'millepede.end~', 'millepede.his', 'millepede.log', 'mp2str.txt']: + subprocess.call(['rm', x]) + + +def generate_mp2str_txt(mil_files_list, dict0): + trailer = '''\ +outlierdownweighting 3 ! number of internal iterations (> 1) +dwfractioncut 0.3 ! 0 < value < 0.5 +regularisation 1.0 0.005 ! regularisation factor, pre-sigma +threads 6 +method fullMINRES-QLP 6 2.0 +end +''' + + str_txt = par_list() + # str_txt += fdc_constraints(dict0) # should be commented out? + # str_txt += cdc_constraints() # should be commented out? + str_txt += 'Cfiles\n' + for x in mil_files_list: + str_txt += x + '\n' + str_txt += trailer + + with open('mp2str.txt', 'w') as f: + f.write(str_txt) + + +# This function changes dict0. +def add_res_to_dict(dict0): + with open('millepede.res') as f: + l0 = f.readlines() + for x in l0: + l1 = x.split() + if l1[0].startswith('Parameter'): + continue + par_id = int(l1[0]) + value = float(l1[1]) + + # par_id --> CCDB table name + if int(par_id / 100000) == 1: # FDC parameters + par_id %= 100000 + plane = int(par_id / 1000) + par_id -= plane * 1000 # 1-5, 100-104, 200-209, 997, 998 + + if par_id == 1 or par_id == 100: + table = '/FDC/cell_offsets' + row = plane - 1 + col = 0 if par_id == 1 else 1 + dict0[table][row][col] = str(float(dict0[table][row][col]) + value) + elif 2 <= par_id and par_id <= 4: + table = '/FDC/cell_rotations' + row = plane - 1 + col = par_id - 2 + dict0[table][row][col] = str(float(dict0[table][row][col]) + value) + elif par_id == 5: + table = '/FDC/wire_alignment' + row = plane - 1 + col = 2 + dict0[table][row][col] = str(float(dict0[table][row][col]) + value) + elif 101 <= par_id and par_id <= 104: + table = '/FDC/cathode_alignment' + row = plane - 1 + col = [1, 3, 0, 2][par_id - 101] + dict0[table][row][col] = str(float(dict0[table][row][col]) + value) + elif 200 <= par_id and par_id <= 209: + table = '/FDC/strip_pitches_v2' + row = plane - 1 + col = par_id - 200 + dict0[table][row][col] = str(float(dict0[table][row][col]) + value) + elif par_id == 997 or par_id == 998: + table = '/FDC/package%d/wire_timing_offsets' % (int((plane - 1) / 6) + 1) + row = (plane - 1) % 6 # cell number, 0-based + for col in [cc + (par_id - 997) * 48 for cc in range(48)]: + dict0[table][row][col] = str(float(dict0[table][row][col]) - value) + else: + print('Error: Unknown parameter', par_id) + else: # CDC parameters + if 1 <= par_id and par_id <= 6: + table = '/CDC/global_alignment' + row = 0 + col = par_id - 1 + dict0[table][row][col] = str(float(dict0[table][row][col]) + value) + elif 1001 <= par_id and par_id <= 15088: + table = '/CDC/wire_alignment' + row = int((par_id - 1001) / 4) + col = (par_id - 1) % 4 + dict0[table][row][col] = str(float(dict0[table][row][col]) + value) + else: + print('Error: Non FDC/CDC parameter', par_id) + exit(1) + + +def dict2ccdb(ccdb_path, runnum, dict0): + rand_id = '9Moh3dYvzI' + ccdb_sqlite = 'sqlite:///' + ccdb_path + for k in dict0: + tmp_file = k.strip('/').replace('/', '_') + '_%s.txt' % rand_id + with open(tmp_file, 'w') as f: + f.writelines([' '.join(x) + '\n' for x in dict0[k]]) + subprocess.call(['ccdb', '-c', ccdb_sqlite, 'add', k, '-r', '%d-%d' % (runnum, runnum), tmp_file]) + subprocess.call(['rm', tmp_file]) + + +def ccdb2dict(ccdb_path, runnum, table_list): + provider = ccdb.AlchemyProvider() + provider.connect('sqlite:///' + ccdb_path) + dict0 = {} + for x in table_list: + assignment = provider.get_assignment(x, runnum, 'default') + dict0[x] = assignment.constant_set.data_table + return dict0 + + +def par_list(): + fixCDCGlobalX = True + fixCDCGlobalY = True + fixCDCGlobalZ = True + fixCDCGlobalPhiX = True + fixCDCGlobalPhiY = True + fixCDCGlobalPhiZ = True + fixCDCWires = True + + fixFDCCathodeOffsets = True + fixFDCCathodeAngles = True + fixFDCCellOffsetsWires = True + fixFDCCellOffsetsCathodes = True + fixFDCWireRotationX = True + fixFDCWireRotationY = True + fixFDCWireRotationZ = True + fixFDCZ = True + fixFDCPitch = True + fixFDCGap = True + fixFDCT0 = False + + translationPresigma = 0.0005 + rotationPresigma = 0.0001 + pitchPresigma = 0.001 + t0Presigma = 10.0 + + l0 = ['Parameter\n'] + + # CDC + l0.append("%10d %10.4f %12.4f\n" % (1, 0.0, -1.0 if fixCDCGlobalX else translationPresigma)) + l0.append("%10d %10.4f %12.4f\n" % (2, 0.0, -1.0 if fixCDCGlobalY else translationPresigma)) + l0.append("%10d %10.4f %12.4f\n" % (3, 0.0, -1.0 if fixCDCGlobalZ else translationPresigma)) + l0.append("%10d %10.4f %12.4f\n" % (4, 0.0, -1.0 if fixCDCGlobalPhiX else rotationPresigma)) + l0.append("%10d %10.4f %12.4f\n" % (5, 0.0, -1.0 if fixCDCGlobalPhiY else rotationPresigma)) + l0.append("%10d %10.4f %12.4f\n" % (6, 0.0, -1.0 if fixCDCGlobalPhiZ else rotationPresigma)) + for i in range(1001, 15089): + l0.append("%10d %10.4f %12.4f\n" % (i, 0.0, -1.0 if fixCDCWires else translationPresigma)) + + # FDC + for i in range(1, 25): + label_offset = 100000 + i * 1000 + l0.append("%10d %10.4f %12.4f\n" % (label_offset + 1, 0.0, -1.0 if fixFDCCellOffsetsWires else translationPresigma)) + l0.append("%10d %10.4f %12.4f\n" % (label_offset + 2, 0.0, -1.0 if fixFDCWireRotationX else rotationPresigma)) + l0.append("%10d %10.4f %12.4f\n" % (label_offset + 3, 0.0, -1.0 if fixFDCWireRotationY else rotationPresigma)) + l0.append("%10d %10.4f %12.4f\n" % (label_offset + 4, 0.0, -1.0 if fixFDCWireRotationZ else rotationPresigma)) + l0.append("%10d %10.4f %12.4f\n" % (label_offset + 5, 0.0, -1.0 if fixFDCZ else translationPresigma)) + l0.append("%10d %10.4f %12.4f\n" % (label_offset + 100, 0.0, -1.0 if fixFDCCellOffsetsCathodes else translationPresigma)) + l0.append("%10d %10.4f %12.4f\n" % (label_offset + 101, 0.0, -1.0 if fixFDCCathodeOffsets else translationPresigma)) + l0.append("%10d %10.4f %12.4f\n" % (label_offset + 102, 0.0, -1.0 if fixFDCCathodeOffsets else translationPresigma)) + + # dPhiU, dPhiV + l0.append("%10d %10.4f %12.4f\n" % (label_offset + 103, 0.0, -1.0 if fixFDCCathodeAngles else rotationPresigma)) + l0.append("%10d %10.4f %12.4f\n" % (label_offset + 104, 0.0, -1.0 if fixFDCCathodeAngles else rotationPresigma)) + + # Strip pitch and gap + l0.append("%10d %10.4f %12.4f\n" % (label_offset + 200, 0.0, -1.0 if fixFDCPitch else pitchPresigma)) + l0.append("%10d %10.4f %12.4f\n" % (label_offset + 201, 0.0, -1.0 if fixFDCGap else translationPresigma)) + l0.append("%10d %10.4f %12.4f\n" % (label_offset + 202, 0.0, -1.0 if fixFDCPitch else pitchPresigma)) + l0.append("%10d %10.4f %12.4f\n" % (label_offset + 203, 0.0, -1.0 if fixFDCGap else translationPresigma)) + l0.append("%10d %10.4f %12.4f\n" % (label_offset + 204, 0.0, -1.0 if fixFDCPitch else pitchPresigma)) + l0.append("%10d %10.4f %12.4f\n" % (label_offset + 205, 0.0, -1.0 if fixFDCPitch else pitchPresigma)) + l0.append("%10d %10.4f %12.4f\n" % (label_offset + 206, 0.0, -1.0 if fixFDCGap else translationPresigma)) + l0.append("%10d %10.4f %12.4f\n" % (label_offset + 207, 0.0, -1.0 if fixFDCPitch else pitchPresigma)) + l0.append("%10d %10.4f %12.4f\n" % (label_offset + 208, 0.0, -1.0 if fixFDCGap else translationPresigma)) + l0.append("%10d %10.4f %12.4f\n" % (label_offset + 209, 0.0, -1.0 if fixFDCPitch else pitchPresigma)) + + # t0 + l0.append("%10d %10.4f %12.4f\n" % (label_offset + 997, 0.0, -1.0 if fixFDCT0 else t0Presigma)) + l0.append("%10d %10.4f %12.4f\n" % (label_offset + 998, 0.0, -1.0 if fixFDCT0 else t0Presigma)) + return (''.join(l0)) + + +def fdc_constraints(dict0): + constrainPackageZ = False + constrainPackageZTogether = False + constrainWireCathodeAlignment = False + constraint0 = False + + l0 = [] + if constrainPackageZ: + for i in range (4): + l0.append('Constraint 0.0\n') + for j in range(6): + indexOffset = 100000 + (i * 6 + j + 1) * 1000 + l0.append('%d 1.0\n' % (indexOffset + 5)) + + if constrainPackageZTogether: + for i in range(4): + for j in range(1, 6): + l0.append('Constraint 0.0\n') + indexOffset = 100000 + (i * 6 + j + 1) * 1000 + l0.append('%d 1.0 \n' % (100000 + (i * 6 + 1) * 1000 + 5)) + l0.append('%d -1.0\n' % (indexOffset + 5)) + + if constraint0: + # t0 + l0.append('Constraint 0.0\n') + for i in range(24): + indexOffset = 100000 + (i + 1) * 1000 + for j in range(901, 997): + l0.append('%d 1.0 \n' % (indexOffset + j)) + + for i in range(24): + indexOffset = 100000 + (i + 1) * 1000 + angleOffset = (i % 6) * math.pi / 3.0; + l0.append('Measurement 0.0 0.02\n') + l0.append('%d %f\n' % (indexOffset + 1, math.sin(angleOffset))) + l0.append('%d %f\n' % (indexOffset + 100, math.sin(angleOffset + math.pi / 2.0))) + l0.append('Measurement 0.0 0.02\n') + l0.append('%d %f\n' % (indexOffset + 1, math.cos(angleOffset))) + l0.append('%d %f\n' % (indexOffset + 100, math.cos(angleOffset + math.pi / 2.0))) + + # Here we need existing values to write the constraint. + if constrainWireCathodeAlignment: + for i in range(24): + # If this is true the cathode pitch is constrained such that the average + # pitch is unchanged but each of the sections can float. If this is + # false, the pitch is adjusted the same ammount for each foil. + averagePitch = True + + indexOffset = 100000 + (i + 1) * 1000 + phiu = 75.0 * math.pi / 180.0 + phiv = math.pi - phiu + + phiu += float(dict0['/FDC/cathode_alignment'][i][0]) + phiv += float(dict0['/FDC/cathode_alignment'][i][2]) + + pu1 = float(dict0['/FDC/strip_pitches_v2'][i][0]) + pu2 = float(dict0['/FDC/strip_pitches_v2'][i][2]) + pu3 = float(dict0['/FDC/strip_pitches_v2'][i][4]) + + pv1 = float(dict0['/FDC/strip_pitches_v2'][i][5]) + pv2 = float(dict0['/FDC/strip_pitches_v2'][i][7]) + pv3 = float(dict0['/FDC/strip_pitches_v2'][i][9]) + + pu = (48.0 * (pu1 + pu3) + 96.0 * pu2) / 192.0 # Average strip pitch + pv = (48.0 * (pv1 + pv3) + 96.0 * pv2) / 192.0 # Average strip pitch + + sinphiu = math.sin(phiu) + sinphiv = math.sin(phiv) + sinphiumphiv = math.sin(phiu - phiv) + cosphiumphiv = math.cos(phiu - phiv) + + if averagePitch: + # Avg = 0 + l0.append('Constraint 0.0\n') + l0.append('%d 48.0\n' % (indexOffset + 200)) + l0.append('%d 96.0\n' % (indexOffset + 202)) + l0.append('%d 48.0\n' % (indexOffset + 204)) + l0.append('Constraint 0.0\n') + l0.append('%d 48.0\n' % (indexOffset + 205)) + l0.append('%d 96.0\n' % (indexOffset + 207)) + l0.append('%d 48.0\n' % (indexOffset + 209)) + else: + # Equal + l0.append('Constraint 0.0\n') + l0.append(' 1.0\n' % (indexOffset + 200)) + l0.append('-1.0\n' % (indexOffset + 202)) + l0.append('Constraint 0.0\n') + l0.append(' 1.0\n' % (indexOffset + 200)) + l0.append('-1.0\n' % (indexOffset + 204)) + l0.append('Constraint 0.0\n') + l0.append(' 1.0\n' % (indexOffset + 205)) + l0.append('-1.0\n' % (indexOffset + 207)) + l0.append('Constraint 0.0\n') + l0.append(' 1.0\n' % (indexOffset + 205)) + l0.append('-1.0\n' % (indexOffset + 209)) + + # Constrain Wire/cathode alignmnet + l0.append('Constraint 0.0\n') + # l0.append('Measurement 0.0 0.00001\n') + l0.append('%d %f\n' % (indexOffset + 200, sinphiv)) + l0.append('%d %f\n' % (indexOffset + 205, sinphiu)) + l0.append('%d %f\n' % (indexOffset + 103, -1 * (pv + pu * cosphiumphiv) * sinphiv / sinphiumphiv)) + l0.append('%d %f\n' % (indexOffset + 104, (pu + pv * cosphiumphiv) * sinphiu / sinphiumphiv)) + l0.append('Constraint 0.0\n') + # l0.append('Measurement 0.0 0.00001\n') + l0.append('%d %f\n' % (indexOffset + 200, sinphiv)) + l0.append('%d %f\n' % (indexOffset + 205, -sinphiu)) + l0.append('%d %f\n' % (indexOffset + 103, (pv - pu * cosphiumphiv) * sinphiv / sinphiumphiv)) + l0.append('%d %f\n' % (indexOffset + 104, (pu - pv * cosphiumphiv) * sinphiu / sinphiumphiv)) + + return (''.join(l0)) + + +def cdc_constraints(): + perRing = True + + # Some CDC geometry information + # straw_offset[29] + straw_offset = [0, 0, 42, 84, 138, 192, 258, 324, 404, 484, 577, 670, 776, 882, 1005, + 1128, 1263, 1398, 1544, 1690, 1848, 2006, 2176, 2346, 2528, 2710, 2907, 3104, 3313] + # Nstraws[28], radius[28], phi[28], phi_ds[28] + Nstraws = [42, 42, 54, 54, 66, 66, 80, 80, 93, 93, 106, 106, 123, 123, + 135, 135, 146, 146, 158, 158, 170, 170, 182, 182, 197, 197, 209, 209] + radius = [10.72134, 12.08024, 13.7795, 15.14602, 18.71726, 20.2438, 22.01672, 23.50008, 25.15616, 26.61158, 28.33624, 29.77388, 31.3817, 32.75838, + 34.43478, 35.81146, 38.28542, 39.7002, 41.31564, 42.73042, 44.34078, 45.75302, 47.36084, 48.77054, 50.37582, 51.76012, 53.36286, 54.74716] + phi = [0, 0.074707844, 0.038166294, 0.096247609, 0.05966371, 0.012001551, 0.040721951, 0.001334527, 0.014963808, 0.048683644, 0.002092645, 0.031681749, 0.040719354, 0.015197341, + 0.006786058, 0.030005892, 0.019704045, -0.001782064, -0.001306618, 0.018592421, 0.003686784, 0.022132975, 0.019600866, 0.002343723, 0.021301449, 0.005348855, 0.005997358, 0.021018761] + phi_ds = [0.000557611, 0.0764693, 0.0385138, 0.0975182, -0.816345, -0.864077, -0.696401, -0.736506, 0.656304, 0.690227, 0.57023, 0.599326, 0.0410675, 0.0145592, + 0.00729358, 0.0296972, 0.43739, 0.415211, 0.38506, 0.405461, -0.355973, -0.337391, -0.317012, -0.334703, 0.0212654, 0.0058214, 0.005997358, 0.0213175] + + # Four output lists + ldxu = [] + ldxd = [] + ldyu = [] + ldyd = [] + if not perRing: + ldxu.append('Constraint 0.0\n') + ldxd.append('Constraint 0.0\n') + ldyu.append('Constraint 0.0\n') + ldyd.append('Constraint 0.0\n') + + # No shrinking or stretching of CDC + # Loop over the rings + + for iRing in range(28): + # Get angular spacing between straws + dPhi = 2 * math.pi / Nstraws[iRing] + if perRing: + ldxu.append('Constraint 0.0\n') + ldxd.append('Constraint 0.0\n') + ldyu.append('Constraint 0.0\n') + ldyd.append('Constraint 0.0\n') + + # Loop over straws + for iStraw in range(Nstraws[iRing]): + index = straw_offset[iRing + 1] + iStraw + dxu_index = 1000 + index * 4 + 1 + dyu_index = 1000 + index * 4 + 2 + dxd_index = 1000 + index * 4 + 3 + dyd_index = 1000 + index * 4 + 4 + + ConstraintXU = math.cos(phi[iRing] + dPhi * iStraw) + ConstraintXD = math.cos(phi_ds[iRing] + dPhi * iStraw) + ConstraintYU = math.sin(phi[iRing] + dPhi * iStraw) + ConstraintYD = math.sin(phi_ds[iRing] + dPhi * iStraw) + + ldxu.append('%d %lf\n' % (dxu_index, ConstraintXU)) + ldxd.append('%d %lf\n' % (dxd_index, ConstraintXD)) + ldyu.append('%d %lf\n' % (dyu_index, ConstraintYU)) + ldyd.append('%d %lf\n' % (dyd_index, ConstraintYD)) + + if not perRing: + ldxu.append('Constraint 0.0\n') + ldxd.append('Constraint 0.0\n') + ldyu.append('Constraint 0.0\n') + ldyd.append('Constraint 0.0\n') + + # No shrinking or stretching of CDC + # Loop over the rings + + for iRing in range(28): + # Get angular spacing between straws + dPhi = 2 * math.pi / Nstraws[iRing] + if perRing: + ldxu.append('Constraint 0.0\n') + ldxd.append('Constraint 0.0\n') + ldyu.append('Constraint 0.0\n') + ldyd.append('Constraint 0.0\n') + + # Loop over straws + for iStraw in range(Nstraws[iRing]): + index = straw_offset[iRing + 1] + iStraw + dxu_index = 1000 + index * 4 + 1 + dyu_index = 1000 + index * 4 + 2 + dxd_index = 1000 + index * 4 + 3 + dyd_index = 1000 + index * 4 + 4 + + ConstraintXU = math.sin(phi[iRing] + dPhi * iStraw) + ConstraintXD = math.sin(phi_ds[iRing] + dPhi * iStraw) + ConstraintYU = math.cos(phi[iRing] + dPhi * iStraw) + ConstraintYD = math.cos(phi_ds[iRing] + dPhi * iStraw) + + ldxu.append('%d %lf\n' % (dxu_index, ConstraintXU)) + ldxd.append('%d %lf\n' % (dxd_index, ConstraintXD)) + ldyu.append('%d %lf\n' % (dyu_index, ConstraintYU)) + ldyd.append('%d %lf\n' % (dyd_index, ConstraintYD)) + + ldxu.append('Constraint 0.0\n') + ldxd.append('Constraint 0.0\n') + ldyu.append('Constraint 0.0\n') + ldyd.append('Constraint 0.0\n') + + # No global shifts + for iRing in range(28): + # Get angular spacing between straws + dPhi = 2 * math.pi / Nstraws[iRing] + # Loop over straws + for iStraw in range(Nstraws[iRing]): + index = straw_offset[iRing + 1] + iStraw + dxu_index = 1000 + index * 4 + 1 + dyu_index = 1000 + index * 4 + 2 + dxd_index = 1000 + index * 4 + 3 + dyd_index = 1000 + index * 4 + 4 + + ConstraintX = 1 + ConstraintY = 1 + + ldxu.append('%d %lf\n' % (dxu_index, ConstraintX)) + ldxd.append('%d %lf\n' % (dxd_index, ConstraintX)) + ldyu.append('%d %lf\n' % (dyu_index, ConstraintY)) + ldyd.append('%d %lf\n' % (dyd_index, ConstraintY)) + + ret_str = ''.join(ldxu) + ret_str += ''.join(ldxd) + ret_str += ''.join(ldyu) + ret_str += ''.join(ldyd) + return ret_str + + +def get_par(input_par_file): + with open(input_par_file) as f: + l0 = f.readlines() + + mydict = {} + for x in l0: + if x.strip().startswith('#') or len(x.strip().split()) < 2: + continue + mydict[x.strip().split()[0]] = x.strip().split()[1] + + return mydict + + +if __name__ == '__main__': + main() diff --git a/src/plugins/Alignment/FDC_t0_alignment/runlist_example b/src/plugins/Alignment/FDC_t0_alignment/runlist_example new file mode 100644 index 0000000000..91634f0c79 --- /dev/null +++ b/src/plugins/Alignment/FDC_t0_alignment/runlist_example @@ -0,0 +1,3 @@ +120297 +120298 +120299 diff --git a/src/plugins/Alignment/FDC_t0_alignment/swif2.py b/src/plugins/Alignment/FDC_t0_alignment/swif2.py new file mode 100755 index 0000000000..aef48a7129 --- /dev/null +++ b/src/plugins/Alignment/FDC_t0_alignment/swif2.py @@ -0,0 +1,59 @@ +#! /apps/bin/python3 +# coding:utf-8 + +import sys +import os +import subprocess + + +def main(): + args = sys.argv + if len(args) != 3: + print('usage: ./swif2.py input_parameter_file run-list-file') + exit(0) + + input_par_file = os.path.abspath(args[1]) + run_list_file = args[2] + + par = get_par(input_par_file) + + swif_out_dir = par['path_to_swif2_output_dir'].rstrip('/') + '/' + script_dir = os.path.dirname(os.path.abspath(args[0])).rstrip('/') + '/' + + with open(run_list_file) as f: + run_list0 = f.readlines() + run_list = [int(x.strip()) for x in run_list0] + + work_flow = 'FDC_t0_' + run_list_file.split('/')[-1].replace('.', '_') + + + ################################# + # EXPERT ONLY (BELOW THIS LINE) # + ################################# + subprocess.call(['swif2', 'create', work_flow]) + for runnum in run_list: + call_list = ['swif2', 'add-job', '-workflow', work_flow, '-account', 'halld', '-partition', 'production'] + call_list += ['-ram', '24g', '-os', 'el9', '-cores', "24"] + call_list += ['-stdout', swif_out_dir + '%s_%06d.out' % (work_flow, runnum)] + call_list += ['-stderr', swif_out_dir + '%s_%06d.err' % (work_flow, runnum)] + call_list += [script_dir + 'mille.py %s %d' % (input_par_file, runnum)] + subprocess.call(call_list) + + subprocess.call(['swif2', 'run', work_flow]) + + +def get_par(input_par_file): + with open(input_par_file) as f: + l0 = f.readlines() + + mydict = {} + for x in l0: + if x.strip().startswith('#') or len(x.strip().split()) < 2: + continue + mydict[x.strip().split()[0]] = x.strip().split()[1] + + return mydict + + +if __name__ == '__main__': + main() diff --git a/src/plugins/Alignment/FDC_t0_alignment/update_official_ccdb.py b/src/plugins/Alignment/FDC_t0_alignment/update_official_ccdb.py new file mode 100755 index 0000000000..4c774416d8 --- /dev/null +++ b/src/plugins/Alignment/FDC_t0_alignment/update_official_ccdb.py @@ -0,0 +1,55 @@ +#! /usr/bin/python +# coding:utf-8 + +import sys +import ccdb +import subprocess + + +def main(): + # CCDB table list + table_list = [] + table_list.append('/FDC/package1/wire_timing_offsets') + table_list.append('/FDC/package2/wire_timing_offsets') + table_list.append('/FDC/package3/wire_timing_offsets') + table_list.append('/FDC/package4/wire_timing_offsets') + + args = sys.argv + if len(args) != 3: + print('usage: ./update_official_ccdb.py ccdb-sqlite-file run-list-file') + exit(0) + + ccdb_path = args[1] + run_list_file = args[2] + + with open(run_list_file) as f: + run_list = [int(x.strip()) for x in f.readlines()] + + for runnum in run_list: + dict0 = ccdb2dict(ccdb_path, runnum, table_list) + dict2ccdb(runnum, dict0) + + +def dict2ccdb(runnum, dict0): + rand_id = '9Moh3dYvzI' + ccdb_sqlite = 'mysql://ccdb_user@hallddb.jlab.org/ccdb' + for k in dict0: + tmp_file = k.strip('/').replace('/', '_') + '_%s.txt' % rand_id + with open(tmp_file, 'w') as f: + f.writelines([' '.join(x) + '\n' for x in dict0[k]]) + subprocess.call(['ccdb', '-c', ccdb_sqlite, 'add', k, '-r', '%d-%d' % (runnum, runnum), tmp_file]) + subprocess.call(['rm', tmp_file]) + + +def ccdb2dict(ccdb_path, runnum, table_list): + provider = ccdb.AlchemyProvider() + provider.connect('sqlite:///' + ccdb_path) + dict0 = {} + for x in table_list: + assignment = provider.get_assignment(x, runnum, 'default') + dict0[x] = assignment.constant_set.data_table + return dict0 + + +if __name__ == '__main__': + main() diff --git a/src/plugins/Alignment/MilleFieldOff/JEventProcessor_MilleFieldOff.cc b/src/plugins/Alignment/MilleFieldOff/JEventProcessor_MilleFieldOff.cc index 59ceb72da7..cebf2f4722 100644 --- a/src/plugins/Alignment/MilleFieldOff/JEventProcessor_MilleFieldOff.cc +++ b/src/plugins/Alignment/MilleFieldOff/JEventProcessor_MilleFieldOff.cc @@ -151,9 +151,11 @@ jerror_t JEventProcessor_MilleFieldOff::evnt(JEventLoop *loop, label_W[2] = label_layer_offset + 3; label_W[3] = label_layer_offset + 4; label_W[4] = label_layer_offset + 5; - // label_W[5] = label_layer_offset + 900 + - // pulls[iPull].fdc_hit->wire->wire; - label_W[5] = label_layer_offset + 999; + if (fdc_hit->wire->wire <= 48) { + label_W[5] = label_layer_offset + 997; + } else { + label_W[5] = label_layer_offset + 998; + } milleWriter->mille(NLC, derLc_W, NGL_W, derGl_W, label_W, resi, err); diff --git a/src/plugins/Alignment/tools/README.md b/src/plugins/Alignment/tools/README.md new file mode 100644 index 0000000000..ab74c61e62 --- /dev/null +++ b/src/plugins/Alignment/tools/README.md @@ -0,0 +1,30 @@ +How to use pede.py in this directory + + +# Preparation + +## One input file should be prepared. +See `input_example` as an example + +## Directives in input parameter file (`input_example`) +`path_to_pede` absolute path to the executable `pede`. See https://www.desy.de/~kleinwrt/MP2/doc/html/index.html to install Millepede (=`pede`). + +`path_to_input_ccdb_sqlite` absolute path to CCDB SQLite file used for the reconstruction (Mille plugin) + +`path_to_output_ccdb_sqlite` absolute path to CCDB SQLite file for output results. This can be the same as `path_to_input_ccdb_sqlite`. + +`runnum` Run Number. The CCDB table for this run number in the output CCDB file will be updated. + +`use_multiple_mil_files` Set true if you use multiple .mil files as inputs. false for a single .mil file. + +`path_to_mil` Set the path to your .mil file if you use a single .mil file as an input. In case you use multiple .mil files, set the path to the directory which contains those .mil files. Note that ALL the .mil files will be used as inputs in this case. + + +# Scripts and how to use + +## pede.py +wrapper script for `pede` command. + +.mil files are necessary as inputs for this pede.py, so use `Mille` plugin before this script. + +`./pede.py your_input_parameter_file` diff --git a/src/plugins/Alignment/tools/input_example b/src/plugins/Alignment/tools/input_example new file mode 100644 index 0000000000..cdda001e13 --- /dev/null +++ b/src/plugins/Alignment/tools/input_example @@ -0,0 +1,13 @@ +path_to_pede /path/to/your/pede +path_to_input_ccdb_sqlite /path/to/your/input/ccdb.sqlite +path_to_output_ccdb_sqlite /path/to/your/output/ccdb.sqlite + +# The CCDB table for the following run number in the ouput CCDB file will be updated. +runnum 120297 + +# Set true if you use multiple .mil files as inputs +use_multiple_mil_files false + +# Set the path to your .mil file in case you set false for use_multiple_mil_files. +# Set the path to your directory which contains .mil files in case you set true for use_multiple_files. Note that ALL the .mil files in the directory are used as inputs. +path_to_mil /path/to/your/mil_file_or_directory diff --git a/src/plugins/Alignment/tools/pede.py b/src/plugins/Alignment/tools/pede.py index 538b01e7a2..fb31ebf616 100755 --- a/src/plugins/Alignment/tools/pede.py +++ b/src/plugins/Alignment/tools/pede.py @@ -5,13 +5,31 @@ import sys import ccdb import math +import glob import subprocess def main(): - # user setting - runnum = 40856 - pede_path = '/home/keigo/work/20191126/target/pede' + args = sys.argv + if len(args) != 2: + print('usage: ./pede.py input_parameter_file') + exit(0) + + input_par_file = args[1] + + par = get_par(input_par_file) + + pede_path = par['path_to_pede'] + in_ccdb_path = par['path_to_input_ccdb_sqlite'] + out_ccdb_path = par['path_to_output_ccdb_sqlite'] + runnum = int(par['runnum']) + mil_path = par['path_to_mil'] + if par['use_multiple_mil_files'].upper().startswith('T'): + mil_list = [] + for x in glob.glob(mil_path.rstrip('/') + '/*.mil'): + mil_list.append(os.path.abspath(x)) + else: + mil_list = [mil_path] # CCDB table list table_list = [] @@ -31,33 +49,16 @@ def main(): table_list.append('/CDC/wire_alignment') table_list.append('/CDC/timing_offsets') - - args = sys.argv - if len(args) != 3: - print('usage: ./pede.py old_ver new_ver') - exit(0) - - old_ver = int(args[1]) - new_ver = int(args[2]) - old_ccdb_path = 'ccdb/ccdb_v%02d.sqlite' % old_ver - new_ccdb_path = 'ccdb/ccdb_v%02d.sqlite' % new_ver - mil_list = ['mil/fieldon_mille_out_v%02d.mil' % old_ver] - - # Copies old CCDB to a new one. - if os.path.exists(new_ccdb_path): - print('Error: file exists') - print(new_ccdb_path) - exit(0) - subprocess.call(['cp', old_ccdb_path, new_ccdb_path]) - - dict0 = ccdb2dict(new_ccdb_path, runnum, table_list) + dict0 = ccdb2dict(in_ccdb_path, runnum, table_list) # Runs pede. generate_mp2str_txt(mil_list, dict0) subprocess.call([pede_path, 'mp2str.txt']) add_res_to_dict(dict0) # Updates dict0. - dict2ccdb(new_ccdb_path, runnum, dict0) + if not os.path.exists(out_ccdb_path): + subprocess.call(['cp', in_ccdb_path, out_ccdb_path]) + dict2ccdb(out_ccdb_path, runnum, dict0) # Deletes temporary files. for x in ['millepede.res', 'millepede.end', 'millepede.end~', 'millepede.his', 'millepede.log', 'mp2str.txt']: @@ -158,7 +159,7 @@ def dict2ccdb(ccdb_path, runnum, dict0): tmp_file = k.strip('/').replace('/', '_') + '_%s.txt' % rand_id with open(tmp_file, 'w') as f: f.writelines([' '.join(x) + '\n' for x in dict0[k]]) - subprocess.call(['ccdb', '-r', '%d' % runnum, '-c', ccdb_sqlite, 'add', k, tmp_file]) + subprocess.call(['ccdb', '-c', ccdb_sqlite, 'add', k, '-r', '%d-%d' % (runnum, runnum), tmp_file]) subprocess.call(['rm', tmp_file]) @@ -181,17 +182,17 @@ def par_list(): fixCDCGlobalPhiZ = True fixCDCWires = True - fixFDCCathodeOffsets = True - fixFDCCathodeAngles = True - fixFDCCellOffsetsWires = True - fixFDCCellOffsetsCathodes = True - fixFDCWireRotationX = True - fixFDCWireRotationY = True - fixFDCWireRotationZ = True - fixFDCZ = True - fixFDCPitch = True - fixFDCGap = True - fixFDCT0 = False + fixFDCCathodeOffsets = False + fixFDCCathodeAngles = False + fixFDCCellOffsetsWires = False + fixFDCCellOffsetsCathodes = False + fixFDCWireRotationX = False + fixFDCWireRotationY = False + fixFDCWireRotationZ = False + fixFDCZ = False + fixFDCPitch = False + fixFDCGap = False + fixFDCT0 = True translationPresigma = 0.0005 rotationPresigma = 0.0001 @@ -483,5 +484,18 @@ def cdc_constraints(): return ret_str +def get_par(input_par_file): + with open(input_par_file) as f: + l0 = f.readlines() + + mydict = {} + for x in l0: + if x.strip().startswith('#') or len(x.strip().split()) < 2: + continue + mydict[x.strip().split()[0]] = x.strip().split()[1] + + return mydict + + if __name__ == '__main__': main() diff --git a/src/plugins/Analysis/ReactionEfficiency/DCustomAction_MissingMatch.cc b/src/plugins/Analysis/ReactionEfficiency/DCustomAction_MissingMatch.cc new file mode 100644 index 0000000000..ba63faa6ca --- /dev/null +++ b/src/plugins/Analysis/ReactionEfficiency/DCustomAction_MissingMatch.cc @@ -0,0 +1,164 @@ +// $Id$ +// +// File: DCustomAction_MissingMatch.cc +// Created: Wed Jun 19 17:20:17 EDT 2019 +// Creator: jrsteven (on Linux ifarm1402.jlab.org 3.10.0-327.el7.x86_64 x86_64) +// + +#include "DCustomAction_MissingMatch.h" + +void DCustomAction_MissingMatch::Initialize(JEventLoop* locEventLoop) +{ + //Optional: Create histograms and/or modify member variables. + //Create any histograms/trees/etc. within a ROOT lock. + //This is so that when running multithreaded, only one thread is writing to the ROOT file at a time. + //NEVER: Get anything from the JEventLoop while in a lock: May deadlock + + //CREATE THE HISTOGRAMS + //Since we are creating histograms, the contents of gDirectory will be modified: must use JANA-wide ROOT lock + japp->RootWriteLock(); //ACQUIRE ROOT LOCK!! + { + CreateAndChangeTo_ActionDirectory(); + + dHistMissingMatch2DTOF = GetOrCreate_Histogram("HistMissingMatch2DTOF", "HistMissingMatch2DTOF", 100, -10, 10, 100, 0.0, 100.0); + dHistMissingMatch2DBCAL = GetOrCreate_Histogram("HistMissingMatch2DBCAL", "HistMissingMatch2DBCAL", 100, -10, 10, 100, 0.0, 100.0); + + dHistMissingMatchDistTOF = GetOrCreate_Histogram("HistMissingMatchDistTOF", "HistMissingMatchDistTOF", 100, 0.0, 100.0); + dHistMissingMatchDistBCAL = GetOrCreate_Histogram("HistMissingMatchDistBCAL", "HistMissingMatchDistBCAL", 100, 0.0, 100.0); + ChangeTo_BaseDirectory(); + } + japp->RootUnLock(); //RELEASE ROOT LOCK!! + + // repeated in Run_Update() for possible CCDB updates each run(?) + const DParticleID* locParticleID = NULL; + locEventLoop->GetSingle(locParticleID); + dParticleID = locParticleID; + + DApplication* dapp=dynamic_cast(locEventLoop->GetJApplication()); + bfield = dapp->GetBfield((locEventLoop->GetJEvent()).GetRunNumber()); + rt = new DReferenceTrajectory(bfield); + + locEventLoop->GetSingle(dAnalysisUtilities); +} + +bool DCustomAction_MissingMatch::Perform_Action(JEventLoop* locEventLoop, const DParticleCombo* locParticleCombo) +{ + // distance of best match to TOF and BCAL + double locBestMissingMatchDistTOF = 999; + double locBestMissingMatchDistBCAL = 999; + + // get missing particle + vector locMissingParticles = locParticleCombo->Get_MissingParticles(Get_Reaction()); + if(locMissingParticles.empty()) return false; + + const DKinematicData *locMissing = locMissingParticles[0]; + DVector3 locMissingPosition = locMissing->position(); + DVector3 locMissingMomentum = locMissing->momentum(); + double locInputStartTime = locParticleCombo->Get_EventVertex().T(); + + rt->Reset(); + rt->Swim(locMissingPosition, locMissingMomentum, locMissing->charge()); + + /* + // try with MC track for PiPlus? + vector locMCThrowns; + locEventLoop->Get(locMCThrowns); + DVector3 locMCThrownPosition; + DVector3 locMCThrownMomentum; + double locMCThrownTime; + for(size_t loc_i=0; loc_iPID() == locMissing->PID()) { + locMCThrownPosition = locMCThrowns[loc_i]->position(); + locMCThrownMomentum = locMCThrowns[loc_i]->momentum(); + locMCThrownTime = locMCThrowns[loc_i]->time(); + break; + } + } + + locMissingPosition.Print(); + locMCThrownPosition.Print(); + locMissingMomentum.Print(); + locMCThrownMomentum.Print(); + cout<Swim(locMCThrownPosition, locMCThrownMomentum, locMissing->charge()); + */ + + // compute distance from unused BCAL showers + vector locUnusedNeutralShowers; + dAnalysisUtilities->Get_UnusedNeutralShowers(locEventLoop, locParticleCombo, locUnusedNeutralShowers); + for(size_t loc_i=0; loc_idDetectorSystem != SYS_BCAL) continue; + + const DBCALShower *locBCALShower; + locUnusedNeutralShowers[loc_i]->GetSingle(locBCALShower); + + shared_ptrlocShowerMatchParams; + DVector3 locOutputProjPos, locOutputProjMom; + if(dParticleID->Distance_ToTrack(rt, locBCALShower, locInputStartTime, locShowerMatchParams, &locOutputProjPos, &locOutputProjMom)) { + + double locDeltaT = locBCALShower->t - locShowerMatchParams->dFlightTime - locInputStartTime; + double locMissingMatchDist = locShowerMatchParams->Get_DistanceToTrack(); + dHistMissingMatch2DBCAL->Fill(locDeltaT, locMissingMatchDist); + + if(fabs(locDeltaT) > 1.0) continue; + + // keep best matched BCAL hit + if(locMissingMatchDist < locBestMissingMatchDistBCAL) + locBestMissingMatchDistBCAL = locMissingMatchDist; + } + } + + // Replace with Get_UnusedTOFPoints function to match custom DEventWriter... + + // compute distance from TOF + vector locTOFPoints; + locEventLoop->Get(locTOFPoints); + for(size_t loc_i=0; loc_iGet_ParticleComboStep(0); + auto locParticle = Get_UseKinFitResultsFlag() ? locParticleComboStep->Get_FinalParticle(dChargedIndices[loc_j]) : locParticleComboStep->Get_FinalParticle_Measured(dChargedIndices[loc_j]); + const DChargedTrack* locChargedTrack = static_cast(locParticleComboStep->Get_FinalParticle_SourceObject(dChargedIndices[loc_j])); + const DChargedTrackHypothesis* locChargedTrackHypothesis = locChargedTrack->Get_Hypothesis(locParticle->PID()); + + if(locChargedTrackHypothesis->Get_TOFHitMatchParams() == nullptr) continue; + const DTOFPoint *locUsedTOFPoint = locChargedTrackHypothesis->Get_TOFHitMatchParams()->dTOFPoint; + if(locUsedTOFPoint == locTOFPoints[loc_i]) { + locIsTOFPointUsed = true; + break; + } + } + if(locIsTOFPointUsed) continue; + + shared_ptrlocHitMatchParams; + DVector3 locOutputProjPos, locOutputProjMom; + + if(dParticleID->Distance_ToTrack(rt, locTOFPoints[loc_i], locInputStartTime, locHitMatchParams, &locOutputProjPos, &locOutputProjMom)) { + + double locDeltaT = locHitMatchParams->dHitTime - locHitMatchParams->dFlightTime - locInputStartTime; + double locMissingMatchDist = locHitMatchParams->Get_DistanceToTrack(); + dHistMissingMatch2DTOF->Fill(locDeltaT, locMissingMatchDist); + + if(fabs(locDeltaT) > 0.3) continue; + + // keep best matched TOF hit + if(locMissingMatchDist < locBestMissingMatchDistTOF) + locBestMissingMatchDistTOF = locMissingMatchDist; + } + } + + Lock_Action(); //ACQUIRE ROOT LOCK!! + { + dHistMissingMatchDistTOF->Fill(locBestMissingMatchDistTOF); + dHistMissingMatchDistBCAL->Fill(locBestMissingMatchDistBCAL); + } + Unlock_Action(); //RELEASE ROOT LOCK!! + + return true; //return false if you want to use this action to apply a cut (and it fails the cut!) +} diff --git a/src/plugins/Analysis/ReactionEfficiency/DCustomAction_MissingMatch.h b/src/plugins/Analysis/ReactionEfficiency/DCustomAction_MissingMatch.h new file mode 100644 index 0000000000..4e476c265e --- /dev/null +++ b/src/plugins/Analysis/ReactionEfficiency/DCustomAction_MissingMatch.h @@ -0,0 +1,64 @@ +// $Id$ +// +// File: DCustomAction_MissingMatch.h +// Created: Wed Jun 19 17:20:17 EDT 2019 +// Creator: jrsteven (on Linux ifarm1402.jlab.org 3.10.0-327.el7.x86_64 x86_64) +// + +#ifndef _DCustomAction_MissingMatch_ +#define _DCustomAction_MissingMatch_ + +#include +#include + +#include "JANA/JEventLoop.h" +#include "JANA/JApplication.h" + +#include "ANALYSIS/DAnalysisAction.h" +#include "ANALYSIS/DReaction.h" +#include "ANALYSIS/DParticleCombo.h" +#include "ANALYSIS/DAnalysisUtilities.h" + +using namespace std; +using namespace jana; + +class DCustomAction_MissingMatch : public DAnalysisAction +{ + public: + + DCustomAction_MissingMatch(const DReaction* locReaction, bool locUseKinFitResultsFlag, deque locChargedIndices, string locActionUniqueString = "") : + DAnalysisAction(locReaction, "Custom_MissingMatch", locUseKinFitResultsFlag, locActionUniqueString), dChargedIndices(locChargedIndices) {} + + void Initialize(JEventLoop* locEventLoop); + void Run_Update(JEventLoop* locEventLoop) { + const DParticleID* locParticleID = NULL; + locEventLoop->GetSingle(locParticleID); + dParticleID = locParticleID; + + DApplication* dapp=dynamic_cast(locEventLoop->GetJApplication()); + bfield = dapp->GetBfield((locEventLoop->GetJEvent()).GetRunNumber()); + rt = new DReferenceTrajectory(bfield); + + locEventLoop->GetSingle(dAnalysisUtilities); + } + + void Reset_NewEvent(void){}; //RESET HISTOGRAM DUPLICATE-CHECK TRACKING HERE!! + private: + + bool Perform_Action(JEventLoop* locEventLoop, const DParticleCombo* locParticleCombo); + + const DParticleID* dParticleID; + const DMagneticFieldMap *bfield; + DReferenceTrajectory *rt; + + const DAnalysisUtilities* dAnalysisUtilities; + + //Store any histograms as member variables here + deque dChargedIndices; + + TH2F *dHistMissingMatch2DTOF, *dHistMissingMatch2DBCAL; + TH1F *dHistMissingMatchDistTOF, *dHistMissingMatchDistBCAL; +}; + +#endif // _DCustomAction_MissingMatch_ + diff --git a/src/plugins/Analysis/ReactionEfficiency/DEventProcessor_ReactionEfficiency.cc b/src/plugins/Analysis/ReactionEfficiency/DEventProcessor_ReactionEfficiency.cc index b3589243e1..a2a1203fe1 100644 --- a/src/plugins/Analysis/ReactionEfficiency/DEventProcessor_ReactionEfficiency.cc +++ b/src/plugins/Analysis/ReactionEfficiency/DEventProcessor_ReactionEfficiency.cc @@ -6,6 +6,7 @@ // #include "DEventProcessor_ReactionEfficiency.h" +#include "DEventWriterROOT_ReactionEfficiency.h" // Routine used to create our DEventProcessor @@ -71,8 +72,8 @@ jerror_t DEventProcessor_ReactionEfficiency::evnt(jana::JEventLoop* locEventLoop //If no cuts are performed by the analysis actions added to a DReaction, then this saves all of its particle combinations. //The event writer gets the DAnalysisResults objects from JANA, performing the analysis. // string is DReaction factory tag: will fill trees for all DReactions that are defined in the specified factory - const DEventWriterROOT* locEventWriterROOT = NULL; - locEventLoop->GetSingle(locEventWriterROOT); + const DEventWriterROOT_ReactionEfficiency* locEventWriterROOT = NULL; + locEventLoop->GetSingle(locEventWriterROOT, "ReactionEfficiency"); locEventWriterROOT->Fill_DataTrees(locEventLoop, "ReactionEfficiency"); return NOERROR; diff --git a/src/plugins/Analysis/ReactionEfficiency/DEventWriterROOT_ReactionEfficiency.cc b/src/plugins/Analysis/ReactionEfficiency/DEventWriterROOT_ReactionEfficiency.cc new file mode 100644 index 0000000000..4d62d0bfca --- /dev/null +++ b/src/plugins/Analysis/ReactionEfficiency/DEventWriterROOT_ReactionEfficiency.cc @@ -0,0 +1,121 @@ +// $Id$ +// +// File: DEventWriterROOT_ReactionEfficiency.cc +// Created: Sat Jun 10 10:20:19 EDT 2023 +// Creator: jrsteven (on Linux ifarm1901.jlab.org 3.10.0-1160.90.1.el7.x86_64 x86_64) +// + +#include "DEventWriterROOT_ReactionEfficiency.h" + +//GLUEX TTREE DOCUMENTATION: https://halldweb.jlab.org/wiki/index.php/Analysis_TTreeFormat + +void DEventWriterROOT_ReactionEfficiency::Run_Update_Custom(JEventLoop* locEventLoop) +{ + const DParticleID* locParticleID = NULL; + locEventLoop->GetSingle(locParticleID); + dParticleID = locParticleID; + + DApplication* dapp=dynamic_cast(locEventLoop->GetJApplication()); + bfield = dapp->GetBfield((locEventLoop->GetJEvent()).GetRunNumber()); + rt = new DReferenceTrajectory(bfield); +} + +void DEventWriterROOT_ReactionEfficiency::Create_CustomBranches_DataTree(DTreeBranchRegister& locBranchRegister, JEventLoop* locEventLoop, const DReaction* locReaction, bool locIsMCDataFlag) const +{ + //EXAMPLES: Create a branch to hold an array of fundamental type: + //If filling for a specific particle, the branch name should match the particle branch name + //locArraySizeString is the name of the branch whose variable that contains the size of the array for that tree entry + //To match the default TTree branches, use either: 'NumThrown', 'NumBeam', 'NumChargedHypos', 'NumNeutralHypos', or 'NumCombos', as appropriate + unsigned int locInitArraySize = 50; //if too small, will auto-increase as needed, but requires new calls //if too large, uses more memory than needed + locBranchRegister.Register_FundamentalArray("BestMissingMatchDistTOF", "NumCombos", locInitArraySize); + locBranchRegister.Register_FundamentalArray("BestMissingMatchDistBCAL", "NumCombos", locInitArraySize); +} + +void DEventWriterROOT_ReactionEfficiency::Create_CustomBranches_ThrownTree(DTreeBranchRegister& locBranchRegister, JEventLoop* locEventLoop) const +{ + //EXAMPLES: See Create_CustomBranches_DataTree +} + +void DEventWriterROOT_ReactionEfficiency::Fill_CustomBranches_DataTree(DTreeFillData* locTreeFillData, JEventLoop* locEventLoop, const DReaction* locReaction, const DMCReaction* locMCReaction, const vector& locMCThrowns, + const DMCThrownMatching* locMCThrownMatching, const DDetectorMatches* locDetectorMatches, + const vector& locBeamPhotons, const vector& locChargedHypos, + const vector& locNeutralHypos, const deque& locParticleCombos) const +{ + //The array indices of the particles/combos in the main TTree branches match the vectors of objects passed into this function + //So if you want to add custom data for each (e.g.) charged track, the correspondence to the main arrays is 1 <--> 1 + + for(size_t loc_icombo=0; loc_icombo locMissingParticles = locParticleCombo->Get_MissingParticles(locReaction); + if(locMissingParticles.empty()) return; + + const DKinematicData *locMissing = locMissingParticles[0]; + DVector3 locMissingPosition = locMissing->position(); + DVector3 locMissingMomentum = locMissing->momentum(); + double locInputStartTime = locParticleCombo->Get_EventVertex().T(); + + rt->Reset(); + rt->Swim(locMissingPosition, locMissingMomentum, locMissing->charge()); + + // compute distance from unused BCAL showers + vector locUnusedNeutralShowers; + dAnalysisUtilities->Get_UnusedNeutralShowers(locEventLoop, locParticleCombo, locUnusedNeutralShowers); + for(size_t loc_i=0; loc_idDetectorSystem != SYS_BCAL) continue; + + const DBCALShower *locBCALShower; + locUnusedNeutralShowers[loc_i]->GetSingle(locBCALShower); + + shared_ptrlocShowerMatchParams; + DVector3 locOutputProjPos, locOutputProjMom; + if(dParticleID->Distance_ToTrack(rt, locBCALShower, locInputStartTime, locShowerMatchParams, &locOutputProjPos, &locOutputProjMom)) { + + double locDeltaT = locBCALShower->t - locShowerMatchParams->dFlightTime - locInputStartTime; + double locMissingMatchDist = locShowerMatchParams->Get_DistanceToTrack(); + + if(fabs(locDeltaT) > 1.0) continue; + + // keep best matched BCAL hit + if(locMissingMatchDist < locBestMissingMatchDistBCAL) + locBestMissingMatchDistBCAL = locMissingMatchDist; + } + } + + vector locUnusedTOFPoints; + dAnalysisUtilities->Get_UnusedTOFPoints(locEventLoop, locParticleCombo, locUnusedTOFPoints); + for(size_t loc_i=0; loc_ilocHitMatchParams; + DVector3 locOutputProjPos, locOutputProjMom; + + //////////////////////////////////////////////////////////////////////// + if(dParticleID->Distance_ToTrack(rt, locUnusedTOFPoints[loc_i], locInputStartTime, locHitMatchParams, &locOutputProjPos, &locOutputProjMom)) { + + double locDeltaT = locHitMatchParams->dHitTime - locHitMatchParams->dFlightTime - locInputStartTime; + double locMissingMatchDist = locHitMatchParams->Get_DistanceToTrack(); + + if(fabs(locDeltaT) > 0.3) continue; + + // keep best matched TOF hit + if(locMissingMatchDist < locBestMissingMatchDistTOF) + locBestMissingMatchDistTOF = locMissingMatchDist; + } + } + + locTreeFillData->Fill_Array("BestMissingMatchDistTOF", locBestMissingMatchDistTOF, loc_icombo); + locTreeFillData->Fill_Array("BestMissingMatchDistBCAL", locBestMissingMatchDistBCAL, loc_icombo); + } + +} + +void DEventWriterROOT_ReactionEfficiency::Fill_CustomBranches_ThrownTree(DTreeFillData* locTreeFillData, JEventLoop* locEventLoop, const DMCReaction* locMCReaction, const vector& locMCThrowns) const +{ + //EXAMPLES: See Fill_CustomBranches_DataTree +} + diff --git a/src/plugins/Analysis/ReactionEfficiency/DEventWriterROOT_ReactionEfficiency.h b/src/plugins/Analysis/ReactionEfficiency/DEventWriterROOT_ReactionEfficiency.h new file mode 100644 index 0000000000..3bf79f4f9e --- /dev/null +++ b/src/plugins/Analysis/ReactionEfficiency/DEventWriterROOT_ReactionEfficiency.h @@ -0,0 +1,45 @@ +// $Id$ +// +// File: DEventWriterROOT_ReactionEfficiency.h +// Created: Sat Jun 10 10:20:19 EDT 2023 +// Creator: jrsteven (on Linux ifarm1901.jlab.org 3.10.0-1160.90.1.el7.x86_64 x86_64) +// + +#ifndef _DEventWriterROOT_ReactionEfficiency_ +#define _DEventWriterROOT_ReactionEfficiency_ + +#include +#include + +#include + +using namespace std; +using namespace jana; + +class DEventWriterROOT_ReactionEfficiency : public DEventWriterROOT +{ + public: + virtual ~DEventWriterROOT_ReactionEfficiency(void){}; + void Run_Update_Custom(JEventLoop* locEventLoop); + + protected: + + //CUSTOM FUNCTIONS: //Inherit from this class and write custom code in these functions + + virtual void Create_CustomBranches_ThrownTree(DTreeBranchRegister& locBranchRegister, JEventLoop* locEventLoop) const; + virtual void Fill_CustomBranches_ThrownTree(DTreeFillData* locTreeFillData, JEventLoop* locEventLoop, const DMCReaction* locMCReaction, const vector& locMCThrowns) const; + + virtual void Create_CustomBranches_DataTree(DTreeBranchRegister& locBranchRegister, JEventLoop* locEventLoop, const DReaction* locReaction, bool locIsMCDataFlag) const; + virtual void Fill_CustomBranches_DataTree(DTreeFillData* locTreeFillData, JEventLoop* locEventLoop, const DReaction* locReaction, const DMCReaction* locMCReaction, const vector& locMCThrowns, + const DMCThrownMatching* locMCThrownMatching, const DDetectorMatches* locDetectorMatches, + const vector& locBeamPhotons, const vector& locChargedHypos, + const vector& locNeutralHypos, const deque& locParticleCombos) const; + + private: + + const DParticleID* dParticleID; + const DMagneticFieldMap *bfield; + DReferenceTrajectory *rt; +}; + +#endif //_DEventWriterROOT_ReactionEfficiency_ diff --git a/src/plugins/Analysis/ReactionEfficiency/DEventWriterROOT_factory_ReactionEfficiency.h b/src/plugins/Analysis/ReactionEfficiency/DEventWriterROOT_factory_ReactionEfficiency.h new file mode 100644 index 0000000000..329955ac10 --- /dev/null +++ b/src/plugins/Analysis/ReactionEfficiency/DEventWriterROOT_factory_ReactionEfficiency.h @@ -0,0 +1,71 @@ +// $Id$ +// +// File: DEventWriterROOT_factory_ReactionEfficiency.h +// Created: Sat Jun 10 10:20:19 EDT 2023 +// Creator: jrsteven (on Linux ifarm1901.jlab.org 3.10.0-1160.90.1.el7.x86_64 x86_64) +// + +#ifndef _DEventWriterROOT_factory_ReactionEfficiency_ +#define _DEventWriterROOT_factory_ReactionEfficiency_ + +#include +#include + +#include "DEventWriterROOT_ReactionEfficiency.h" + +class DEventWriterROOT_factory_ReactionEfficiency : public jana::JFactory +{ + public: + DEventWriterROOT_factory_ReactionEfficiency(){use_factory = 1;}; //prevents JANA from searching the input file for these objects + ~DEventWriterROOT_factory_ReactionEfficiency(){}; + const char* Tag(void){return "ReactionEfficiency";} + + DEventWriterROOT_ReactionEfficiency *dROOTEventWriter = nullptr; + + private: + + //------------------ + // brun + //------------------ + jerror_t brun(JEventLoop *loop, int32_t runnumber) + { + // (See DTAGHGeometry_factory.h) + SetFactoryFlag(NOT_OBJECT_OWNER); + ClearFactoryFlag(WRITE_TO_OUTPUT); + + if( dROOTEventWriter == nullptr ) { + dROOTEventWriter = new DEventWriterROOT_ReactionEfficiency(); + dROOTEventWriter->Initialize(loop); + dROOTEventWriter->Run_Update_Custom(loop); + } else { + dROOTEventWriter->Run_Update(loop); + dROOTEventWriter->Run_Update_Custom(loop); + } + + return NOERROR; + } + + //------------------ + // evnt + //------------------ + jerror_t evnt(JEventLoop *loop, uint64_t eventnumber) + { + // Reuse existing DBCALGeometry object. + if( dROOTEventWriter ) _data.push_back( dROOTEventWriter ); + + return NOERROR; + } + + + //------------------ + // fini + //------------------ + jerror_t fini(void) + { + // Delete object: Must be "this" thread so that interfaces deleted properly + delete dROOTEventWriter; + return NOERROR; + } +}; + +#endif // _DEventWriterROOT_factory_ReactionEfficiency_ diff --git a/src/plugins/Analysis/ReactionEfficiency/DFactoryGenerator_ReactionEfficiency.h b/src/plugins/Analysis/ReactionEfficiency/DFactoryGenerator_ReactionEfficiency.h index 67447915ad..b55c58ef53 100644 --- a/src/plugins/Analysis/ReactionEfficiency/DFactoryGenerator_ReactionEfficiency.h +++ b/src/plugins/Analysis/ReactionEfficiency/DFactoryGenerator_ReactionEfficiency.h @@ -12,6 +12,7 @@ #include #include "DReaction_factory_ReactionEfficiency.h" +#include "DEventWriterROOT_factory_ReactionEfficiency.h" class DFactoryGenerator_ReactionEfficiency : public jana::JFactoryGenerator { @@ -22,6 +23,7 @@ class DFactoryGenerator_ReactionEfficiency : public jana::JFactoryGenerator jerror_t GenerateFactories(jana::JEventLoop* locEventLoop) { locEventLoop->AddFactory(new DReaction_factory_ReactionEfficiency()); + locEventLoop->AddFactory(new DEventWriterROOT_factory_ReactionEfficiency()); return NOERROR; } }; diff --git a/src/plugins/Analysis/ReactionEfficiency/DReaction_factory_ReactionEfficiency.cc b/src/plugins/Analysis/ReactionEfficiency/DReaction_factory_ReactionEfficiency.cc index 5ecdc7180c..b54a440f3f 100644 --- a/src/plugins/Analysis/ReactionEfficiency/DReaction_factory_ReactionEfficiency.cc +++ b/src/plugins/Analysis/ReactionEfficiency/DReaction_factory_ReactionEfficiency.cc @@ -7,6 +7,44 @@ #include "DReaction_factory_ReactionEfficiency.h" +// helper function that splits string at positions of given delimiter keeping only non-empty tokens +vector +tokenizeString( + const string& s, + const char delimiter +) { + istringstream ss(s); + string token; + vector result; + while (getline(ss, token, delimiter)) { + if (token != "") { + result.push_back(token); + } + } + return result; +} + +// helper function that registers reaction depending on white list +void +DReaction_factory_ReactionEfficiency::registerReaction( + DReaction* locReaction, + const vector& locReactionsToWrite +) { + if (not locReaction) { + return; + } + if (locReactionsToWrite.empty()) { + // process all reactions + _data.push_back(locReaction); + } else { + // process only selected reactions + const string locReactionName = locReaction->Get_ReactionName(); + if (find(locReactionsToWrite.begin(), locReactionsToWrite.end(), locReactionName) != locReactionsToWrite.end()) { + _data.push_back(locReaction); + } + } +} + //------------------ // evnt //------------------ @@ -18,6 +56,10 @@ jerror_t DReaction_factory_ReactionEfficiency::evnt(JEventLoop* locEventLoop, ui double locMinKinFitFOM = 1e-4; gPARMS->SetDefaultParameter("REACTIONEFFIC:MINKINFITFOM", locMinKinFitFOM); + string locOnlyReactions = ""; // default: process all reactions + gPARMS->SetDefaultParameter("REACTIONEFFIC:ONLY_REACTIONS", locOnlyReactions); // define reactions to process as semicolon-separated list + // e.g. REACTIONEFFIC:ONLY_REACTIONS pi0pipmisspim__B1_T1_U1_Effic;pi0pimmisspip__B1_T1_U1_Effic + const vector locReactionsToWrite = tokenizeString(locOnlyReactions, ';'); // DOCUMENTATION: // ANALYSIS library: https://halldweb1.jlab.org/wiki/index.php/GlueX_Analysis_Software @@ -81,11 +123,15 @@ jerror_t DReaction_factory_ReactionEfficiency::evnt(JEventLoop* locEventLoop, ui locReaction->Add_AnalysisAction(new DCustomAction_RecoilMass(locReaction, false, locRecoilIndices, 0.2, 1.2, "OmegaRecoil")); locReaction->Add_AnalysisAction(new DCustomAction_RecoilMass(locReaction, true, locRecoilIndices, 0.2, 1.2, "OmegaRecoil_KinFit")); + // CUSTOM ACTION TO MATCH MISSING TRAJECTORY WITH FAST DETECTOR + deque locChargedIndices; locChargedIndices.clear(); + locChargedIndices.push_back(1); locChargedIndices.push_back(2); + locReaction->Add_AnalysisAction(new DCustomAction_MissingMatch(locReaction, true, locChargedIndices, "MissingMatch")); + // HISTOGRAM MASSES //false/true: measured/kinfit data locReaction->Add_AnalysisAction(new DHistogramAction_InvariantMass(locReaction, Pi0, false, 600, 0.0, 0.3, "Pi0_PostKinFit")); - _data.push_back(locReaction); //Register the DReaction with the factory - + //registerReaction(locReaction, locReactionsToWrite); //Register the DReaction with the factory /**************************************************** pi0pimmisspip__B1_T1_U1_M7_Effic ****************************************************/ @@ -115,10 +161,204 @@ jerror_t DReaction_factory_ReactionEfficiency::evnt(JEventLoop* locEventLoop, ui locReaction->Add_AnalysisAction(new DCustomAction_RecoilMass(locReaction, false, locRecoilIndices, 0.2, 1.2, "OmegaRecoil")); locReaction->Add_AnalysisAction(new DCustomAction_RecoilMass(locReaction, true, locRecoilIndices, 0.2, 1.2, "OmegaRecoil_KinFit")); + // CUSTOM ACTION TO MATCH MISSING TRAJECTORY WITH FAST DETECTOR + locChargedIndices.clear(); + locChargedIndices.push_back(1); locChargedIndices.push_back(2); + locReaction->Add_AnalysisAction(new DCustomAction_MissingMatch(locReaction, true, locChargedIndices, "MissingMatch")); + + // HISTOGRAM MASSES //false/true: measured/kinfit data + locReaction->Add_AnalysisAction(new DHistogramAction_InvariantMass(locReaction, Pi0, false, 600, 0.0, 0.3, "Pi0_PostKinFit")); + + //registerReaction(locReaction, locReactionsToWrite); //Register the DReaction with the factory + + /**************************************************** pi0pipmisspim__B1_T1_U1_Effic ****************************************************/ + + locReaction = new DReaction("pi0pipmisspim__B1_T1_U1_Effic"); + locReactionStep = new DReactionStep(Gamma, Proton, {Pi0, PiPlus, Proton}, PiMinus); + locReaction->Add_ReactionStep(locReactionStep); + dReactionStepPool.push_back(locReactionStep); //register so will be deleted later: prevent memory leak + locReactionStep = new DReactionStep(Pi0, {Gamma, Gamma}); + locReaction->Add_ReactionStep(locReactionStep); + dReactionStepPool.push_back(locReactionStep); //register so will be deleted later: prevent memory leak + + locReaction->Set_KinFitType(d_P4AndVertexFit); + locReaction->Set_NumPlusMinusRFBunches(1); // B1 + locReaction->Set_MaxExtraGoodTracks(1); // T1 + locReaction->Enable_TTreeOutput("tree_pi0pipmisspim__B1_T1_U1_Effic.root", true); // U1 = true -> true/false: do/don't save unused hypotheses + + // HISTOGRAM MASSES //false/true: measured/kinfit data + locReaction->Add_AnalysisAction(new DHistogramAction_InvariantMass(locReaction, Pi0, false, 600, 0.0, 0.3, "Pi0_PreKinFit")); + + // KINEMATIC FIT + locReaction->Add_AnalysisAction(new DHistogramAction_KinFitResults(locReaction, 0.05)); //5% confidence level cut on pull histograms only + locReaction->Add_AnalysisAction(new DCutAction_KinFitFOM(locReaction, locMinKinFitFOM)); //0% confidence level cut //require kinematic fit converges + + // CUSTOM ACTION TO REDUCE OUTPUT SIZE + locRecoilIndices.clear(); locRecoilIndices.push_back(2); + locReaction->Add_AnalysisAction(new DCustomAction_RecoilMass(locReaction, false, locRecoilIndices, 0.2, 1.2, "OmegaRecoil")); + locReaction->Add_AnalysisAction(new DCustomAction_RecoilMass(locReaction, true, locRecoilIndices, 0.2, 1.2, "OmegaRecoil_KinFit")); + + // CUSTOM ACTION TO MATCH MISSING TRAJECTORY WITH FAST DETECTOR + locChargedIndices.clear(); + locChargedIndices.push_back(1); locChargedIndices.push_back(2); + locReaction->Add_AnalysisAction(new DCustomAction_MissingMatch(locReaction, true, locChargedIndices, "MissingMatch")); + // HISTOGRAM MASSES //false/true: measured/kinfit data locReaction->Add_AnalysisAction(new DHistogramAction_InvariantMass(locReaction, Pi0, false, 600, 0.0, 0.3, "Pi0_PostKinFit")); - _data.push_back(locReaction); //Register the DReaction with the factory + registerReaction(locReaction, locReactionsToWrite); //Register the DReaction with the factory + + /**************************************************** pi0pimmisspip__B1_T1_U1_Effic ****************************************************/ + + locReaction = new DReaction("pi0pimmisspip__B1_T1_U1_Effic"); + locReactionStep = new DReactionStep(Gamma, Proton, {Pi0, PiMinus, Proton}, PiPlus); + locReaction->Add_ReactionStep(locReactionStep); + dReactionStepPool.push_back(locReactionStep); //register so will be deleted later: prevent memory leak + locReactionStep = new DReactionStep(Pi0, {Gamma, Gamma}); + locReaction->Add_ReactionStep(locReactionStep); + dReactionStepPool.push_back(locReactionStep); //register so will be deleted later: prevent memory leak + + locReaction->Set_KinFitType(d_P4AndVertexFit); + locReaction->Set_NumPlusMinusRFBunches(1); // B1 + locReaction->Set_MaxExtraGoodTracks(1); // T1 + locReaction->Enable_TTreeOutput("tree_pi0pimmisspip__B1_T1_U1_Effic.root", true); // U1 = true -> true/false: do/don't save unused hypotheses + + // HISTOGRAM MASSES //false/true: measured/kinfit data + locReaction->Add_AnalysisAction(new DHistogramAction_InvariantMass(locReaction, Pi0, false, 600, 0.0, 0.3, "Pi0_PreKinFit")); + + // KINEMATIC FIT + locReaction->Add_AnalysisAction(new DHistogramAction_KinFitResults(locReaction, 0.05)); //5% confidence level cut on pull histograms only + locReaction->Add_AnalysisAction(new DCutAction_KinFitFOM(locReaction, locMinKinFitFOM)); //0% confidence level cut //require kinematic fit converges + + // CUSTOM ACTION TO REDUCE OUTPUT SIZE + locRecoilIndices.clear(); locRecoilIndices.push_back(2); + locReaction->Add_AnalysisAction(new DCustomAction_RecoilMass(locReaction, false, locRecoilIndices, 0.2, 1.2, "OmegaRecoil")); + locReaction->Add_AnalysisAction(new DCustomAction_RecoilMass(locReaction, true, locRecoilIndices, 0.2, 1.2, "OmegaRecoil_KinFit")); + + // CUSTOM ACTION TO MATCH MISSING TRAJECTORY WITH FAST DETECTOR + locChargedIndices.clear(); + locChargedIndices.push_back(1); locChargedIndices.push_back(2); + locReaction->Add_AnalysisAction(new DCustomAction_MissingMatch(locReaction, true, locChargedIndices, "MissingMatch")); + + // HISTOGRAM MASSES //false/true: measured/kinfit data + locReaction->Add_AnalysisAction(new DHistogramAction_InvariantMass(locReaction, Pi0, false, 600, 0.0, 0.3, "Pi0_PostKinFit")); + + registerReaction(locReaction, locReactionsToWrite); //Register the DReaction with the factory + + + /**************************************************** pippimmisspi0__B1_T1_U1_M7_Effic ****************************************************/ + + locReaction = new DReaction("pippimmisspi0__B1_T1_U1_M7_Effic"); + locReactionStep = new DReactionStep(Gamma, Proton, {PiPlus, PiMinus, Proton}, Pi0); + locReaction->Add_ReactionStep(locReactionStep); + dReactionStepPool.push_back(locReactionStep); //register so will be deleted later: prevent memory leak + + locReaction->Set_KinFitType(d_P4AndVertexFit); + locReaction->Set_NumPlusMinusRFBunches(1); // B1 + locReaction->Set_MaxExtraGoodTracks(1); // T1 + locReaction->Enable_TTreeOutput("tree_pippimmisspi0__B1_T1_U1_M7_Effic.root", true); // U1 = true -> true/false: do/don't save unused hypotheses + + // KINEMATIC FIT + locReaction->Add_AnalysisAction(new DHistogramAction_KinFitResults(locReaction, 0.05)); //5% confidence level cut on pull histograms only + locReaction->Add_AnalysisAction(new DCutAction_KinFitFOM(locReaction, locMinKinFitFOM)); //0% confidence level cut //require kinematic fit converges + + // CUSTOM ACTION TO REDUCE OUTPUT SIZE + locRecoilIndices.clear(); locRecoilIndices.push_back(2); + locReaction->Add_AnalysisAction(new DCustomAction_RecoilMass(locReaction, false, locRecoilIndices, 0.2, 1.2, "OmegaRecoil")); + locReaction->Add_AnalysisAction(new DCustomAction_RecoilMass(locReaction, true, locRecoilIndices, 0.2, 1.2, "OmegaRecoil_KinFit")); + + registerReaction(locReaction, locReactionsToWrite); //Register the DReaction with the factory + + + /**************************************************** pippimpi0__B1_T1_U1_M7_Effic ****************************************************/ + // exclusive pi+ pi- pi0 w/ no pi0 mass constraint + locReaction = new DReaction("pippimpi0__B1_T1_U1_M7_Effic"); + locReactionStep = new DReactionStep(Gamma, Proton, {Pi0, PiPlus, PiMinus, Proton}); + locReaction->Add_ReactionStep(locReactionStep); + dReactionStepPool.push_back(locReactionStep); //register so will be deleted later: prevent memory leak + locReactionStep = new DReactionStep(Pi0, {Gamma, Gamma}); + locReactionStep->Set_KinFitConstrainInitMassFlag(false); + locReaction->Add_ReactionStep(locReactionStep); + dReactionStepPool.push_back(locReactionStep); //register so will be deleted later: prevent memory leak + + locReaction->Set_KinFitType(d_P4AndVertexFit); + locReaction->Set_NumPlusMinusRFBunches(1); // B1 + locReaction->Set_MaxExtraGoodTracks(1); // T1 + locReaction->Enable_TTreeOutput("tree_pippimpi0__B1_T1_U1_M7_Effic.root", true); // U1 = true -> true/false: do/don't save unused hypotheses + + // HISTOGRAM MASSES //false/true: measured/kinfit data + locReaction->Add_AnalysisAction(new DHistogramAction_InvariantMass(locReaction, Pi0, false, 600, 0.0, 0.3, "Pi0_PreKinFit")); + + // KINEMATIC FIT + locReaction->Add_AnalysisAction(new DHistogramAction_KinFitResults(locReaction, 0.05)); //5% confidence level cut on pull histograms only + locReaction->Add_AnalysisAction(new DCutAction_KinFitFOM(locReaction, locMinKinFitFOM)); //0% confidence level cut //require kinematic fit converges + + // CUSTOM ACTION TO REDUCE OUTPUT SIZE + locRecoilIndices.clear(); locRecoilIndices.push_back(3); + locReaction->Add_AnalysisAction(new DCustomAction_RecoilMass(locReaction, false, locRecoilIndices, 0.2, 1.2, "OmegaRecoil")); + locReaction->Add_AnalysisAction(new DCustomAction_RecoilMass(locReaction, true, locRecoilIndices, 0.2, 1.2, "OmegaRecoil_KinFit")); + + // HISTOGRAM MASSES //false/true: measured/kinfit data + locReaction->Add_AnalysisAction(new DHistogramAction_InvariantMass(locReaction, Pi0, false, 600, 0.0, 0.3, "Pi0_PostKinFit")); + + registerReaction(locReaction, locReactionsToWrite); //Register the DReaction with the factory + + + /**************************************************** pippimpi0__B1_T1_U1_Effic ****************************************************/ + // exclusive pi+ pi- pi0 w/ pi0 mass constraint + locReaction = new DReaction("pippimpi0__B1_T1_U1_Effic"); + locReactionStep = new DReactionStep(Gamma, Proton, {Pi0, PiPlus, PiMinus, Proton}); + locReaction->Add_ReactionStep(locReactionStep); + dReactionStepPool.push_back(locReactionStep); //register so will be deleted later: prevent memory leak + locReactionStep = new DReactionStep(Pi0, {Gamma, Gamma}); + locReactionStep->Set_KinFitConstrainInitMassFlag(true); + locReaction->Add_ReactionStep(locReactionStep); + dReactionStepPool.push_back(locReactionStep); //register so will be deleted later: prevent memory leak + + locReaction->Set_KinFitType(d_P4AndVertexFit); + locReaction->Set_NumPlusMinusRFBunches(1); // B1 + locReaction->Set_MaxExtraGoodTracks(1); // T1 + locReaction->Enable_TTreeOutput("tree_pippimpi0__B1_T1_U1_Effic.root", true); // U1 = true -> true/false: do/don't save unused hypotheses + + // HISTOGRAM MASSES //false/true: measured/kinfit data + locReaction->Add_AnalysisAction(new DHistogramAction_InvariantMass(locReaction, Pi0, false, 600, 0.0, 0.3, "Pi0_PreKinFit")); + + // KINEMATIC FIT + locReaction->Add_AnalysisAction(new DHistogramAction_KinFitResults(locReaction, 0.05)); //5% confidence level cut on pull histograms only + locReaction->Add_AnalysisAction(new DCutAction_KinFitFOM(locReaction, locMinKinFitFOM)); //0% confidence level cut //require kinematic fit converges + + // CUSTOM ACTION TO REDUCE OUTPUT SIZE + locRecoilIndices.clear(); locRecoilIndices.push_back(3); + locReaction->Add_AnalysisAction(new DCustomAction_RecoilMass(locReaction, false, locRecoilIndices, 0.2, 1.2, "OmegaRecoil")); + locReaction->Add_AnalysisAction(new DCustomAction_RecoilMass(locReaction, true, locRecoilIndices, 0.2, 1.2, "OmegaRecoil_KinFit")); + + // HISTOGRAM MASSES //false/true: measured/kinfit data + locReaction->Add_AnalysisAction(new DHistogramAction_InvariantMass(locReaction, Pi0, false, 600, 0.0, 0.3, "Pi0_PostKinFit")); + + registerReaction(locReaction, locReactionsToWrite); //Register the DReaction with the factory + + /**************************************************** pippim__B1_T1_U1_Effic ****************************************************/ + locReaction = new DReaction("pippim__B1_T1_U1_Effic"); + locReactionStep = new DReactionStep(Gamma, Proton, {PiPlus, PiMinus, Proton}); + locReaction->Add_ReactionStep(locReactionStep); + dReactionStepPool.push_back(locReactionStep); //register so will be deleted later: prevent memory leak + + locReaction->Set_KinFitType(d_P4AndVertexFit); + locReaction->Set_NumPlusMinusRFBunches(1); // B1 + locReaction->Set_MaxExtraGoodTracks(1); // T1 + locReaction->Enable_TTreeOutput("tree_pippim__B1_T1_U1_Effic.root", true); // U1 = true -> true/false: do/don't save unused hypotheses + + // KINEMATIC FIT + locReaction->Add_AnalysisAction(new DHistogramAction_KinFitResults(locReaction, 0.05)); //5% confidence level cut on pull histograms only + locReaction->Add_AnalysisAction(new DCutAction_KinFitFOM(locReaction, locMinKinFitFOM)); //0% confidence level cut //require kinematic fit converges + + // CUSTOM ACTION TO REDUCE OUTPUT SIZE + locRecoilIndices.clear(); locRecoilIndices.push_back(2); + locReaction->Add_AnalysisAction(new DCustomAction_RecoilMass(locReaction, false, locRecoilIndices, 0.2, 1.2, "OmegaRecoil")); + locReaction->Add_AnalysisAction(new DCustomAction_RecoilMass(locReaction, true, locRecoilIndices, 0.2, 1.2, "OmegaRecoil_KinFit")); + + registerReaction(locReaction, locReactionsToWrite); //Register the DReaction with the factory + /**************************************************** kpkmmissprot__B1_T1_U1_Effic ****************************************************/ @@ -141,7 +381,7 @@ jerror_t DReaction_factory_ReactionEfficiency::evnt(JEventLoop* locEventLoop, ui locReaction->Add_AnalysisAction(new DCustomAction_RecoilMass(locReaction, false, locRecoilIndices, 1.0, 2.0, "Lambda1520Recoil")); locReaction->Add_AnalysisAction(new DCustomAction_RecoilMass(locReaction, true, locRecoilIndices, 1.0, 2.0, "Lambda1520Recoil_KinFit")); - //_data.push_back(locReaction); //Register the DReaction with the factory + //registerReaction(locReaction, locReactionsToWrite); //Register the DReaction with the factory /**************************************************** kpmisskm__B1_T1_U1_Lambda1520Effic ****************************************************/ @@ -164,7 +404,7 @@ jerror_t DReaction_factory_ReactionEfficiency::evnt(JEventLoop* locEventLoop, ui locReaction->Add_AnalysisAction(new DCustomAction_RecoilMass(locReaction, false, locRecoilIndices, 1.0, 2.0, "Lambda1520Recoil")); locReaction->Add_AnalysisAction(new DCustomAction_RecoilMass(locReaction, true, locRecoilIndices, 1.0, 2.0, "Lambda1520Recoil_KinFit")); - _data.push_back(locReaction); //Register the DReaction with the factory + registerReaction(locReaction, locReactionsToWrite); //Register the DReaction with the factory /**************************************************** kpmisskm__B1_T1_U1_PhiEffic ****************************************************/ @@ -187,7 +427,7 @@ jerror_t DReaction_factory_ReactionEfficiency::evnt(JEventLoop* locEventLoop, ui locReaction->Add_AnalysisAction(new DCustomAction_RecoilMass(locReaction, false, locRecoilIndices, 0.8, 1.3, "PhiRecoil")); locReaction->Add_AnalysisAction(new DCustomAction_RecoilMass(locReaction, true, locRecoilIndices, 0.8, 1.3, "PhiRecoil_KinFit")); - _data.push_back(locReaction); //Register the DReaction with the factory + registerReaction(locReaction, locReactionsToWrite); //Register the DReaction with the factory /**************************************************** kmmisskp__B1_T1_U1_PhiEffic ****************************************************/ @@ -210,7 +450,7 @@ jerror_t DReaction_factory_ReactionEfficiency::evnt(JEventLoop* locEventLoop, ui locReaction->Add_AnalysisAction(new DCustomAction_RecoilMass(locReaction, false, locRecoilIndices, 0.8, 1.3, "PhiRecoil")); locReaction->Add_AnalysisAction(new DCustomAction_RecoilMass(locReaction, true, locRecoilIndices, 0.8, 1.3, "PhiRecoil_KinFit")); - _data.push_back(locReaction); //Register the DReaction with the factory + registerReaction(locReaction, locReactionsToWrite); //Register the DReaction with the factory /**************************************************** gpimkpmissprot__B1_T1_U1_Effic ****************************************************/ @@ -233,7 +473,7 @@ jerror_t DReaction_factory_ReactionEfficiency::evnt(JEventLoop* locEventLoop, ui locReaction->Add_AnalysisAction(new DCustomAction_RecoilMass(locReaction, false, locRecoilIndices, 0.5, 1.5, "Sigma0Recoil")); locReaction->Add_AnalysisAction(new DCustomAction_RecoilMass(locReaction, true, locRecoilIndices, 0.5, 1.5, "Sigma0Recoil_KinFit")); - _data.push_back(locReaction); //Register the DReaction with the factory + registerReaction(locReaction, locReactionsToWrite); //Register the DReaction with the factory /**************************************************** kpsigmamissprot__B1_T1_U1_Effic ****************************************************/ @@ -265,7 +505,7 @@ jerror_t DReaction_factory_ReactionEfficiency::evnt(JEventLoop* locEventLoop, ui locReaction->Add_AnalysisAction(new DCustomAction_RecoilMass(locReaction, false, locRecoilIndices, 0.5, 1.5, "Sigma0Recoil")); locReaction->Add_AnalysisAction(new DCustomAction_RecoilMass(locReaction, true, locRecoilIndices, 0.5, 1.5, "Sigma0Recoil_KinFit")); - _data.push_back(locReaction); //Register the DReaction with the factory + registerReaction(locReaction, locReactionsToWrite); //Register the DReaction with the factory /**************************************************** antilamblambmissprot__B1_T1_U1_Effic ****************************************************/ @@ -297,7 +537,7 @@ jerror_t DReaction_factory_ReactionEfficiency::evnt(JEventLoop* locEventLoop, ui locReaction->Add_AnalysisAction(new DHistogramAction_InvariantMass(locReaction, AntiLambda, false, 100, 0.8, 1.3, "AntiLambdaMass")); locReaction->Add_AnalysisAction(new DCutAction_InvariantMass(locReaction, AntiLambda, false, 0.95, 1.25, "AntiLambdaMassCut")); - _data.push_back(locReaction); //Register the DReaction with the factory + registerReaction(locReaction, locReactionsToWrite); //Register the DReaction with the factory /**************************************************** antilamblambmisspim__B1_T1_U1_Effic ****************************************************/ @@ -329,7 +569,7 @@ jerror_t DReaction_factory_ReactionEfficiency::evnt(JEventLoop* locEventLoop, ui locReaction->Add_AnalysisAction(new DHistogramAction_InvariantMass(locReaction, AntiLambda, false, 100, 0.8, 1.3, "AntiLambdaMass")); locReaction->Add_AnalysisAction(new DCutAction_InvariantMass(locReaction, AntiLambda, false, 0.95, 1.25, "AntiLambdaMassCut")); - _data.push_back(locReaction); //Register the DReaction with the factory + registerReaction(locReaction, locReactionsToWrite); //Register the DReaction with the factory /**************************************************** antilamblambmissprot__B1_T1_U1_Effic ****************************************************/ @@ -361,7 +601,7 @@ jerror_t DReaction_factory_ReactionEfficiency::evnt(JEventLoop* locEventLoop, ui locReaction->Add_AnalysisAction(new DHistogramAction_InvariantMass(locReaction, Lambda, false, 100, 0.8, 1.3, "LambdaMass")); locReaction->Add_AnalysisAction(new DCutAction_InvariantMass(locReaction, Lambda, false, 0.95, 1.25, "LambdaMassCut")); - _data.push_back(locReaction); //Register the DReaction with the factory + registerReaction(locReaction, locReactionsToWrite); //Register the DReaction with the factory /**************************************************** antilamblambmisspip__B1_T1_U1_Effic ****************************************************/ @@ -393,12 +633,12 @@ jerror_t DReaction_factory_ReactionEfficiency::evnt(JEventLoop* locEventLoop, ui locReaction->Add_AnalysisAction(new DHistogramAction_InvariantMass(locReaction, Lambda, false, 100, 0.8, 1.3, "LambdaMass")); locReaction->Add_AnalysisAction(new DCutAction_InvariantMass(locReaction, Lambda, false, 0.95, 1.25, "LambdaMassCut")); - _data.push_back(locReaction); //Register the DReaction with the factory + registerReaction(locReaction, locReactionsToWrite); //Register the DReaction with the factory - /**************************************************** pi0lambkpmiss__B1_T1_U1_Effic ****************************************************/ + /**************************************************** pi0lambmisskp__B1_T1_U1_Effic ****************************************************/ - locReaction = new DReaction("pi0lambkpmiss__B1_T1_U1_Effic"); + locReaction = new DReaction("pi0lambmisskp__B1_T1_U1_Effic"); locReactionStep = new DReactionStep(Gamma, Proton, {Pi0, PiMinus, Proton}, KPlus); locReaction->Add_ReactionStep(locReactionStep); dReactionStepPool.push_back(locReactionStep); //register so will be deleted later: prevent memory leak @@ -410,7 +650,7 @@ jerror_t DReaction_factory_ReactionEfficiency::evnt(JEventLoop* locEventLoop, ui locReaction->Set_KinFitType(d_P4AndVertexFit); locReaction->Set_NumPlusMinusRFBunches(1); // B1 locReaction->Set_MaxExtraGoodTracks(1); // T1 - locReaction->Enable_TTreeOutput("tree_pi0lambkpmiss__B1_T1_U1_Effic.root", true); // U1 = true -> true/false: do/don't save unused hypotheses + locReaction->Enable_TTreeOutput("tree_pi0lambmisskp__B1_T1_U1_Effic.root", true); // U1 = true -> true/false: do/don't save unused hypotheses // KINEMATIC FIT locReaction->Add_AnalysisAction(new DHistogramAction_KinFitResults(locReaction, 0.05)); //5% confidence level cut on pull histograms only @@ -426,12 +666,12 @@ jerror_t DReaction_factory_ReactionEfficiency::evnt(JEventLoop* locEventLoop, ui locReaction->Add_AnalysisAction(new DHistogramAction_InvariantMass(locReaction, 0, locLambdaIndices, false, 100, 0.8, 1.3, "LambdaMass")); locReaction->Add_AnalysisAction(new DCutAction_InvariantMass(locReaction, 0, locLambdaIndices, false, 0.95, 1.25, "LambdaMassCut")); - _data.push_back(locReaction); //Register the DReaction with the factory + registerReaction(locReaction, locReactionsToWrite); //Register the DReaction with the factory - /**************************************************** pi0lambpmiss__B1_T1_U1_Effic ****************************************************/ + /**************************************************** pi0kplambmissprot__B1_T1_U1_Effic ****************************************************/ - locReaction = new DReaction("pi0lambpmiss__B1_T1_U1_Effic"); + locReaction = new DReaction("pi0kplambmissprot__B1_T1_U1_Effic"); locReactionStep = new DReactionStep(Gamma, Proton, {Pi0, PiMinus, KPlus}, Proton); locReaction->Add_ReactionStep(locReactionStep); dReactionStepPool.push_back(locReactionStep); //register so will be deleted later: prevent memory leak @@ -443,7 +683,7 @@ jerror_t DReaction_factory_ReactionEfficiency::evnt(JEventLoop* locEventLoop, ui locReaction->Set_KinFitType(d_P4AndVertexFit); locReaction->Set_NumPlusMinusRFBunches(1); // B1 locReaction->Set_MaxExtraGoodTracks(1); // T1 - locReaction->Enable_TTreeOutput("tree_pi0lambpmiss__B1_T1_U1_Effic.root", true); // U1 = true -> true/false: do/don't save unused hypotheses + locReaction->Enable_TTreeOutput("tree_pi0kplambmissprot__B1_T1_U1_Effic.root", true); // U1 = true -> true/false: do/don't save unused hypotheses // KINEMATIC FIT locReaction->Add_AnalysisAction(new DHistogramAction_KinFitResults(locReaction, 0.05)); //5% confidence level cut on pull histograms only @@ -453,12 +693,12 @@ jerror_t DReaction_factory_ReactionEfficiency::evnt(JEventLoop* locEventLoop, ui locRecoilIndices.clear(); locRecoilIndices.push_back(0); locRecoilIndices.push_back(2); // K* = Pi0+KPlus locReaction->Add_AnalysisAction(new DCustomAction_RecoilMass(locReaction, true, locRecoilIndices, 0.9, 1.3, "LambdaRecoil_KinFit")); - _data.push_back(locReaction); //Register the DReaction with the factory + registerReaction(locReaction, locReactionsToWrite); //Register the DReaction with the factory - /**************************************************** pi0lambpimmiss__B1_T1_U1_Effic ****************************************************/ + /**************************************************** pi0kplambmisspim__B1_T1_U1_Effic ****************************************************/ - locReaction = new DReaction("pi0lambpimmiss__B1_T1_U1_Effic"); + locReaction = new DReaction("pi0kplambmisspim__B1_T1_U1_Effic"); locReactionStep = new DReactionStep(Gamma, Proton, {Pi0, KPlus, Proton}, PiMinus); locReaction->Add_ReactionStep(locReactionStep); dReactionStepPool.push_back(locReactionStep); //register so will be deleted later: prevent memory leak @@ -470,7 +710,7 @@ jerror_t DReaction_factory_ReactionEfficiency::evnt(JEventLoop* locEventLoop, ui locReaction->Set_KinFitType(d_P4AndVertexFit); locReaction->Set_NumPlusMinusRFBunches(1); // B1 locReaction->Set_MaxExtraGoodTracks(1); // T1 - locReaction->Enable_TTreeOutput("tree_pi0lambpimmiss__B1_T1_U1_Effic.root", true); // U1 = true -> true/false: do/don't save unused hypotheses + locReaction->Enable_TTreeOutput("tree_pi0kplambmisspim__B1_T1_U1_Effic.root", true); // U1 = true -> true/false: do/don't save unused hypotheses // KINEMATIC FIT locReaction->Add_AnalysisAction(new DHistogramAction_KinFitResults(locReaction, 0.05)); //5% confidence level cut on pull histograms only @@ -480,7 +720,108 @@ jerror_t DReaction_factory_ReactionEfficiency::evnt(JEventLoop* locEventLoop, ui locRecoilIndices.clear(); locRecoilIndices.push_back(0); locRecoilIndices.push_back(2); // K* = Pi0+KPlus locReaction->Add_AnalysisAction(new DCustomAction_RecoilMass(locReaction, true, locRecoilIndices, 0.9, 1.3, "LambdaRecoil_KinFit")); - _data.push_back(locReaction); //Register the DReaction with the factory + registerReaction(locReaction, locReactionsToWrite); //Register the DReaction with the factory + + + /**************************************************** pippippimpimmissprot__B1_T1_U1_Effic ****************************************************/ + + locReaction = new DReaction("pippippimpimmissprot__B1_T1_U1_Effic"); + locReactionStep = new DReactionStep(Gamma, Proton, {PiPlus, PiPlus, PiMinus, PiMinus}, Proton); + locReaction->Add_ReactionStep(locReactionStep); + dReactionStepPool.push_back(locReactionStep); //register so will be deleted later: prevent memory leak + + locReaction->Set_KinFitType(d_P4AndVertexFit); + locReaction->Set_NumPlusMinusRFBunches(1); // B1 + locReaction->Set_MaxExtraGoodTracks(1); // T1 + locReaction->Enable_TTreeOutput("tree_pippippimpimmissprot__B1_T1_U1_Effic.root", true); // U1 = true -> true/false: do/don't save unused hypotheses + + // KINEMATIC FIT + locReaction->Add_AnalysisAction(new DHistogramAction_KinFitResults(locReaction, 0.05)); //5% confidence level cut on pull histograms only + locReaction->Add_AnalysisAction(new DCutAction_KinFitFOM(locReaction, locMinKinFitFOM)); //0% confidence level cut //require kinematic fit converges + + // MISSING MASS SQUARED + locReaction->Add_AnalysisAction(new DHistogramAction_MissingMassSquared(locReaction, false, 100, -1.0, 4.5, "MM2")); + + registerReaction(locReaction, locReactionsToWrite); //Register the DReaction with the factory + + + /**************************************************** omegamisspim__B1_T1_U1_Effic ****************************************************/ + + locReaction = new DReaction("omegamisspim__B1_T1_U1_Effic"); + locReactionStep = new DReactionStep(Gamma, Proton, {omega, Pi0, Proton}); + locReaction->Add_ReactionStep(locReactionStep); + dReactionStepPool.push_back(locReactionStep); //register so will be deleted later: prevent memory leak + + locReactionStep = new DReactionStep(omega, {Pi0, PiPlus}, PiMinus); + locReaction->Add_ReactionStep(locReactionStep); + dReactionStepPool.push_back(locReactionStep); //register so will be deleted later: prevent memory leak + locReactionStep = new DReactionStep(Pi0, {Gamma, Gamma}); + locReaction->Add_ReactionStep(locReactionStep); + dReactionStepPool.push_back(locReactionStep); //register so will be deleted later: prevent memory leak + locReactionStep = new DReactionStep(Pi0, {Gamma, Gamma}); + locReaction->Add_ReactionStep(locReactionStep); + dReactionStepPool.push_back(locReactionStep); //register so will be deleted later: prevent memory leak + + locReaction->Set_KinFitType(d_P4AndVertexFit); + locReaction->Set_NumPlusMinusRFBunches(1); // B1 + locReaction->Set_MaxExtraGoodTracks(1); // T1 + locReaction->Enable_TTreeOutput("tree_omegapi0misspim__B1_T1_U1_Effic.root", true); // U1 = true -> true/false: do/don't save unused hypotheses + + // HISTOGRAM MASSES //false/true: measured/kinfit data + locReaction->Add_AnalysisAction(new DHistogramAction_InvariantMass(locReaction, Pi0, false, 600, 0.0, 0.3, "Pi0_PreKinFit")); + + // KINEMATIC FIT + locReaction->Add_AnalysisAction(new DHistogramAction_KinFitResults(locReaction, 0.05)); //5% confidence level cut on pull histograms only + locReaction->Add_AnalysisAction(new DCutAction_KinFitFOM(locReaction, locMinKinFitFOM)); //0% confidence level cut //require kinematic fit converges + + // CUSTOM ACTION TO REDUCE OUTPUT SIZE + locRecoilIndices.clear(); locRecoilIndices.push_back(2); + locReaction->Add_AnalysisAction(new DCustomAction_RecoilMass(locReaction, false, locRecoilIndices, 0.8, 1.6, "b1Recoil")); + locReaction->Add_AnalysisAction(new DCustomAction_RecoilMass(locReaction, true, locRecoilIndices, 0.8, 1.6, "b1Recoil_KinFit")); + + // HISTOGRAM MASSES //false/true: measured/kinfit data + locReaction->Add_AnalysisAction(new DHistogramAction_InvariantMass(locReaction, Pi0, false, 600, 0.0, 0.3, "Pi0_PostKinFit")); + + registerReaction(locReaction, locReactionsToWrite); //Register the DReaction with the factory + + /**************************************************** omegapi0misspip__B1_T1_U1_Effic ****************************************************/ + + locReaction = new DReaction("omegapi0misspip__B1_T1_U1_Effic"); + locReactionStep = new DReactionStep(Gamma, Proton, {omega, Pi0, Proton}); + locReaction->Add_ReactionStep(locReactionStep); + dReactionStepPool.push_back(locReactionStep); //register so will be deleted later: prevent memory leak + + locReactionStep = new DReactionStep(omega, {Pi0, PiMinus}, PiPlus); + locReaction->Add_ReactionStep(locReactionStep); + dReactionStepPool.push_back(locReactionStep); //register so will be deleted later: prevent memory leak + locReactionStep = new DReactionStep(Pi0, {Gamma, Gamma}); + locReaction->Add_ReactionStep(locReactionStep); + dReactionStepPool.push_back(locReactionStep); //register so will be deleted later: prevent memory leak + locReactionStep = new DReactionStep(Pi0, {Gamma, Gamma}); + locReaction->Add_ReactionStep(locReactionStep); + dReactionStepPool.push_back(locReactionStep); //register so will be deleted later: prevent memory leak + + locReaction->Set_KinFitType(d_P4AndVertexFit); + locReaction->Set_NumPlusMinusRFBunches(1); // B1 + locReaction->Set_MaxExtraGoodTracks(1); // T1 + locReaction->Enable_TTreeOutput("tree_omegapi0misspip__B1_T1_U1_Effic.root", true); // U1 = true -> true/false: do/don't save unused hypotheses + + // HISTOGRAM MASSES //false/true: measured/kinfit data + locReaction->Add_AnalysisAction(new DHistogramAction_InvariantMass(locReaction, Pi0, false, 600, 0.0, 0.3, "Pi0_PreKinFit")); + + // KINEMATIC FIT + locReaction->Add_AnalysisAction(new DHistogramAction_KinFitResults(locReaction, 0.05)); //5% confidence level cut on pull histograms only + locReaction->Add_AnalysisAction(new DCutAction_KinFitFOM(locReaction, locMinKinFitFOM)); //0% confidence level cut //require kinematic fit converges + + // CUSTOM ACTION TO REDUCE OUTPUT SIZE + locRecoilIndices.clear(); locRecoilIndices.push_back(2); + locReaction->Add_AnalysisAction(new DCustomAction_RecoilMass(locReaction, false, locRecoilIndices, 0.8, 1.6, "b1Recoil")); + locReaction->Add_AnalysisAction(new DCustomAction_RecoilMass(locReaction, true, locRecoilIndices, 0.8, 1.6, "b1Recoil_KinFit")); + + // HISTOGRAM MASSES //false/true: measured/kinfit data + locReaction->Add_AnalysisAction(new DHistogramAction_InvariantMass(locReaction, Pi0, false, 600, 0.0, 0.3, "Pi0_PostKinFit")); + + registerReaction(locReaction, locReactionsToWrite); //Register the DReaction with the factory return NOERROR; } diff --git a/src/plugins/Analysis/ReactionEfficiency/DReaction_factory_ReactionEfficiency.h b/src/plugins/Analysis/ReactionEfficiency/DReaction_factory_ReactionEfficiency.h index 5883638fe2..39e206f0ef 100644 --- a/src/plugins/Analysis/ReactionEfficiency/DReaction_factory_ReactionEfficiency.h +++ b/src/plugins/Analysis/ReactionEfficiency/DReaction_factory_ReactionEfficiency.h @@ -17,6 +17,7 @@ #include #include "DCustomAction_RecoilMass.h" +#include "DCustomAction_MissingMatch.h" using namespace std; using namespace jana; @@ -32,6 +33,7 @@ class DReaction_factory_ReactionEfficiency : public jana::JFactory const char* Tag(void){return "ReactionEfficiency";} private: + void registerReaction(DReaction* locReaction, const vector& locReactionsToWrite); jerror_t evnt(JEventLoop* locEventLoop, uint64_t locEventNumber); jerror_t fini(void); ///< Called after last event of last event source has been processed. diff --git a/src/plugins/Analysis/ReactionFilter/DReaction_factory_ReactionFilter.cc b/src/plugins/Analysis/ReactionFilter/DReaction_factory_ReactionFilter.cc index e177a7c9fc..b0d0fa704d 100644 --- a/src/plugins/Analysis/ReactionFilter/DReaction_factory_ReactionFilter.cc +++ b/src/plugins/Analysis/ReactionFilter/DReaction_factory_ReactionFilter.cc @@ -84,6 +84,8 @@ DReactionStep* DReaction_factory_ReactionFilter::Create_DefaultDecayStep(Particl return (new DReactionStep(OmegaMinus, {KMinus, Lambda})); else if(locPID == Lambda_c) return (new DReactionStep(Lambda_c, {PiPlus, KMinus, Proton})); + else if(locPID == Sigma_cPlusPlus) + return (new DReactionStep(Sigma_cPlusPlus, {PiPlus, Lambda_c})); return nullptr; } @@ -226,6 +228,7 @@ jerror_t DReaction_factory_ReactionFilter::evnt(JEventLoop* locEventLoop, uint64 // KINEMATICS & OTHER INFO locReaction->Add_AnalysisAction(new DHistogramAction_ParticleComboKinematics(locReaction, true)); + locReaction->Add_AnalysisAction(new DHistogramAction_TriggerStudies(locReaction, "", 0.05)); _data.push_back(locReaction); //Register the DReaction with the factory } diff --git a/src/plugins/Calibration/BCAL_ADC_4ns/JEventProcessor_BCAL_ADC_4ns.cc b/src/plugins/Calibration/BCAL_ADC_4ns/JEventProcessor_BCAL_ADC_4ns.cc index 34005bcde0..351d468e04 100644 --- a/src/plugins/Calibration/BCAL_ADC_4ns/JEventProcessor_BCAL_ADC_4ns.cc +++ b/src/plugins/Calibration/BCAL_ADC_4ns/JEventProcessor_BCAL_ADC_4ns.cc @@ -10,7 +10,6 @@ *************************************/ #include "JEventProcessor_BCAL_ADC_4ns.h" -#include "HistogramTools.h" #include "BCAL/DBCALHit.h" #include "BCAL/DBCALTDCHit.h" #include "BCAL/DBCALCluster.h" @@ -63,6 +62,27 @@ JEventProcessor_BCAL_ADC_4ns::~JEventProcessor_BCAL_ADC_4ns() jerror_t JEventProcessor_BCAL_ADC_4ns::init(void) { // This is called once at program startup. + char channame[50], histtitle[255]; + + float zminhall = 0; + float zmaxhall = 450; + + // create root folder and cd to it, store main dir + TDirectory *main = gDirectory; // save current directory + TDirectory *adchistdir = main->mkdir("BCAL_ADC_Deltat")->mkdir("ZvsDeltat"); + adchistdir->cd(); + + for (int module=0; modulecd(); return NOERROR; } @@ -116,16 +136,18 @@ jerror_t JEventProcessor_BCAL_ADC_4ns::evnt(JEventLoop *loop, uint64_t eventnumb } if (bestHypothesis == NULL) continue; // Now from this hypothesis we can get the detector matches to the BCAL - const DBCALShowerMatchParams* bcalMatch = bestHypothesis->Get_BCALShowerMatchParams(); + //const DBCALShowerMatchParams* bcalMatch = bestHypothesis->Get_BCALShowerMatchParams(); + auto bcalMatch = bestHypothesis->Get_BCALShowerMatchParams(); if (bcalMatch == NULL) continue; - const DSCHitMatchParams* scMatch = bestHypothesis->Get_SCHitMatchParams(); + // const DSCHitMatchParams* scMatch = bestHypothesis->Get_SCHitMatchParams(); + auto scMatch = bestHypothesis->Get_SCHitMatchParams(); if (scMatch == NULL) continue; DVector3 position = bestHypothesis->position(); // We also need the reference trajectory, which is buried deep in there const DTrackTimeBased *timeBasedTrack = nullptr; bestHypothesis->GetSingle(timeBasedTrack); - const DReferenceTrajectory *rt = timeBasedTrack->rt; + const DReferenceTrajectory *rt = timeBasedTrack->rt; // TOFIX: this is deprecated if (timeBasedTrack->FOM < 0.0027) continue; // 3-sigma cut on tracking FOM if (timeBasedTrack->Ndof < 10) continue; // CDC: 5 params in fit, 10 dof => [15 hits]; FDC [10 hits] @@ -152,8 +174,6 @@ jerror_t JEventProcessor_BCAL_ADC_4ns::evnt(JEventLoop *loop, uint64_t eventnumb float zmaxhall = 450; if (rt->GetIntersectionWithRadius(rpoint,proj_pos, &pathLength, &flightTime)==NOERROR){ // Now proj_pos contains the projected position of the track at this particular point within the BCAL - char channame[255]; - sprintf(channame, "M%02iL%iS%i", thisPoint->module(), thisPoint->layer(), thisPoint->sector()); double trackHitZ = proj_pos.z(); vector hitVector; @@ -163,9 +183,7 @@ jerror_t JEventProcessor_BCAL_ADC_4ns::evnt(JEventLoop *loop, uint64_t eventnumb double Deltat = hitVector[0]->t_raw - hitVector[1]->t_raw; if (hitVector[0]->end==1) Deltat = -Deltat; - sprintf(title, "%s Z_{Track} vs #Delta t;#Delta t = t_{US}-t_{DS};Z_{Track} [cm]", channame); - Fill2DHistogram ("BCAL_ADC_Deltat", "ZvsDeltat", channame, Deltat, trackHitZ, title, - 480, -30, 30, 250, zminhall, zmaxhall); + hZvsDeltat[thisPoint->module()][thisPoint->layer()][thisPoint->sector()]->Fill(Deltat, trackHitZ); } } } diff --git a/src/plugins/Calibration/BCAL_ADC_4ns/JEventProcessor_BCAL_ADC_4ns.h b/src/plugins/Calibration/BCAL_ADC_4ns/JEventProcessor_BCAL_ADC_4ns.h index 7bcd70abed..35d9cd8999 100644 --- a/src/plugins/Calibration/BCAL_ADC_4ns/JEventProcessor_BCAL_ADC_4ns.h +++ b/src/plugins/Calibration/BCAL_ADC_4ns/JEventProcessor_BCAL_ADC_4ns.h @@ -10,18 +10,28 @@ #include +#include + class JEventProcessor_BCAL_ADC_4ns:public jana::JEventProcessor{ public: JEventProcessor_BCAL_ADC_4ns(); ~JEventProcessor_BCAL_ADC_4ns(); const char* className(void){return "JEventProcessor_BCAL_ADC_4ns";} + static const int nummodule=48; + static const int numlayer=4; + static const int numsector=4; + + private: jerror_t init(void); ///< Called once at program start. jerror_t brun(jana::JEventLoop *eventLoop, int32_t runnumber); ///< Called everytime a new run number is detected. jerror_t evnt(jana::JEventLoop *eventLoop, uint64_t eventnumber); ///< Called every event. jerror_t erun(void); ///< Called everytime run number changes, provided brun has been called. jerror_t fini(void); ///< Called after last event of last event source has been processed. + + TH2F *hZvsDeltat[JEventProcessor_BCAL_ADC_4ns::nummodule][JEventProcessor_BCAL_ADC_4ns::numlayer][JEventProcessor_BCAL_ADC_4ns::numsector]; + }; #endif // _JEventProcessor_BCAL_ADC_4ns_ diff --git a/src/plugins/Calibration/BCAL_SiPM_saturation/JEventProcessor_BCAL_SiPM_saturation.cc b/src/plugins/Calibration/BCAL_SiPM_saturation/JEventProcessor_BCAL_SiPM_saturation.cc index d5f86c86b4..c290fc899c 100644 --- a/src/plugins/Calibration/BCAL_SiPM_saturation/JEventProcessor_BCAL_SiPM_saturation.cc +++ b/src/plugins/Calibration/BCAL_SiPM_saturation/JEventProcessor_BCAL_SiPM_saturation.cc @@ -63,7 +63,55 @@ JEventProcessor_BCAL_SiPM_saturation::~JEventProcessor_BCAL_SiPM_saturation() //------------------ jerror_t JEventProcessor_BCAL_SiPM_saturation::init(void) { + Int_t nbins=100; + + // This is called once at program startup. + gDirectory->mkdir("BCAL_SiPM_saturation"); + gDirectory->cd("BCAL_SiPM_saturation"); + + gDirectory->mkdir("Hists1D"); + gDirectory->cd("Hists1D"); + + dHistEthrown = new TH1F("Ethrown", "BCAL SiPM Saturation; Thrown Energy (GeV)",4*nbins,0,10); + dHistEshower = new TH1F("Eshower", "BCAL SiPM Saturation; Shower Energy (GeV)",10*nbins,0,10); + dHistThrownTheta = new TH1F("Thrown Theta", "BCAL SiPM Saturation; Thrown Theta (degrees)",4*90,0,90); + dHistNCell = new TH1F("NCell", "BCAL SiPM Saturation; Number of cells",nbins,0,100 ); + dHistLayer = new TH1F("layer", "BCAL SiPM Saturation; Layer Number",5,0,5); + dHistEpoint = new TH1F("Ept", "BCAL SiPM Saturation; Point Energy (GeV)",10*nbins,0,10); + + + nbins=5100; + + dHistPeakLayer1 = new TH1F("Hit pulse_peak layer=1", "BCAL SiPM Saturation; Hit Pulse_peak (counts)",nbins,-100,5000); + dHistIntegralLayer1 = new TH1F("Hit integral layer=1", "BCAL SiPM Saturation; Hit integral (GeV)",nbins,0, 10); + dHistPeakLayer2 = new TH1F("Hit pulse_peak layer=2", "BCAL SiPM Saturation; Hit Pulse_peak (counts)",nbins,-100,5000); + dHistIntegralLayer2 = new TH1F("Hit integral layer=2", "BCAL SiPM Saturation; Hit integral (GeV)",nbins,0, 10); + dHistPeakLayer3 = new TH1F("Hit pulse_peak layer=3", "BCAL SiPM Saturation; Hit Pulse_peak (counts)",nbins,-100,5000); + dHistIntegralLayer3 = new TH1F("Hit integral layer=3", "BCAL SiPM Saturation; Hit integral (GeV)",nbins,0, 10); + dHistPeakLayer4 = new TH1F("Hit pulse_peak layer=4", "BCAL SiPM Saturation; Hit Pulse_peak (counts)",nbins,-100,5000); + dHistIntegralLayer4 = new TH1F("Hit integral layer=4", "BCAL SiPM Saturation; Hit integral (GeV)",nbins,0, 10); + dHistEcalc = new TH1F("Ecalc", "BCAL SiPM Saturation; Calc Energy (GeV)",4*nbins,0,10); + dHistEcalcEpt = new TH1F("Ecalc-Ept", "BCAL SiPM Saturation; Calc-Pt Energy (GeV)",nbins,-0.05,0.05); + + gDirectory->cd(".."); + + gDirectory->mkdir("Hists2D"); + gDirectory->cd("Hists2D"); + + nbins=100; + + dHistEshowerVsEthrown = new TH2F("Eshower_vs_Ethrown", "BCAL SiPM Saturation; Thrown Energy (GeV); Shower Energy (GeV)", + 4*nbins,0,10,4*nbins,0,10); + dHistEdiffVsEthrown = new TH2F("EDiff_vs_Ethrown", "BCAL SiPM Saturation; Thrown Energy (GeV); (Shower - Thrown) Energy (GeV)", + 4*nbins,0,10,nbins,-0.5,0.5); + dHistEdiffFracVsEthrown = new TH2F("EDiff/Ethrown_vs_Ethrown", "BCAL SiPM Saturation; Thrown Energy (GeV); (EShower - EThrown)/Ethrown", + 4*nbins,0,10,nbins,-0.2,0.2); + + gDirectory->cd(".."); + + gDirectory->cd(".."); + return NOERROR; } @@ -140,15 +188,15 @@ jerror_t JEventProcessor_BCAL_SiPM_saturation::evnt(JEventLoop *loop, uint64_t e if (locDetector != SYS_BCAL) continue; // Get shower properties vector BCALShowers; - locNeutralShower->Get(BCALShowers); + locNeutralShower->Get(BCALShowers); - // Should be only one BCAL shower for each neutral shower - const DBCALShower* locBCALShower= BCALShowers[0]; - Eshower = locBCALShower->E; + // Should be only one BCAL shower for each neutral shower + const DBCALShower* locBCALShower= BCALShowers[0]; + Eshower = locBCALShower->E; - // for MC select showers that are greater than 50% of thrown energy - if (NumThrown == 1 && Eshower < Ethrown/2.) - continue; + // for MC select showers that are greater than 50% of thrown energy + if (NumThrown == 1 && Eshower < Ethrown/2.) + continue; /*float E_preshower = locBCALShower->E_preshower; float z = locBCALShower->z; @@ -161,89 +209,82 @@ jerror_t JEventProcessor_BCAL_SiPM_saturation::evnt(JEventLoop *loop, uint64_t e // cout << " Shower i=" << i << " E_shower=" << Eshower << " E_preshower=" << E_preshower << " x=" << x << " y=" << y << " z=" << z << " R=" << R << " sigLong=" << sigLong << " sigTrans=" << sigTrans << " sigTheta=" << sigTheta << endl; - Int_t nbins=100; - - // Fill histogram for showers - Fill1DHistogram ("BCAL_SiPM_saturation", "Hists1D", "Ethrown", Ethrown, - "BCAL SiPM Saturation; Thrown Energy (GeV)",4*nbins,0,10); + // Get vector of points in this shower + // load these earlier to collect the histogram fill calls below + vector Points; + locNeutralShower->Get(Points); + uint Ncell = Points.size(); + + japp->RootWriteLock(); //ACQUIRE ROOT LOCK!! - Fill1DHistogram ("BCAL_SiPM_saturation", "Hists1D", "Eshower", Eshower, - "BCAL SiPM Saturation; Shower Energy (GeV)",10*nbins,0,10); - Fill1DHistogram ("BCAL_SiPM_saturation", "Hists1D", "Thrown Theta", thetathrown, - "BCAL SiPM Saturation; Thrown Theta (degrees)",4*90,0,90); + // Fill histogram for showers + dHistEthrown->Fill(Ethrown); + dHistEshower->Fill(Eshower); + dHistThrownTheta->Fill(thetathrown); // Fill 2D histograms - Fill2DHistogram ("BCAL_SiPM_saturation", "Hists2D", "Eshower_vs_Ethrown", Ethrown, Eshower, - "BCAL SiPM Saturation; Thrown Energy (GeV); Shower Energy (GeV)", - 4*nbins,0,10,4*nbins,0,10); - Fill2DHistogram ("BCAL_SiPM_saturation", "Hists2D", "EDiff_vs_Ethrown", Ethrown, Eshower - Ethrown, - "BCAL SiPM Saturation; Thrown Energy (GeV); (Shower - Thrown) Energy (GeV)", - 4*nbins,0,10,nbins,-0.5,0.5); - Fill2DHistogram ("BCAL_SiPM_saturation", "Hists2D", "EDiff/Ethrown_vs_Ethrown", Ethrown, Ethrown>0? (Eshower - Ethrown)/Ethrown : 0, - "BCAL SiPM Saturation; Thrown Energy (GeV); (EShower - EThrown)/Ethrown", - 4*nbins,0,10,nbins,-0.2,0.2); + dHistEshowerVsEthrown->Fill(Ethrown, Eshower); + dHistEdiffVsEthrown->Fill(Ethrown, Eshower - Ethrown); + dHistEdiffFracVsEthrown->Fill(Ethrown, Ethrown>0? (Eshower - Ethrown)/Ethrown : 0); - // Get vector of points in this shower - vector Points; - locNeutralShower->Get(Points); - uint Ncell = Points.size(); + dHistNCell->Fill(Ncell); + + japp->RootUnLock(); //RELEASE ROOT LOCK - Fill1DHistogram ("BCAL_SiPM_saturation", "Hists1D", "NCell", Ncell, - "BCAL SiPM Saturation; Number of cells",nbins,0,100); for (unsigned int j = 0; j < Ncell; j++){ const DBCALPoint* locPoint = Points[j]; float t = locPoint->t(); float z = locPoint->z(); - float Ept = locPoint->E(); - int module= locPoint->module(); - int layer = locPoint->layer(); - int sector = locPoint->sector(); - // cout << " j=" << j << " t=" << t << endl; - - // calculate point energy (code taken from DBCALPoint.cc) - float z_bcal_center = 212; - float fibLen = 390; - float zLocal = z - z_bcal_center; - - - float dUp = 0.5 * fibLen + zLocal; - float dDown = 0.5 * fibLen - zLocal; - if (dUp>fibLen) dUp=fibLen; - if (dUp<0) dUp=0; - if (dDown>fibLen) dDown=fibLen; - if (dDown<0) dDown=0; - int channel = (module-1)*16 + (layer-1)*4 + (sector-1); - // cout << " module=" << module << " layer=" << layer << " sector=" << sector << " channel=" << channel << endl; - // cout << " attenuation length 00=" << attenuation_parameters[channel][0] << endl; - float attenuation_length = attenuation_parameters[channel][0]; - float attUp = exp( -dUp / attenuation_length ); - float attDown = exp( -dDown / attenuation_length ); + float Ept = locPoint->E(); + int module= locPoint->module(); + int layer = locPoint->layer(); + int sector = locPoint->sector(); + // cout << " j=" << j << " t=" << t << endl; + + // calculate point energy (code taken from DBCALPoint.cc) + float z_bcal_center = 212; + float fibLen = 390; + float zLocal = z - z_bcal_center; + + + float dUp = 0.5 * fibLen + zLocal; + float dDown = 0.5 * fibLen - zLocal; + if (dUp>fibLen) dUp=fibLen; + if (dUp<0) dUp=0; + if (dDown>fibLen) dDown=fibLen; + if (dDown<0) dDown=0; + int channel = (module-1)*16 + (layer-1)*4 + (sector-1); + // cout << " module=" << module << " layer=" << layer << " sector=" << sector << " channel=" << channel << endl; + // cout << " attenuation length 00=" << attenuation_parameters[channel][0] << endl; + float attenuation_length = attenuation_parameters[channel][0]; + float attUp = exp( -dUp / attenuation_length ); + float attDown = exp( -dDown / attenuation_length ); - if (VERBOSE>=3) cout << " VERBOSE >=3" << " t=" << t << " z=" << z << endl; - + if (VERBOSE>=3) cout << " VERBOSE >=3" << " t=" << t << " z=" << z << endl; - // Fill 1D histograms - Fill1DHistogram ("BCAL_SiPM_saturation", "Hists1D", "layer", layer, - "BCAL SiPM Saturation; Layer Number",5,0,5); + japp->RootWriteLock(); //ACQUIRE ROOT LOCK!! + + // Fill 1D histograms + dHistLayer->Fill(layer); + dHistEpoint->Fill(Ept); - Fill1DHistogram ("BCAL_SiPM_saturation", "Hists1D", "Ept", Ept, - "BCAL SiPM Saturation; Point Energy (GeV)",10*nbins,0,10); + japp->RootUnLock(); //RELEASE ROOT LOCK - // cout << " Point: Ept=" << Ept << endl; - float upHit=0; - float downHit=0; - // following two lines commented out to supress warning - // float uppeak=0; - // float downpeak=0; + // cout << " Point: Ept=" << Ept << endl; + float upHit=0; + float downHit=0; + // following two lines commented out to supress warning + // float uppeak=0; + // float downpeak=0; - vector Hits; - locPoint->Get(Hits); - uint Nhits = Hits.size(); + vector Hits; + locPoint->Get(Hits); + uint Nhits = Hits.size(); - for (unsigned int j = 0; j < Nhits; j++){ + for (unsigned int j = 0; j < Nhits; j++){ const DBCALHit* locHit = Hits[j]; float Ehit = locHit->E; /*int module = locHit->module; @@ -252,55 +293,44 @@ jerror_t JEventProcessor_BCAL_SiPM_saturation::evnt(JEventLoop *loop, uint64_t e int end = locHit->end; int pulse_peak = locHit->pulse_peak; - // cout << " module=" << module << " layer=" << layer << " sector=" << sector << " pulse_peak/Ehit=" << pulse_peak/Ehit << endl; + // cout << " module=" << module << " layer=" << layer << " sector=" << sector << " pulse_peak/Ehit=" << pulse_peak/Ehit << endl; - if (end == 0) { - upHit = Ehit; - // following line commented out to supress warning - // uppeak = pulse_peak; - } - if (end == 1) { - downHit = Ehit; - // following line commented out to supress warning - // downpeak = pulse_peak; - } + if (end == 0) { + upHit = Ehit; + // following line commented out to supress warning + // uppeak = pulse_peak; + } + if (end == 1) { + downHit = Ehit; + // following line commented out to supress warning + // downpeak = pulse_peak; + } - nbins=5100; + japp->RootWriteLock(); //ACQUIRE ROOT LOCK!! // Fill 1D histograms - if (layer == 1) { - Fill1DHistogram ("BCAL_SiPM_saturation", "Hists1D", "Hit pulse_peak layer=1", pulse_peak, - "BCAL SiPM Saturation; Hit Pulse_peak (counts)",nbins,-100,5000); - - Fill1DHistogram ("BCAL_SiPM_saturation", "Hists1D", "Hit integral layer=1", Ehit, - "BCAL SiPM Saturation; Hit integral (GeV)",nbins,0, 10); - } - else if (layer == 2) { - Fill1DHistogram ("BCAL_SiPM_saturation", "Hists1D", "Hit pulse_peak layer=2", pulse_peak, - "BCAL SiPM Saturation; Hit Pulse_peak (counts)",nbins,-100,5000); - - Fill1DHistogram ("BCAL_SiPM_saturation", "Hists1D", "Hit integral layer=2", Ehit, - "BCAL SiPM Saturation; Hit integral (GeV)",nbins,0, 10); - } - else if (layer == 3) { - Fill1DHistogram ("BCAL_SiPM_saturation", "Hists1D", "Hit pulse_peak layer=3", pulse_peak, - "BCAL SiPM Saturation; Hit Pulse_peak (counts)",nbins,-100,5000); - - Fill1DHistogram ("BCAL_SiPM_saturation", "Hists1D", "Hit integral layer=3", Ehit, - "BCAL SiPM Saturation; Hit integral (GeV)",nbins,0, 10); - } - else if (layer == 4) { - Fill1DHistogram ("BCAL_SiPM_saturation", "Hists1D", "Hit pulse_peak layer=4", pulse_peak, - "BCAL SiPM Saturation; Hit Pulse_peak (counts)",nbins,-100,5000); - - Fill1DHistogram ("BCAL_SiPM_saturation", "Hists1D", "Hit integral layer=4", Ehit, - "BCAL SiPM Saturation; Hit integral (GeV)",nbins,0, 10); - } - else { - cout << " ***Illegal layer=" << layer << endl; - } - + if (layer == 1) { + dHistPeakLayer1->Fill(pulse_peak); + dHistIntegralLayer1->Fill(Ehit); + } + else if (layer == 2) { + dHistPeakLayer2->Fill(pulse_peak); + dHistIntegralLayer2->Fill(Ehit); + } + else if (layer == 3) { + dHistPeakLayer3->Fill(pulse_peak); + dHistIntegralLayer3->Fill(Ehit); + } + else if (layer == 4) { + dHistPeakLayer4->Fill(pulse_peak); + dHistIntegralLayer4->Fill(Ehit); + } + else { + cout << " ***Illegal layer=" << layer << endl; + } + + japp->RootUnLock(); //RELEASE ROOT LOCK } @@ -315,10 +345,8 @@ jerror_t JEventProcessor_BCAL_SiPM_saturation::evnt(JEventLoop *loop, uint64_t e << " lambda=" << attenuation_length << " Eup=" << upHit << " Edown=" << downHit << " Point: Ept=" << Ept << " Ecalc=" << Ecalc << " Diff=" << Ept-Ecalc << endl;*/ - Fill1DHistogram ("BCAL_SiPM_saturation", "Hists1D", "Ecalc", Ecalc, - "BCAL SiPM Saturation; Calc Energy (GeV)",4*nbins,0,10); - Fill1DHistogram ("BCAL_SiPM_saturation", "Hists1D", "Ecalc-Ept", Ecalc-Ept, - "BCAL SiPM Saturation; Calc-Pt Energy (GeV)",nbins,-0.05,0.05); + dHistEcalc->Fill(Ecalc); + dHistEcalcEpt->Fill(Ecalc-Ept); } diff --git a/src/plugins/Calibration/BCAL_SiPM_saturation/JEventProcessor_BCAL_SiPM_saturation.h b/src/plugins/Calibration/BCAL_SiPM_saturation/JEventProcessor_BCAL_SiPM_saturation.h index d1ae6d12f8..ea329b322e 100644 --- a/src/plugins/Calibration/BCAL_SiPM_saturation/JEventProcessor_BCAL_SiPM_saturation.h +++ b/src/plugins/Calibration/BCAL_SiPM_saturation/JEventProcessor_BCAL_SiPM_saturation.h @@ -11,6 +11,10 @@ #include +#include "TH1F.h" +#include "TH2F.h" + + class JEventProcessor_BCAL_SiPM_saturation:public jana::JEventProcessor{ public: JEventProcessor_BCAL_SiPM_saturation(); @@ -28,6 +32,30 @@ class JEventProcessor_BCAL_SiPM_saturation:public jana::JEventProcessor{ vector< vector > attenuation_parameters; // store attenuation length + + TH1F *dHistEthrown; + TH1F *dHistEshower; + TH1F *dHistThrownTheta; + TH1F *dHistNCell; + TH1F *dHistLayer; + TH1F *dHistEpoint; + + TH1F *dHistPeakLayer1; + TH1F *dHistIntegralLayer1; + TH1F *dHistPeakLayer2; + TH1F *dHistIntegralLayer2; + TH1F *dHistPeakLayer3; + TH1F *dHistIntegralLayer3; + TH1F *dHistPeakLayer4; + TH1F *dHistIntegralLayer4; + TH1F *dHistEcalc; + TH1F *dHistEcalcEpt; + + + TH2F *dHistEshowerVsEthrown; + TH2F *dHistEdiffVsEthrown; + TH2F *dHistEdiffFracVsEthrown; + }; #endif // _JEventProcessor_BCAL_SiPM_saturation_ diff --git a/src/plugins/Calibration/BCAL_attenlength_gainratio/JEventProcessor_BCAL_attenlength_gainratio.cc b/src/plugins/Calibration/BCAL_attenlength_gainratio/JEventProcessor_BCAL_attenlength_gainratio.cc index 96fc2af9d4..62b97c23d1 100644 --- a/src/plugins/Calibration/BCAL_attenlength_gainratio/JEventProcessor_BCAL_attenlength_gainratio.cc +++ b/src/plugins/Calibration/BCAL_attenlength_gainratio/JEventProcessor_BCAL_attenlength_gainratio.cc @@ -104,7 +104,7 @@ jerror_t JEventProcessor_BCAL_attenlength_gainratio::init(void) hist2D_intattenlength = new TH2F("hist2D_intattenlength",histtitle,48,0.5,48.5,16,0.5,16.5); sprintf(histtitle,"Gain ratio from integ.;Module;Layer and Sector;G_{U}/G_{D}"); hist2D_intgainratio = new TH2F("hist2D_intgainratio",histtitle,48,0.5,48.5,16,0.5,16.5); - + if (VERBOSEHISTOGRAMS) { sprintf(histtitle,"Atten. length from peak;Module;Layer and Sector"); hist2D_peakattenlength = new TH2F("hist2D_peakattenlength",histtitle,48,0.5,48.5,16,0.5,16.5); @@ -126,6 +126,7 @@ jerror_t JEventProcessor_BCAL_attenlength_gainratio::init(void) TDirectory *dirlogpeakratiovsZ = bcalgainratio->mkdir("logpeakratiovsZ"); TDirectory *dirlogintratiovsZ = bcalgainratio->mkdir("logintratiovsZ"); + TDirectory *dirlogEratiovsZ = bcalgainratio->mkdir("logEratiovsZ"); TDirectory *dirEvsZ = bcalgainratio->mkdir("EvsZ"); // Create histograms @@ -142,7 +143,33 @@ jerror_t JEventProcessor_BCAL_attenlength_gainratio::init(void) } } } + + dirlogEratiovsZ->cd(); + for (int layer=0; layercd(); + for (int layer=0; layerRootFillLock(this); //ACQUIRE ROOT FILL LOCK @@ -288,26 +313,12 @@ jerror_t JEventProcessor_BCAL_attenlength_gainratio::evnt(JEventLoop *loop, uint logintratiovsZ_all->Fill(zpos, logintratio); logpeakratiovsZ_all->Fill(zpos, logpeakratio); - sprintf(name,"logintratiovsZ_layer%i",layer); - sprintf(histtitle,"Layer %i;Z Position (cm);log of integral ratio US/DS",layer); - Fill2DHistogram("bcalgainratio", "logintratiovsZ", name, - zpos, logintratio, histtitle, 500,-250.0,250.0,500,-3,3); - - if (VERBOSEHISTOGRAMS) { - sprintf(name,"logEratiovsZ_%02i%i%i",module,layer,sector); - sprintf(histtitle,"Channel (M%i,L%i,S%i);Z Position (cm);log of E ratio ln(E_{US}/E_{DS}) ",module,layer,sector); - Fill2DHistogram("bcalgainratio", "logEratiovsZ", name, - zpos, logEratio, histtitle, 250,-250.0,250.0,400,-4,4); - } - - sprintf(name,"logEratiovsZ_layer%i",layer); - sprintf(histtitle,"Layer %i;Z Position (cm);log of E ratio ln(E_{US}/E_{DS}) ",layer); - Fill2DHistogram("bcalgainratio", "logEratiovsZ", name, - zpos, logEratio, histtitle, 500,-250.0,250.0,500,-3,3); - + logintratiovsZ_layers[layer-1]->Fill(zpos, logintratio); + logEratiovsZ_layers[layer-1]->Fill(zpos, logEratio); if (VERBOSEHISTOGRAMS) { logpeakratiovsZ[module-1][layer-1][sector-1]->Fill(zpos, logpeakratio); + logEratiovsZ[module-1][layer-1][sector-1]->Fill(zpos, logEratio); } } if (VERBOSEHISTOGRAMS) EvsZ[module-1][layer-1][sector-1]->Fill(zpos, pointE); @@ -321,6 +332,10 @@ jerror_t JEventProcessor_BCAL_attenlength_gainratio::evnt(JEventLoop *loop, uint return NOERROR; } + +// FINISHFINISHFINISHFINISHFINISHFINISHFINISH + + //------------------ // erun //------------------ diff --git a/src/plugins/Calibration/BCAL_attenlength_gainratio/JEventProcessor_BCAL_attenlength_gainratio.h b/src/plugins/Calibration/BCAL_attenlength_gainratio/JEventProcessor_BCAL_attenlength_gainratio.h index 22030797d0..54df9a2908 100644 --- a/src/plugins/Calibration/BCAL_attenlength_gainratio/JEventProcessor_BCAL_attenlength_gainratio.h +++ b/src/plugins/Calibration/BCAL_attenlength_gainratio/JEventProcessor_BCAL_attenlength_gainratio.h @@ -54,11 +54,14 @@ class JEventProcessor_BCAL_attenlength_gainratio:public jana::JEventProcessor{ TH2I *logintratiovsZ_all = nullptr; TH2I *logpeakratiovsZ[JEventProcessor_BCAL_attenlength_gainratio::nummodule][JEventProcessor_BCAL_attenlength_gainratio::numlayer][JEventProcessor_BCAL_attenlength_gainratio::numsector]; TH2I *logintratiovsZ[JEventProcessor_BCAL_attenlength_gainratio::nummodule][JEventProcessor_BCAL_attenlength_gainratio::numlayer][JEventProcessor_BCAL_attenlength_gainratio::numsector]; + TH2I *logEratiovsZ[JEventProcessor_BCAL_attenlength_gainratio::nummodule][JEventProcessor_BCAL_attenlength_gainratio::numlayer][JEventProcessor_BCAL_attenlength_gainratio::numsector]; TH2I *EvsZ[JEventProcessor_BCAL_attenlength_gainratio::nummodule][JEventProcessor_BCAL_attenlength_gainratio::numlayer][JEventProcessor_BCAL_attenlength_gainratio::numsector]; // Debug histograms to help understand data TH2I *EvsZ_all = nullptr; TH2I *EvsZ_layer[4] = { nullptr }; + TH2I *logintratiovsZ_layers[4] = { nullptr }; + TH2I *logEratiovsZ_layers[4] = { nullptr }; TH2F *hist2D_aveZ = nullptr; }; diff --git a/src/plugins/Calibration/CDC_TimeToDistance/JEventProcessor_CDC_TimeToDistance.cc b/src/plugins/Calibration/CDC_TimeToDistance/JEventProcessor_CDC_TimeToDistance.cc index b478df9cf5..f27c11347f 100644 --- a/src/plugins/Calibration/CDC_TimeToDistance/JEventProcessor_CDC_TimeToDistance.cc +++ b/src/plugins/Calibration/CDC_TimeToDistance/JEventProcessor_CDC_TimeToDistance.cc @@ -49,7 +49,7 @@ JEventProcessor_CDC_TimeToDistance::~JEventProcessor_CDC_TimeToDistance() //------------------ jerror_t JEventProcessor_CDC_TimeToDistance::init(void) { - // Save the current values of the T/D constants + int prof_td_max = 1000; gDirectory->mkdir("CDC_TimeToDistance"); gDirectory->cd("CDC_TimeToDistance"); @@ -57,6 +57,66 @@ jerror_t JEventProcessor_CDC_TimeToDistance::init(void) // Use a TProfile to avoid problems adding together multiple root files... HistCurrentConstants = new TProfile("CDC_TD_Constants", "CDC T/D constants", 125 ,0.5, 125.5); + dHistZ2tracks0001 = new TH1F("Z_2tracks_0_001", "Vertex z from 2 tracks with fom 0.001+; z (cm)",700,30,100); + dHistZ2tracks001 = new TH1F("Z_2tracks_0_01", "Vertex z from 2 tracks with fom 0.01+; z (cm)",700,30,100); + dHistZ2tracks01 = new TH1F("Z_2tracks_0_1", "Vertex z from 2 tracks with fom 0.1+; z (cm)",700,30,100); + + dHistResidualVslogFOM = new TH2F("Residual vs logFOM", "Residual vs log10(FOM); log10(FOM); Residual(cm)", + 50,-10,0,100, -0.05,0.05); + dHistResidualVsFOM = new TH2F("Residual vs FOM", "Residual vs FOM; FOM; Residual(cm)", + 50,0,1,100, -0.05,0.05); + dHistEarlyDriftTimesPerChannel = new TH2F("Early Drift Times", "Per straw drift times; Drift time [ns];CCDB Index", + 200,-50,50,3522,0.5,3522.5); + dHistResidualVsDriftTime = new TH2F("Residual Vs. Drift Time", "Residual Vs. Drift Time; Drift time [ns];Residual [cm]", + 250,0.,1000,100, -0.05,0.05); + dHistResidualVsDriftTimeFOM09 = new TH2F("Residual Vs. Drift Time, FOM 0.9+", "Residual Vs. Drift Time, FOM 0.9+; Drift time [ns];Residual [cm]", + 250,0.,1000,100, -0.05,0.05); + dHistResidualVsDriftTimeFOM06 = new TH2F("Residual Vs. Drift Time, FOM 0.6+", "Residual Vs. Drift Time, FOM 0.6+; Drift time [ns];Residual [cm]", + 250,0.,1000,100, -0.05,0.05); + dHistResidualVsDriftTimeFOM01 = new TH2F("Residual Vs. Drift Time, FOM 0.1+", "Residual Vs. Drift Time, FOM 0.1+; Drift time [ns];Residual [cm]", + 250,0.,1000,100, -0.05,0.05); + dHistResidualVsDriftTimeFOM001 = new TH2F("Residual Vs. Drift Time, FOM 0.01+", "Residual Vs. Drift Time, FOM 0.01+; Drift time [ns];Residual [cm]", + 250,0.,1000,100, -0.05,0.05); + dHistResidualVsDriftTimeStraightStraws = new TH2F("Residual Vs. Drift Time, max sag < 0.2mm", "Residual Vs. Drift Time (straight straws); Drift time [ns];Residual [cm]", + 250,0.,1000,100, -0.05,0.05); + + dHistBz = new TH1F("Bz", "B_{z};B_{z} [T]", 100, 0.0, 2.5); + + dHistPredictedDistanceVsDeltaVsDrift = new TProfile2D("Predicted Drift Distance Vs Delta Vs t_drift", + "Predicted Drift Distance Vs. #delta Vs. t_{drift}; t_{drift} [ns]; #delta [cm]", + 500, 0, prof_td_max, 200, -0.3, 0.3); + dHistPredictedDistanceVsDeltaVsDriftFOM09 = new TProfile2D("Predicted Drift Distance Vs Delta Vs t_drift, FOM 0.9+", + "Predicted Drift Distance Vs. #delta Vs. t_{drift}, FOM 0.9+; t_{drift} [ns]; #delta [cm]", + 500, 0, prof_td_max, 200, -0.3, 0.3); + dHistPredictedDistanceVsDeltaVsDriftFOM06 = new TProfile2D("Predicted Drift Distance Vs Delta Vs t_drift, FOM 0.6+", + "Predicted Drift Distance Vs. #delta Vs. t_{drift}, FOM 0.9+; t_{drift} [ns]; #delta [cm]", + 500, 0, prof_td_max, 200, -0.3, 0.3); + dHistPredictedDistanceVsDeltaVsDriftFOM01 = new TProfile2D("Predicted Drift Distance Vs Delta Vs t_drift, FOM 0.1+", + "Predicted Drift Distance Vs. #delta Vs. t_{drift}, FOM 0.9+; t_{drift} [ns]; #delta [cm]", + 500, 0, prof_td_max, 200, -0.3, 0.3); + dHistPredictedDistanceVsDeltaVsDriftFOM001 = new TProfile2D("Predicted Drift Distance Vs Delta Vs t_drift, FOM 0.01+", + "Predicted Drift Distance Vs. #delta Vs. t_{drift}, FOM 0.9+; t_{drift} [ns]; #delta [cm]", + 500, 0, prof_td_max, 200, -0.3, 0.3); + dHistPredictedDistanceVsDeltaVsDrift05 = new TProfile2D("Predicted Drift Distance Vs Delta Vs t_drift < 0.05", + "Predicted Drift Distance Vs. #delta Vs. t_{drift}; t_{drift} [ns]; #delta [cm]", + 500, 0, prof_td_max, 200, -0.3, 0.3); + dHistPredictedDistanceVsDeltaVsDrift10 = new TProfile2D("Predicted Drift Distance Vs Delta Vs t_drift < 0.10", + "Predicted Drift Distance Vs. #delta Vs. t_{drift}; t_{drift} [ns]; #delta [cm]", + 500, 0, prof_td_max, 200, -0.3, 0.3); + dHistPredictedDistanceVsDeltaVsDrift15 = new TProfile2D("Predicted Drift Distance Vs Delta Vs t_drift < 0.15", + "Predicted Drift Distance Vs. #delta Vs. t_{drift}; t_{drift} [ns]; #delta [cm]", + 500, 0, prof_td_max, 200, -0.3, 0.3); + dHistPredictedDistanceVsDeltaVsDrift20 = new TProfile2D("Predicted Drift Distance Vs Delta Vs t_drift < 0.20", + "Predicted Drift Distance Vs. #delta Vs. t_{drift}; t_{drift} [ns]; #delta [cm]", + 500, 0, prof_td_max, 200, -0.3, 0.3); + dHistPredictedDistanceVsDeltaVsDrift25 = new TProfile2D("Predicted Drift Distance Vs Delta Vs t_drift < 0.25", + "Predicted Drift Distance Vs. #delta Vs. t_{drift}; t_{drift} [ns]; #delta [cm]", + 500, 0, prof_td_max, 200, -0.3, 0.3); + dHistPredictedDistanceVsDeltaVsDriftBz18 = new TProfile2D("Predicted Drift Distance Vs Delta Vs t_drift, Bz 1.8T", + "Predicted Drift Distance Vs. #delta Vs. t_{drift}; t_{drift} [ns]; #delta [cm]", + 500, 0, prof_td_max, 200, -0.3, 0.3); + + gDirectory->cd(".."); UNBIASED_RING=0; @@ -112,11 +172,13 @@ jerror_t JEventProcessor_CDC_TimeToDistance::brun(JEventLoop *eventLoop, int32_t char ccdbTable[128]; sprintf(ccdbTable,"CDC/cdc_drift_table%s",dIsNoFieldFlag?"::NoBField":""); - if (jcalib->Get(ccdbTable, tvals)==false){ + if (jcalib->Get(ccdbTable, tvals)==false){ + japp->RootWriteLock(); //ACQUIRE ROOT LOCK!! for(unsigned int i=0; i &row = tvals[i]; HistCurrentConstants->Fill(i+1,1000.*row["t"]); } + japp->RootUnLock(); //RELEASE ROOT LOCK } else{ jerr << " CDC time-to-distance table not available... bailing..." << endl; @@ -125,6 +187,7 @@ jerror_t JEventProcessor_CDC_TimeToDistance::brun(JEventLoop *eventLoop, int32_t sprintf(ccdbTable,"CDC/drift_parameters%s",dIsNoFieldFlag?"::NoBField":""); if (jcalib->Get(ccdbTable, tvals)==false){ + japp->RootWriteLock(); //ACQUIRE ROOT LOCK!! map &row = tvals[0]; // long drift side HistCurrentConstants->Fill(101,row["a1"]); HistCurrentConstants->Fill(102,row["a2"]); @@ -150,6 +213,7 @@ jerror_t JEventProcessor_CDC_TimeToDistance::brun(JEventLoop *eventLoop, int32_t HistCurrentConstants->Fill(120,row["c3"]); HistCurrentConstants->Fill(121,row["B1"]); HistCurrentConstants->Fill(122,row["B2"]); + japp->RootUnLock(); //RELEASE ROOT LOCK } // Save run number @@ -203,13 +267,13 @@ jerror_t JEventProcessor_CDC_TimeToDistance::evnt(JEventLoop *loop, uint64_t eve if(!thisTimeBasedTrack->IsSmoothed) least_fom = 0; // don't use this event } } - - if (least_fom >= 0.001) Fill1DHistogram("CDC_TimeToDistance","","Z_2tracks_0_001", z, "Vertex z from 2 tracks with fom 0.001+; z (cm)",700,30,100); - - if (least_fom >= 0.01) Fill1DHistogram("CDC_TimeToDistance","","Z_2tracks_0_01", z, "Vertex z from 2 tracks with fom 0.01+; z (cm)",700,30,100); - - if (least_fom >= 0.1) Fill1DHistogram("CDC_TimeToDistance","","Z_2tracks_0_1", z, "Vertex z from 2 tracks with fom 0.1+; z (cm)",700,30,100); - + + japp->RootWriteLock(); //ACQUIRE ROOT LOCK!! + if (least_fom >= 0.001) dHistZ2tracks0001->Fill(z); + if (least_fom >= 0.01) dHistZ2tracks001->Fill(z); + if (least_fom >= 0.1) dHistZ2tracks01->Fill(z); + japp->RootUnLock(); //RELEASE ROOT LOCK + } // end if 2 tracks @@ -247,46 +311,21 @@ jerror_t JEventProcessor_CDC_TimeToDistance::evnt(JEventLoop *loop, uint64_t eve int ring = thisCDCHit->wire->ring; int straw = thisCDCHit->wire->straw; - - Fill2DHistogram("CDC_TimeToDistance","","Residual vs logFOM", - log10(thisTimeBasedTrack->FOM), thisPull.resi, - "Residual vs log10(FOM); log10(FOM); Residual(cm)", - 50,-10,0,100, -0.05,0.05); - - - Fill2DHistogram("CDC_TimeToDistance","","Residual vs FOM", - thisTimeBasedTrack->FOM, thisPull.resi, - "Residual vs FOM; FOM; Residual(cm)", - 50,0,1,100, -0.05,0.05); - - + japp->RootWriteLock(); //ACQUIRE ROOT LOCK!! + + dHistResidualVsFOM->Fill(thisTimeBasedTrack->FOM, thisPull.resi); + dHistResidualVslogFOM->Fill(log10(thisTimeBasedTrack->FOM), thisPull.resi); // Fill Histogram with the drift times near t0 (+-50 ns) - Fill2DHistogram("CDC_TimeToDistance","","Early Drift Times", - time,straw_offset[ring]+straw, - "Per straw drift times; Drift time [ns];CCDB Index", - 200,-50,50,3522,0.5,3522.5); - - Fill2DHistogram("CDC_TimeToDistance","","Residual Vs. Drift Time", - time,residual, - "Residual Vs. Drift Time; Drift time [ns];Residual [cm]", - 250,0.,1000,100, -0.05,0.05); - - if (thisTimeBasedTrack->FOM >= 0.9) Fill2DHistogram("CDC_TimeToDistance","","Residual Vs. Drift Time, FOM 0.9+", time,residual, "Residual Vs. Drift Time, FOM 0.9+; Drift time [ns];Residual [cm]", 250,0.,1000,100, -0.05,0.05); - - if (thisTimeBasedTrack->FOM >= 0.6) Fill2DHistogram("CDC_TimeToDistance","","Residual Vs. Drift Time, FOM 0.6+", time,residual, "Residual Vs. Drift Time, FOM 0.6+; Drift time [ns];Residual [cm]", 250,0.,1000,100, -0.05,0.05); - - if (thisTimeBasedTrack->FOM >= 0.1) Fill2DHistogram("CDC_TimeToDistance","","Residual Vs. Drift Time, FOM 0.1+", time,residual, "Residual Vs. Drift Time, FOM 0.1+; Drift time [ns];Residual [cm]", 250,0.,1000,100, -0.05,0.05); - - if (thisTimeBasedTrack->FOM >= 0.01) Fill2DHistogram("CDC_TimeToDistance","","Residual Vs. Drift Time, FOM 0.01+", time,residual, "Residual Vs. Drift Time, FOM 0.01+; Drift time [ns];Residual [cm]", 250,0.,1000,100, -0.05,0.05); - - - if (max_sag[ring - 1][straw - 1] < 0.02) Fill2DHistogram("CDC_TimeToDistance","","Residual Vs. Drift Time, max sag < 0.2mm", - time,residual, - "Residual Vs. Drift Time (straight straws); Drift time [ns];Residual [cm]", - 250,0.,1000,100, -0.05,0.05); - + dHistEarlyDriftTimesPerChannel->Fill(time,straw_offset[ring]+straw); + dHistResidualVsDriftTime->Fill(time,residual); + if (thisTimeBasedTrack->FOM >= 0.9) dHistResidualVsDriftTimeFOM09->Fill(time,residual); + if (thisTimeBasedTrack->FOM >= 0.6) dHistResidualVsDriftTimeFOM06->Fill(time,residual); + if (thisTimeBasedTrack->FOM >= 0.1) dHistResidualVsDriftTimeFOM01->Fill(time,residual); + if (thisTimeBasedTrack->FOM >= 0.01) dHistResidualVsDriftTimeFOM001->Fill(time,residual); + + if (max_sag[ring - 1][straw - 1] < 0.02) dHistResidualVsDriftTimeStraightStraws->Fill(time,residual); if(UNBIASED_RING != 0 && (ring != UNBIASED_RING) ) continue; @@ -299,73 +338,42 @@ jerror_t JEventProcessor_CDC_TimeToDistance::evnt(JEventLoop *loop, uint64_t eve DVector3 thisHitLocation = thisCDCHit->wire->origin + udir * (dz / udir.CosTheta()); double Bz = dMagneticField->GetBz(thisHitLocation.X(), thisHitLocation.Y(), thisHitLocation.Z()); if ( Bz != 0.0 ) { - Fill1DHistogram("CDC_TimeToDistance", "", "Bz", - Bz, - "B_{z};B_{z} [T]", 100, 0.0, 2.5); + dHistBz->Fill(Bz); } double delta = max_sag[ring - 1][straw - 1]*(1.-dz*dz/5625.) *cos(docaphi + sag_phi_offset[ring - 1][straw - 1]); - int prof_td_max = 1000; // We only really need one histogram here - Fill2DProfile("CDC_TimeToDistance", "", "Predicted Drift Distance Vs Delta Vs t_drift", - time, delta, predictedDistance, - "Predicted Drift Distance Vs. #delta Vs. t_{drift}; t_{drift} [ns]; #delta [cm]", - 500, 0, prof_td_max, 200, -0.3, 0.3); - - - if (thisTimeBasedTrack->FOM >= 0.01) Fill2DProfile("CDC_TimeToDistance", "", "Predicted Drift Distance Vs Delta Vs t_drift, FOM 0.01+", time, delta, predictedDistance, "Predicted Drift Distance Vs. #delta Vs. t_{drift}, FOM 0.01+; t_{drift} [ns]; #delta [cm]", 500, 0, prof_td_max, 200, -0.3, 0.3); - - if (thisTimeBasedTrack->FOM >= 0.1) Fill2DProfile("CDC_TimeToDistance", "", "Predicted Drift Distance Vs Delta Vs t_drift, FOM 0.1+", time, delta, predictedDistance, "Predicted Drift Distance Vs. #delta Vs. t_{drift}, FOM 0.1+; t_{drift} [ns]; #delta [cm]", 500, 0, prof_td_max, 200, -0.3, 0.3); - - if (thisTimeBasedTrack->FOM >= 0.6) Fill2DProfile("CDC_TimeToDistance", "", "Predicted Drift Distance Vs Delta Vs t_drift, FOM 0.6+", time, delta, predictedDistance, "Predicted Drift Distance Vs. #delta Vs. t_{drift}, FOM 0.6+; t_{drift} [ns]; #delta [cm]", 500, 0, prof_td_max, 200, -0.3, 0.3); - - if (thisTimeBasedTrack->FOM >= 0.9) Fill2DProfile("CDC_TimeToDistance", "", "Predicted Drift Distance Vs Delta Vs t_drift, FOM 0.9+", time, delta, predictedDistance, "Predicted Drift Distance Vs. #delta Vs. t_{drift}, FOM 0.9+; t_{drift} [ns]; #delta [cm]", 500, 0, prof_td_max, 200, -0.3, 0.3); - + dHistPredictedDistanceVsDeltaVsDrift->Fill(time, delta, predictedDistance); + if (thisTimeBasedTrack->FOM >= 0.9) dHistPredictedDistanceVsDeltaVsDriftFOM09->Fill(time, delta, predictedDistance); + if (thisTimeBasedTrack->FOM >= 0.6) dHistPredictedDistanceVsDeltaVsDriftFOM06->Fill(time, delta, predictedDistance); + if (thisTimeBasedTrack->FOM >= 0.1) dHistPredictedDistanceVsDeltaVsDriftFOM01->Fill(time, delta, predictedDistance); + if (thisTimeBasedTrack->FOM >= 0.01) dHistPredictedDistanceVsDeltaVsDriftFOM001->Fill(time, delta, predictedDistance); // To investigate some features, also do this in bins of Max sag if (max_sag[ring - 1][straw - 1] < 0.05){ - Fill2DProfile("CDC_TimeToDistance", "", "Predicted Drift Distance Vs Delta Vs t_drift < 0.05", - time, delta, predictedDistance, - "Predicted Drift Distance Vs. #delta Vs. t_{drift}; t_{drift} [ns]; #delta [cm]", - 500, 0, prof_td_max, 200, -0.3, 0.3); + dHistPredictedDistanceVsDeltaVsDrift05->Fill(time, delta, predictedDistance); } else if (max_sag[ring - 1][straw - 1] < 0.10){ - Fill2DProfile("CDC_TimeToDistance", "", "Predicted Drift Distance Vs Delta Vs t_drift < 0.10", - time, delta, predictedDistance, - "Predicted Drift Distance Vs. #delta Vs. t_{drift}; t_{drift} [ns]; #delta [cm]", - 500, 0, prof_td_max, 200, -0.3, 0.3); + dHistPredictedDistanceVsDeltaVsDrift10->Fill(time, delta, predictedDistance); } else if (max_sag[ring - 1][straw - 1] < 0.15){ - Fill2DProfile("CDC_TimeToDistance", "", "Predicted Drift Distance Vs Delta Vs t_drift < 0.15", - time, delta, predictedDistance, - "Predicted Drift Distance Vs. #delta Vs. t_{drift}; t_{drift} [ns]; #delta [cm]", - 500, 0, prof_td_max, 200, -0.3, 0.3); + dHistPredictedDistanceVsDeltaVsDrift15->Fill(time, delta, predictedDistance); } else if (max_sag[ring - 1][straw - 1] < 0.20){ - Fill2DProfile("CDC_TimeToDistance", "", "Predicted Drift Distance Vs Delta Vs t_drift < 0.20", - time, delta, predictedDistance, - "Predicted Drift Distance Vs. #delta Vs. t_{drift}; t_{drift} [ns]; #delta [cm]", - 500, 0, prof_td_max, 200, -0.3, 0.3); + dHistPredictedDistanceVsDeltaVsDrift20->Fill(time, delta, predictedDistance); } else if (max_sag[ring - 1][straw - 1] < 0.25){ - Fill2DProfile("CDC_TimeToDistance", "", "Predicted Drift Distance Vs Delta Vs t_drift < 0.25", - time, delta, predictedDistance, - "Predicted Drift Distance Vs. #delta Vs. t_{drift}; t_{drift} [ns]; #delta [cm]", - 500, 0, prof_td_max, 200, -0.3, 0.3); + dHistPredictedDistanceVsDeltaVsDrift25->Fill(time, delta, predictedDistance); } // histo for hits in 1.8T region - if (Bz > 1/75 && Bz < 1.85) Fill2DProfile("CDC_TimeToDistance", "", "Predicted Drift Distance Vs Delta Vs t_drift, Bz 1.8T", - time, delta, predictedDistance, - "Predicted Drift Distance Vs. #delta Vs. t_{drift}, 1.8T; t_{drift} [ns]; #delta [cm]", - 500, 0, prof_td_max, 200, -0.3, 0.3); - - - + if (Bz > 1.75 && Bz < 1.85) dHistPredictedDistanceVsDeltaVsDriftBz18->Fill(time, delta, predictedDistance); + + japp->RootUnLock(); //RELEASE ROOT LOCK } } return NOERROR; diff --git a/src/plugins/Calibration/CDC_TimeToDistance/JEventProcessor_CDC_TimeToDistance.h b/src/plugins/Calibration/CDC_TimeToDistance/JEventProcessor_CDC_TimeToDistance.h index f69fde8db0..47d1728e80 100644 --- a/src/plugins/Calibration/CDC_TimeToDistance/JEventProcessor_CDC_TimeToDistance.h +++ b/src/plugins/Calibration/CDC_TimeToDistance/JEventProcessor_CDC_TimeToDistance.h @@ -9,7 +9,10 @@ #define _JEventProcessor_CDC_TimeToDistance_ #include +#include "TProfile2D.h" #include "TProfile.h" +#include "TH1F.h" +#include "TH2F.h" #include "HDGEOMETRY/DMagneticFieldMap.h" class JEventProcessor_CDC_TimeToDistance:public jana::JEventProcessor{ @@ -26,10 +29,41 @@ class JEventProcessor_CDC_TimeToDistance:public jana::JEventProcessor{ jerror_t fini(void); ///< Called after last event of last event source has been processed. vector >max_sag; vector >sag_phi_offset; - TProfile *HistCurrentConstants; + const DMagneticFieldMap* dMagneticField; int UNBIASED_RING; double MIN_FOM; + + TProfile *HistCurrentConstants; + + TH1F *dHistZ2tracks0001; + TH1F *dHistZ2tracks001; + TH1F *dHistZ2tracks01; + + TH2F *dHistResidualVslogFOM; + TH2F *dHistResidualVsFOM; + TH2F *dHistEarlyDriftTimesPerChannel; + TH2F *dHistResidualVsDriftTime; + TH2F *dHistResidualVsDriftTimeFOM09; + TH2F *dHistResidualVsDriftTimeFOM06; + TH2F *dHistResidualVsDriftTimeFOM01; + TH2F *dHistResidualVsDriftTimeFOM001; + TH2F *dHistResidualVsDriftTimeStraightStraws; + + TH1F *dHistBz; + + TProfile2D *dHistPredictedDistanceVsDeltaVsDrift; + TProfile2D *dHistPredictedDistanceVsDeltaVsDriftFOM09; + TProfile2D *dHistPredictedDistanceVsDeltaVsDriftFOM06; + TProfile2D *dHistPredictedDistanceVsDeltaVsDriftFOM01; + TProfile2D *dHistPredictedDistanceVsDeltaVsDriftFOM001; + TProfile2D *dHistPredictedDistanceVsDeltaVsDrift05; + TProfile2D *dHistPredictedDistanceVsDeltaVsDrift10; + TProfile2D *dHistPredictedDistanceVsDeltaVsDrift15; + TProfile2D *dHistPredictedDistanceVsDeltaVsDrift20; + TProfile2D *dHistPredictedDistanceVsDeltaVsDrift25; + TProfile2D *dHistPredictedDistanceVsDeltaVsDriftBz18; + }; #endif // _JEventProcessor_CDC_TimeToDistance_ diff --git a/src/plugins/Calibration/FCALLEDTree/JEventProcessor_FCALLEDTree.cc b/src/plugins/Calibration/FCALLEDTree/JEventProcessor_FCALLEDTree.cc index 9fed42da23..1c28d3ea50 100644 --- a/src/plugins/Calibration/FCALLEDTree/JEventProcessor_FCALLEDTree.cc +++ b/src/plugins/Calibration/FCALLEDTree/JEventProcessor_FCALLEDTree.cc @@ -24,6 +24,13 @@ extern "C"{ } } // "C" +static TH2F *hXYGeo; +static TH2F *hXYGeo_w; +static TH2F *hE; +static TH2F *hped; +static TH2F *hpeak; +static TH2F *hinteg; + //------------------ // JEventProcessor_FCALLEDTree (Constructor) @@ -68,9 +75,22 @@ jerror_t JEventProcessor_FCALLEDTree::init(void) m_tree->Branch( "event", &m_event, "event/L" ); m_tree->Branch( "eTot", &m_eTot, "eTot/F" ); } - - japp->RootUnLock(); + // create root folder and cd to it, store main dir + TDirectory *main = gDirectory; // save current directory + TDirectory *hvscandir = main->mkdir("hv_scan"); + hvscandir->cd(); + + hXYGeo = new TH2F("XYGeo", ";row;column #;Counts", 59, 0, 59, 59, 0, 59); + hXYGeo_w = new TH2F("XYGeo_w", ";row;column #;E_{max}^{sum} [GeV]", 59, 0, 59, 59, 0, 59); + hE = new TH2F("m_E", ";channel;energy;Counts", 2800, 0, 2800, 1200, 0, 12.); + hped = new TH2F("m_ped", ";channel;pedestal;Counts", 2800, 0, 2800, 4096, 0., 4096.); + hpeak = new TH2F("m_peak", ";channel;peak;Counts", 2800, 0, 2800, 4096, 0., 4096.); + hinteg = new TH2F("m_integ", ";channel;integ;Counts", 2800, 0, 2800, 4096, 0., 4096.); + + main->cd(); + + japp->RootUnLock(); return NOERROR; } @@ -106,21 +126,24 @@ jerror_t JEventProcessor_FCALLEDTree::evnt(JEventLoop *loop, uint64_t eventnumbe return OBJECT_NOT_AVAILABLE; const DFCALGeometry& fcalGeom = *(fcalGeomVect[0]); - japp->RootFillLock(this); m_event = eventnumber; m_nHits = 0; m_eTot = 0; + + japp->RootFillLock(this); + for( vector< const DFCALHit* >::const_iterator hit = hits.begin(); hit != hits.end(); ++hit ){ vector< const DFCALDigiHit* > digiHits; (**hit).Get( digiHits ); + if( digiHits.size() != 1 ) std::cout << "ERROR: wrong size!! " << std::endl; - + const DFCALDigiHit& dHit = *(digiHits[0]); m_chan[m_nHits] = fcalGeom.channel( (**hit).row, (**hit).column ); @@ -138,13 +161,13 @@ jerror_t JEventProcessor_FCALLEDTree::evnt(JEventLoop *loop, uint64_t eventnumbe int row = fcalGeom.row((**hit).x); int col = fcalGeom.column((**hit).y); - - Fill2DHistogram("hv_scan","","XYGeo", row, col, ";row;column #;Counts", 59, 0, 59, 59, 0, 59); - Fill2DWeightedHistogram("hv_scan","","XYGeo_w", row, col, (**hit).E, ";row;column #;E_{max}^{sum} [GeV]", 59, 0, 59, 59, 0, 59); - Fill2DHistogram("hv_scan","","m_E", fcalGeom.channel((**hit).row, (**hit).column ), (**hit).E, ";channel;energy;Counts", 2800, 0, 2800, 1200, 0, 12.); - Fill2DHistogram("hv_scan","","m_ped", fcalGeom.channel((**hit).row, (**hit).column ), (float)dHit.pedestal/dHit.nsamples_pedestal, ";channel;pedestal;Counts", 2800, 0, 2800, 4096, 0., 4096.); - Fill2DHistogram("hv_scan","","m_peak", fcalGeom.channel((**hit).row, (**hit).column ), dHit.pulse_peak - m_ped[m_nHits], ";channel;peak;Counts", 2800, 0, 2800, 4096, 0., 4096.); - Fill2DHistogram("hv_scan","","m_integ", fcalGeom.channel((**hit).row, (**hit).column ), dHit.pulse_integral - (m_ped[m_nHits]*dHit.nsamples_integral), ";channel;integ;Counts", 2800, 0, 2800, 4096, 0., 4096.); + + hXYGeo->Fill( row, col ); + hXYGeo_w->Fill(row, col, (**hit).E ); + hE->Fill(fcalGeom.channel((**hit).row, (**hit).column ), (**hit).E); + hped->Fill(fcalGeom.channel((**hit).row, (**hit).column ), (float)dHit.pedestal/dHit.nsamples_pedestal); + hpeak->Fill(fcalGeom.channel((**hit).row, (**hit).column ), dHit.pulse_peak - m_ped[m_nHits]); + hinteg->Fill(fcalGeom.channel((**hit).row, (**hit).column ), dHit.pulse_integral - (m_ped[m_nHits]*dHit.nsamples_integral)); ++m_nHits; } @@ -154,7 +177,8 @@ jerror_t JEventProcessor_FCALLEDTree::evnt(JEventLoop *loop, uint64_t eventnumbe } japp->RootFillUnLock(this); - + + return NOERROR; } @@ -175,10 +199,11 @@ jerror_t JEventProcessor_FCALLEDTree::erun(void) jerror_t JEventProcessor_FCALLEDTree::fini(void) { // Called before program exit after event processing is finished. - japp->RootWriteLock(); - m_tree->Write(); - japp->RootUnLock(); - + if (btree == 1) { + japp->RootWriteLock(); + m_tree->Write(); + japp->RootUnLock(); + } return NOERROR; } diff --git a/src/plugins/Calibration/FCALLEDTree/SConstruct b/src/plugins/Calibration/FCALLEDTree/SConstruct deleted file mode 100644 index bdb81fe3e6..0000000000 --- a/src/plugins/Calibration/FCALLEDTree/SConstruct +++ /dev/null @@ -1,129 +0,0 @@ - -# -# Jan. 31, 2014 David Lawrence -# -# This SConstruct file can be copied into a directory containing -# the source for a plugin and used to compile it. It will use and -# install into the directory specified by the HALLD_MY environment -# variable if defined. Otherwise, it will install in the HALLD_HOME -# directory. -# -# This file should not need modification. It will be copied in by -# the mkplugin or mkfactory_plugin scripts or you can just copy it -# by hand. -# -# To use this, just type "scons install" to build and install. -# Just type "scons" if you want to build, but not install it. -# -# > scons install -# -# Note that unlike the rest of the SBMS system, this does not -# use a separate build directory and builds everything in the -# source directory. This is due to technical details and will hopefully -# be fixed in the future. For now it means, that you must be -# diligent of building for multiple platforms using the same source. -# - -import os -import sys -import subprocess -import glob - -# Get HALLD_HOME environment variable, verifying it is set -halld_home = os.getenv('HALLD_HOME') -if(halld_home == None): - print 'HALLD_HOME environment variable not set!' - exit(-1) - -# Get HALLD_MY if it exists. Otherwise use HALLD_HOME -halld_my = os.getenv('HALLD_MY', halld_home) - -# Add SBMS directory to PYTHONPATH -sbmsdir = "%s/src/SBMS" % halld_home -sys.path.append(sbmsdir) - -import sbms - -# Get command-line options -SHOWBUILD = ARGUMENTS.get('SHOWBUILD', 0) - -# Get platform-specific name -osname = os.getenv('BMS_OSNAME', 'build') - -# Get architecture name -arch = subprocess.Popen(["uname"], stdout=subprocess.PIPE).communicate()[0].strip() - -# Setup initial environment -installdir = "%s/%s" %(halld_my, osname) -include = "%s/include" % (installdir) -bin = "%s/bin" % (installdir) -lib = "%s/lib" % (installdir) -plugins = "%s/plugins" % (installdir) -env = Environment( ENV = os.environ, # Bring in full environment, including PATH - CPPPATH = [include], - LIBPATH = ["%s/%s/lib" %(halld_home, osname)], # n.b. add HALLD_HOME here and prepend HALLD_MY below - variant_dir = ".%s" % (osname)) - -# Only add HALLD_MY library search path if it already exists -# since we'll get a warning otherwise -if (os.path.exists(lib)): env.PrependUnique(lib) - -# These are SBMS-specific variables (i.e. not default scons ones) -env.Replace(INSTALLDIR = installdir, - OSNAME = osname, - INCDIR = include, - BINDIR = bin, - LIBDIR = lib, - PLUGINSDIR = plugins, - ALL_SOURCES = [], # used so we can add generated sources - SHOWBUILD = SHOWBUILD, - COMMAND_LINE_TARGETS = COMMAND_LINE_TARGETS) - -# Use terse output unless otherwise specified -if SHOWBUILD==0: - env.Replace( CCCOMSTR = "Compiling [$SOURCE]", - CXXCOMSTR = "Compiling [$SOURCE]", - FORTRANPPCOMSTR = "Compiling [$SOURCE]", - FORTRANCOMSTR = "Compiling [$SOURCE]", - SHCCCOMSTR = "Compiling [$SOURCE]", - SHCXXCOMSTR = "Compiling [$SOURCE]", - LINKCOMSTR = "Linking [$TARGET]", - SHLINKCOMSTR = "Linking [$TARGET]", - INSTALLSTR = "Installing [$TARGET]", - ARCOMSTR = "Archiving [$TARGET]", - RANLIBCOMSTR = "Ranlib [$TARGET]") - - -# Get compiler from environment variables (if set) -env.Replace( CXX = os.getenv('CXX', 'g++'), - CC = os.getenv('CC' , 'gcc'), - FC = os.getenv('FC' , 'gfortran') ) - -# Add local directory, directories from HALLD_MY and HALLD_HOME to include search path -#env.PrependUnique(CPPPATH = ['#']) -env.PrependUnique(CPPPATH = ['%s/src' % halld_my, '%s/src/libraries' % halld_my, '%s/src/libraries/include' % halld_my]) -env.PrependUnique(CPPPATH = ['%s/src' % halld_home, '%s/src/libraries' % halld_home, '%s/src/libraries/include' % halld_home]) - -env.PrependUnique(CPPPATH = ['%s/%s/include' % (halld_my,osname)]) -env.PrependUnique(CPPPATH = ['%s/%s/include' % (halld_home,osname)]) - -# Turn on debug symbols and warnings -env.PrependUnique( CFLAGS = ['-g', '-fPIC', '-Wall']) -env.PrependUnique( CXXFLAGS = ['-g', '-fPIC', '-Wall']) -env.PrependUnique(FORTRANFLAGS = ['-g', '-fPIC', '-Wall']) - -env.PrependUnique( CXXFLAGS = ['-std=c++11']) - -# Apply any platform/architecture specific settings -sbms.ApplyPlatformSpecificSettings(env, arch) -sbms.ApplyPlatformSpecificSettings(env, osname) - -# Make plugin from source in this directory -sbms.AddDANA(env) -sbms.AddROOT(env) -sbms.plugin(env) - -# Make install target -env.Alias('install', installdir) - - diff --git a/src/plugins/Calibration/FCAL_Pi0TOF/JEventProcessor_FCAL_Pi0TOF.cc b/src/plugins/Calibration/FCAL_Pi0TOF/JEventProcessor_FCAL_Pi0TOF.cc index b40bdc14f9..b5728761e5 100644 --- a/src/plugins/Calibration/FCAL_Pi0TOF/JEventProcessor_FCAL_Pi0TOF.cc +++ b/src/plugins/Calibration/FCAL_Pi0TOF/JEventProcessor_FCAL_Pi0TOF.cc @@ -145,8 +145,8 @@ jerror_t JEventProcessor_FCAL_Pi0TOF::evnt(JEventLoop *loop, uint64_t eventnumbe loop->Get(locEventRFBunches); double locRFTime = locEventRFBunches.empty() ? 0.0 : locEventRFBunches[0]->dTime; - uint32_t locL1Trigger_fp = locL1Triggers.empty() ? 0.0 : locL1Triggers[0]->fp_trig_mask; - uint32_t locL1Trigger = locL1Triggers.empty() ? 0.0 : locL1Triggers[0]->trig_mask; + // uint32_t locL1Trigger_fp = locL1Triggers.empty() ? 0.0 : locL1Triggers[0]->fp_trig_mask; + // uint32_t locL1Trigger = locL1Triggers.empty() ? 0.0 : locL1Triggers[0]->trig_mask; int trig_bit[33]; if (locL1Triggers.size() > 0) { @@ -215,15 +215,15 @@ jerror_t JEventProcessor_FCAL_Pi0TOF::evnt(JEventLoop *loop, uint64_t eventnumbe int rings1 = (int) (radiusShower1 / (5 * k_cm)); int ringl1 = (int) (radiusShowerlog1 / (5 * k_cm)); - double frac_ring_thres = frac_thres_1_to_5; - if (ring1 >= 6) - frac_ring_thres = frac_thres_6_to_23; - double frac_rings_thres = frac_thres_1_to_5; - if (rings1 >= 6) - frac_rings_thres = frac_thres_6_to_23; - double frac_ringl_thres = frac_thres_1_to_5; - if (ringl1 >= 6) - frac_ringl_thres = frac_thres_6_to_23; + // double frac_ring_thres = frac_thres_1_to_5; + // if (ring1 >= 6) + // frac_ring_thres = frac_thres_6_to_23; + // double frac_rings_thres = frac_thres_1_to_5; + // if (rings1 >= 6) + // frac_rings_thres = frac_thres_6_to_23; + // double frac_ringl_thres = frac_thres_1_to_5; + // if (ringl1 >= 6) + // frac_ringl_thres = frac_thres_6_to_23; double frac1 = fcalCluster1->getEmax()/fcalCluster1->getEnergy(); double Eclust1 = fcalCluster1->getEnergy(); @@ -839,7 +839,7 @@ jerror_t JEventProcessor_FCAL_Pi0TOF::evnt(JEventLoop *loop, uint64_t eventnumbe //} if (DO_METHOD == 1 || DO_METHOD == 2) { - for (unsigned int k = 0; k < (int) locBeamPhotons.size(); k ++) { + for (unsigned int k = 0; k < (unsigned int) locBeamPhotons.size(); k ++) { const DBeamPhoton *ebeam = locBeamPhotons[k]; //double eb = ebeam->lorentzMomentum().E(); diff --git a/src/plugins/Calibration/HLDetectorTiming/HistMacro_TrackingTiming_CPP.C b/src/plugins/Calibration/HLDetectorTiming/HistMacro_TrackingTiming_CPP.C new file mode 100644 index 0000000000..10bfdd3905 --- /dev/null +++ b/src/plugins/Calibration/HLDetectorTiming/HistMacro_TrackingTiming_CPP.C @@ -0,0 +1,132 @@ +// hnamepath: /HLDetectorTiming/Physics Triggers/CDC/CDCHit time +// hnamepath: /HLDetectorTiming/Physics Triggers/FDC/FDCHit Cathode time +// hnamepath: /HLDetectorTiming/Physics Triggers/FDC/FDCHit Wire time +// hnamepath: /HLDetectorTiming/Physics Triggers/TRACKING/Earliest CDC Time Minus Matched BCAL Time +// hnamepath: /HLDetectorTiming/Physics Triggers/TRACKING/Earliest Flight-time Corrected CDC Time +// hnamepath: /HLDetectorTiming/Physics Triggers/TRACKING/Earliest Flight-time Corrected FDC Time +// hnamepath: /HLDetectorTiming/Physics Triggers/FDC/FDCHit Wire time vs. module +{ + //Goto Path + TDirectory *locDirectory = (TDirectory*)gDirectory->FindObjectAny("HLDetectorTiming"); + if(!locDirectory) + return; + locDirectory->cd(); + + //Get Histograms + TH1I* CDC_Timing = (TH1I*)gDirectory->Get("Physics Triggers/CDC/CDCHit time"); + TH1I* CDC_BCAL_Timing = (TH1I*)gDirectory->Get("Physics Triggers/TRACKING/Earliest CDC Time Minus Matched BCAL Time"); + TH1I* CDC_Earliest_Time = (TH1I*)gDirectory->Get("Physics Triggers/TRACKING/Earliest Flight-time Corrected CDC Time"); + TH1I* FDC_Strip_Timing = (TH1I*)gDirectory->Get("Physics Triggers/FDC/FDCHit Cathode time"); + TH1I* FDC_Wire_Timing = (TH1I*)gDirectory->Get("Physics Triggers/FDC/FDCHit Wire time"); + TH1I* FDC_Earliest_Time = (TH1I*)gDirectory->Get("Physics Triggers/TRACKING/Earliest Flight-time Corrected FDC Time"); + TH2I* FDC_Wire_Module_Time = (TH2I*)gDirectory->Get("Physics Triggers/FDC/FDCHit Wire time vs. module"); + + //Get/Make Canvas + TCanvas *locCanvas = NULL; + if(TVirtualPad::Pad() == NULL) + locCanvas = new TCanvas("TrackMatchedTiming", "TrackMatchedTiming", 1200, 800); //for testing + else + locCanvas = gPad->GetCanvas(); + locCanvas->Divide(3, 2); + + //Draw + locCanvas->cd(1); + gPad->SetTicks(); + gPad->SetGrid(); + if(CDC_Timing != NULL) + { + CDC_Timing->Draw(); + CDC_Timing->SetFillColor(kGray); + } + else{ + TPaveText *text = new TPaveText(0.1, 0.4, 0.9, 0.6); + text->AddText("No CDC Times in data"); + text->Draw(); + } + + locCanvas->cd(2); + gPad->SetTicks(); + gPad->SetGrid(); + if(CDC_Earliest_Time != NULL) + { + CDC_Earliest_Time->Draw(); + CDC_Earliest_Time->SetFillColor(kGray); + } + else{ + TPaveText *text = new TPaveText(0.1, 0.4, 0.9, 0.6); + text->AddText("No CDC tracks matced to BCAL/SC with reasonable FOM"); + text->Draw(); + } + + locCanvas->cd(3); + gPad->SetTicks(); + gPad->SetGrid(); + if(CDC_BCAL_Timing != NULL) + { + CDC_BCAL_Timing->Draw(); + CDC_BCAL_Timing->SetFillColor(kGray); + } + else{ + TPaveText *text = new TPaveText(0.1, 0.4, 0.9, 0.6); + text->AddText("No CDC tracks matced to SC with reasonable FOM"); + text->Draw(); + } + + locCanvas->cd(4); + gPad->SetTicks(); + gPad->SetGrid(); + if(FDC_Strip_Timing != NULL) + { + FDC_Strip_Timing->GetXaxis()->SetRangeUser(-150,350); + FDC_Strip_Timing->Draw(); + FDC_Strip_Timing->SetFillColor(kGray); + } + else{ + TPaveText *text = new TPaveText(0.1, 0.4, 0.9, 0.6); + text->AddText("No FDC Cathode Hit times"); + text->Draw(); + } + + locCanvas->cd(5); + gPad->SetTicks(); + gPad->SetGrid(); + if(FDC_Wire_Timing != NULL) + { + FDC_Wire_Timing->Draw(); + FDC_Wire_Timing->SetFillColor(kGray); + } + else{ + TPaveText *text = new TPaveText(0.1, 0.4, 0.9, 0.6); + text->AddText("No FDC Wire Hit times"); + text->Draw(); + } + + locCanvas->cd(6); + gPad->SetTicks(); + gPad->SetGrid(); + if(FDC_Wire_Module_Time != NULL) + { + gPad->SetMargin(0.1,0.1,0.15,0.1); + FDC_Wire_Module_Time->GetXaxis()->SetTitle(); + FDC_Wire_Module_Time->Draw("COLZ"); + } + else{ + TPaveText *text = new TPaveText(0.1, 0.4, 0.9, 0.6); + text->AddText("No FDC Wire Hit times"); + text->Draw(); + } + + /* + if(FDC_Earliest_Time != NULL) + { + FDC_Earliest_Time->Draw(); + FDC_Earliest_Time->SetFillColor(kGray); + } + else{ + TPaveText *text = new TPaveText(0.1, 0.4, 0.9, 0.6); + text->AddText("No FDC tracks matced to SC/TOF with reasonable FOM"); + text->Draw(); + } + */ +} + diff --git a/src/plugins/Calibration/TOF_calib/JEventProcessor_TOF_calib.cc b/src/plugins/Calibration/TOF_calib/JEventProcessor_TOF_calib.cc index c645f03e13..fa83ef9c79 100644 --- a/src/plugins/Calibration/TOF_calib/JEventProcessor_TOF_calib.cc +++ b/src/plugins/Calibration/TOF_calib/JEventProcessor_TOF_calib.cc @@ -233,6 +233,12 @@ jerror_t JEventProcessor_TOF_calib::evnt(JEventLoop *loop, uint64_t eventnumber) memset(th,0,locTOFGeometry->Get_NPlanes()*locTOFGeometry->Get_NBars()*locTOFGeometry->Get_NEnds()*4); for (unsigned int k=0; kQF & 0x40){ // pedestal determination failed! do not use this hit! + continue; + } + int plane = hit->plane; int end = hit->end; diff --git a/src/plugins/Utilities/SConscript b/src/plugins/Utilities/SConscript index 170b8db419..f3d712aa5e 100644 --- a/src/plugins/Utilities/SConscript +++ b/src/plugins/Utilities/SConscript @@ -7,12 +7,12 @@ Import('*') subdirs = ['danarest', 'evio_writer', 'evio-hddm'] subdirs.extend(['2trackskim', 'pi0bcalskim', 'pi0fcalskim', 'twogamma_fcal_skim', 'run_summary', 'track_skimmer', 'trackeff_missing','ps_skim', 'trigger_skims', 'bigevents_skim', 'coherent_peak_skim','exclusivepi0skim','randomtrigger_skim','pi0fcaltofskim','single_neutral_skim','compton_neutral_skim','eta2g_primexd_skim','eta6g_primexd_skim','etapi0_primexd_skim', 'cdcbcal_skim', 'cdc_goodtrack_skim','cdc_scan']) -subdirs.extend(['Pi0Finder', 'EventTagPi0','es_test','omega_skim','cal_high_energy_skim', 'syncskim', 'dedx_tree', 'phi_skim']) +subdirs.extend(['Pi0Finder', 'EventTagPi0','es_test','omega_skim','cal_high_energy_skim', 'syncskim', 'dedx_tree', 'phi_skim', 'npp_skim', 'cpp_skim']) SConscript(dirs=subdirs, exports='env osname', duplicate=0) # Optional targets optdirs = ['danahddm', 'dumpcandidates', 'dumpthrowns', 'l3bdt'] optdirs.extend(['merge_rawevents', 'syncskim', 'DAQ', 'TTab', 'rawevent']) -optdirs.extend(['cdc_emu', 'fmwpc_scan']) +optdirs.extend(['cdc_emu', 'fmwpc_scan', 'epem_ml_skim']) sbms.OptionallyBuild(env, optdirs) diff --git a/src/plugins/Utilities/cpp_skim/JEventProcessor_cpp_skim.cc b/src/plugins/Utilities/cpp_skim/JEventProcessor_cpp_skim.cc new file mode 100644 index 0000000000..fe0fdf3014 --- /dev/null +++ b/src/plugins/Utilities/cpp_skim/JEventProcessor_cpp_skim.cc @@ -0,0 +1,144 @@ +// $Id$ +// +// File: JEventProcessor_cpp_skim.cc +// Created: Tue Apr 16 10:14:04 EDT 2024 +// Creator: ilarin (on Linux ifarm1802.jlab.org 3.10.0-1160.102.1.el7.x86_64 x86_64) +// + +#include "JEventProcessor_cpp_skim.h" +using namespace jana; + + +// Routine used to create our JEventProcessor +#include +#include + + +extern "C"{ +void InitPlugin(JApplication *app){ + InitJANAPlugin(app); + app->AddProcessor(new JEventProcessor_cpp_skim()); +} +} // "C" + + +//------------------ +// JEventProcessor_cpp_skim (Constructor) +//------------------ +JEventProcessor_cpp_skim::JEventProcessor_cpp_skim() +{ + +} + +//------------------ +// ~JEventProcessor_cpp_skim (Destructor) +//------------------ +JEventProcessor_cpp_skim::~JEventProcessor_cpp_skim() +{ + +} + +//------------------ +// init +//------------------ +jerror_t JEventProcessor_cpp_skim::init(void) +{ + // This is called once at program startup. + + return NOERROR; +} + +//------------------ +// brun +//------------------ +jerror_t JEventProcessor_cpp_skim::brun(JEventLoop *eventLoop, int32_t runnumber) +{ + // This is called whenever the run number changes + num_epics_events = 0; + return NOERROR; +} + +//------------------ +// evnt +//------------------ +jerror_t JEventProcessor_cpp_skim::evnt(JEventLoop *loop, uint64_t eventnumber) +{ + // This is called for every event. Use of common resources like writing + // to a file or filling a histogram should be mutex protected. Using + // loop->Get(...) to get reconstructed objects (and thereby activating the + // reconstruction algorithm) should be done outside of any mutex lock + // since multiple threads may call this method at the same time. + // Here's an example: + // + // vector mydataclasses; + // loop->Get(mydataclasses); + // + // japp->RootFillLock(this); + // ... fill historgrams or trees ... + // japp->RootFillUnLock(this); + + + const DEventWriterEVIO* locEventWriterEVIO = NULL; + loop->GetSingle(locEventWriterEVIO); + if(locEventWriterEVIO == NULL) { + cerr << "from JEventProcessor_cpp_skim: locEventWriterEVIO is not available" << endl; + exit(1); + } + + if(loop->GetJEvent().GetStatusBit(kSTATUS_BOR_EVENT)) { // Begin of Run event + locEventWriterEVIO->Write_EVIOEvent(loop,"cpp_2c"); + return NOERROR; + } + + if(loop->GetJEvent().GetStatusBit(kSTATUS_EPICS_EVENT)) { // Epics event + if(num_epics_events<5) locEventWriterEVIO->Write_EVIOEvent(loop,"cpp_2c"); + ++num_epics_events; + return NOERROR; + } + + + vector tracks; + loop->Get(tracks); + + int npos = 0, nneg = 0; + for(unsigned int j=0; jmomentum().Mag(); + DVector3 origin = track->position(); + if(p<0.2 || p>15.0 || fabs(origin.Z())>90. || origin.Pt()>2.7) continue; + + double chi = track->chisq; + int ndof = track->Ndof; + double prob = TMath::Prob(chi,ndof); + if(prob<1.e-3) continue; + + double q = track->charge(); + if(q> 0.1) ++npos; + if(q<-0.1) ++nneg; + } + + if(npos*nneg) locEventWriterEVIO->Write_EVIOEvent(loop,"cpp_2c"); + + return NOERROR; +} + +//------------------ +// erun +//------------------ +jerror_t JEventProcessor_cpp_skim::erun(void) +{ + // This is called whenever the run number changes, before it is + // changed to give you a chance to clean up before processing + // events from the next run number. + return NOERROR; +} + +//------------------ +// fini +//------------------ +jerror_t JEventProcessor_cpp_skim::fini(void) +{ + // Called before program exit after event processing is finished. + return NOERROR; +} + diff --git a/src/plugins/Utilities/cpp_skim/JEventProcessor_cpp_skim.h b/src/plugins/Utilities/cpp_skim/JEventProcessor_cpp_skim.h new file mode 100644 index 0000000000..fd32cb9644 --- /dev/null +++ b/src/plugins/Utilities/cpp_skim/JEventProcessor_cpp_skim.h @@ -0,0 +1,43 @@ +// $Id$ +// +// File: JEventProcessor_cpp_skim.h +// Created: Tue Apr 16 10:14:04 EDT 2024 +// Creator: ilarin (on Linux ifarm1802.jlab.org 3.10.0-1160.102.1.el7.x86_64 x86_64) +// + +#ifndef _JEventProcessor_cpp_skim_ +#define _JEventProcessor_cpp_skim_ + +#include +#include "evio_writer/DEventWriterEVIO.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class JEventProcessor_cpp_skim:public jana::JEventProcessor{ + public: + JEventProcessor_cpp_skim(); + ~JEventProcessor_cpp_skim(); + const char* className(void) {return "JEventProcessor_cpp_skim";} + int num_epics_events; + + private: + jerror_t init(void); ///< Called once at program start. + jerror_t brun(jana::JEventLoop *eventLoop, int32_t runnumber); ///< Called everytime a new run number is detected. + jerror_t evnt(jana::JEventLoop *eventLoop, uint64_t eventnumber); ///< Called every event. + jerror_t erun(void); ///< Called everytime run number changes, provided brun has been called. + jerror_t fini(void); ///< Called after last event of last event source has been processed. + +}; + +#endif // _JEventProcessor_cpp_skim_ + diff --git a/src/plugins/Utilities/cpp_skim/SConscript b/src/plugins/Utilities/cpp_skim/SConscript new file mode 100644 index 0000000000..2d9eacdd33 --- /dev/null +++ b/src/plugins/Utilities/cpp_skim/SConscript @@ -0,0 +1,11 @@ +import sbms + +# get env object and clone it +Import('*') +env = env.Clone() + +sbms.AddJANA(env) +sbms.AddDANA(env) +sbms.AddROOT(env) +sbms.plugin(env) + diff --git a/src/plugins/Utilities/epem_ml_skim/JEventProcessor_epem_ml_skim.cc b/src/plugins/Utilities/epem_ml_skim/JEventProcessor_epem_ml_skim.cc new file mode 100644 index 0000000000..a4cf9379a3 --- /dev/null +++ b/src/plugins/Utilities/epem_ml_skim/JEventProcessor_epem_ml_skim.cc @@ -0,0 +1,265 @@ +// $Id$ +// +// File: JEventProcessor_epem_ml_skim.cc +// Created: Mon Jun 5 10:42:13 EDT 2023 +// Creator: acschick (on Linux ifarm1801.jlab.org 3.10.0-1160.90.1.el7.x86_64 x86_64) +// + +#include "JEventProcessor_epem_ml_skim.h" +using namespace jana; + + +// Routine used to create our JEventProcessor +#include +#include + +#include "FMWPC/DCPPEpEm.h" +#include "PID/DChargedTrack.h" +#include "TRACKING/DTrackTimeBased.h" + +#include +#include +#include +#include +#include "TProfile.h" +#include + + +static TH1D *htrack_mom; +static TH1D *htrack_mom_ok; +static TH1D *htrack_chi2; +static TH1D *htrack_chi2_ok; +static TH1D *htrack_theta; +static TH1D *htrack_theta_ok; +static TH1D *htrack_phi; +static TH1D *htrack_phi_ok; + + +static TH1D *hphiJT; +static TH1D *hinvmass_ee; +static TH1D *hFCALElasticity; + +static TH1D *hpimem_ML_classifier; +static TH1D *hpipep_ML_classifier; + + +extern "C"{ +void InitPlugin(JApplication *app){ + InitJANAPlugin(app); + app->AddProcessor(new JEventProcessor_epem_ml_skim()); +} +} // "C" + + +//------------------ +// JEventProcessor_epem_ml_skim (Constructor) +//------------------ +JEventProcessor_epem_ml_skim::JEventProcessor_epem_ml_skim() +{ + +} + +//------------------ +// ~JEventProcessor_epem_ml_skim (Destructor) +//------------------ +JEventProcessor_epem_ml_skim::~JEventProcessor_epem_ml_skim() +{ + +} + +//------------------ +// init +//------------------ +jerror_t JEventProcessor_epem_ml_skim::init(void) +{ + // This is called once at program startup. + + events_read = 0; + events_written = 0; + + TDirectory *main = gDirectory; + gDirectory->mkdir("epem_ml_skim")->cd(); + gDirectory->mkdir("Tracks")->cd(); + + htrack_mom = new TH1D("htrack_mom", ";p (GeV/c)", 200, 0, 10); + htrack_mom_ok = new TH1D("htrack_mom_ok", ";p (GeV/c)", 200, 0, 10); + htrack_chi2 = new TH1D("htrack_chi2","; #chi^{2}/NDF", 500, 0.0, 1.0); + htrack_chi2_ok = new TH1D("htrack_chi2_ok","; #chi^{2}/NDF", 500, 0.0, 1.0); + htrack_theta = new TH1D("htrack_theta","; Track #theta", 500, 0.0, 50); + htrack_theta_ok = new TH1D("htrack_theta_ok","; Track #theta", 500, 0.0, 50); + htrack_phi = new TH1D("htrack_phi"," ; Track #phi", 360, -180, 180); + htrack_phi_ok = new TH1D("htrack_phi_ok"," ; Track #phi", 360, -180, 180); + + gDirectory->cd("/epem_ml_skim"); + gDirectory->mkdir("Reconstructed")->cd(); + + hphiJT = new TH1D("hphiJT", "#vec{J}_{T}.#phi() ;#phi (degrees)", 90, -180, 180); + hinvmass_ee = new TH1D("hinvmass_ee", "Inv. Mass e^{+}e^{-} ;inv. mass (MeV/c^{2})", 234, 0.0, 1.0); + hFCALElasticity = new TH1D("hFCALElasticity", "; (E^{FCAL}_{1} + E^{FCAL}_{2})/E_{0}", 200, 0, 1.5); + + hpimem_ML_classifier = new TH1D("hpimem_ML_classifier", "ML model classifier for #pi^{-}/e^{-};classifier value", 200, 0.0, 1.0); + hpipep_ML_classifier = new TH1D("hpipep_ML_classifier", "ML model classifier for #pi^{+}/e^{+};classifier value", 200, 0.0, 1.0); + + main->cd(); + + return NOERROR; +} + +//------------------ +// brun +//------------------ +jerror_t JEventProcessor_epem_ml_skim::brun(JEventLoop *eventLoop, int32_t runnumber) +{ + // This is called whenever the run number changes + return NOERROR; +} + +//------------------ +// evnt +//------------------ +jerror_t JEventProcessor_epem_ml_skim::evnt(JEventLoop *loop, uint64_t eventnumber) +{ + // This is called for every event. Use of common resources like writing + // to a file or filling a histogram should be mutex protected. Using + // loop->Get(...) to get reconstructed objects (and thereby activating the + // reconstruction algorithm) should be done outside of any mutex lock + // since multiple threads may call this method at the same time. + // Here's an example: + // + // vector mydataclasses; + // loop->Get(mydataclasses); + // + // japp->RootFillLock(this); + // ... fill histograms or trees ... + // japp->RootFillUnLock(this); + + + + ++events_read; + // if( eventnumber%100 == 0){ + vector locCPPEpEms; + loop->Get(locCPPEpEms); + + // get charged tracks + vector chargedTrackVector; + loop->Get(chargedTrackVector); + + // get detector matches + const DDetectorMatches *detMatches = nullptr; + loop->GetSingle(detMatches); + + + for (unsigned int iTrack = 0; iTrack < chargedTrackVector.size(); iTrack++){ + const DChargedTrackHypothesis* bestHypothesis = chargedTrackVector[iTrack]->Get_BestTrackingFOM(); + // Cut very loosely on the track quality + auto thisTimeBasedTrack = bestHypothesis->Get_TrackTimeBased(); + + japp->RootFillLock(this); //ACQUIRE ROOT FILL LOCK + htrack_mom->Fill(thisTimeBasedTrack->pmag()); + htrack_chi2->Fill(thisTimeBasedTrack->FOM); + htrack_theta->Fill(thisTimeBasedTrack->momentum().Theta()*TMath::RadToDeg()); + htrack_phi->Fill(thisTimeBasedTrack->momentum().Phi()*TMath::RadToDeg()); + japp->RootFillUnLock(this); //RELEASE ROOT FILL LOCK + + // At least one match either to the Time-Of-Flight OR the FCAL + if ( !detMatches->Get_IsMatchedToDetector(thisTimeBasedTrack, SYS_TOF) && !detMatches->Get_IsMatchedToDetector(thisTimeBasedTrack, SYS_FCAL)){ + // cout << "no tracks matched to TOF or FCAL" << "\n"; + continue; + } + /* + // from CDC analysis + if (thisTimeBasedTrack->FOM < 1E-20){ + continue; + } + */ + // Cut on the reconstructed momentum below 1GeV, no curlers + /* + if(thisTimeBasedTrack->pmag() < 1.0){ + continue; + } + */ + japp->RootFillLock(this); //ACQUIRE ROOT FILL LOCK + htrack_mom_ok->Fill(thisTimeBasedTrack->pmag()); + htrack_chi2_ok->Fill(thisTimeBasedTrack->FOM); + htrack_theta_ok->Fill(thisTimeBasedTrack->momentum().Theta()*TMath::RadToDeg()); + htrack_phi_ok->Fill(thisTimeBasedTrack->momentum().Phi()*TMath::RadToDeg()); + japp->RootFillUnLock(this); //RELEASE ROOT FILL LOCK + } + + for( auto cppepem : locCPPEpEms ){ + auto &Ebeam = cppepem->Ebeam; + auto &weight = cppepem->weight; + auto &ep_v4 = cppepem->ep_v4; + auto &em_v4 = cppepem->em_v4; + auto &ep_FCALShower = cppepem->PositronShower; + auto &em_FCALShower = cppepem->ElectronShower; + double ep_FCALEnergy = (ep_FCALShower!=NULL)?ep_FCALShower->getEnergy():0.; + double em_FCALEnergy = (em_FCALShower!=NULL)?em_FCALShower->getEnergy():0.; + double FCALElasticity = (ep_FCALEnergy + em_FCALEnergy)/Ebeam; + double W_2e = (ep_v4 + em_v4).Mag(); + if(W_2e > 0.621){ + continue; + } + double ep_v3mag = ep_v4.Vect().Mag(); + double em_v3mag = em_v4.Vect().Mag(); + double JTx = ep_v4.X() * 2*em_v4.E()/(ep_v4.E() - ep_v3mag * cos(ep_v4.Theta())) + + em_v4.X() * 2*ep_v4.E()/(em_v4.E() - em_v3mag * cos(em_v4.Theta())); + + double JTy = ep_v4.Y() * 2*em_v4.E()/(ep_v4.E() - ep_v3mag * cos(ep_v4.Theta())) + + em_v4.Y() * 2*ep_v4.E()/(em_v4.E() - em_v3mag * cos(em_v4.Theta())); + + double Jphi = atan2(JTy, JTx)*180/acos(-1); + + double MLPClassifierMinus=cppepem->pimem_ML_classifier; + double MLPClassifierPlus=cppepem->pipep_ML_classifier; + + + if(MLPClassifierPlus < 0.8 || MLPClassifierMinus < 0.8){ + continue; + } + + japp->RootFillLock(this); + hpimem_ML_classifier->Fill(MLPClassifierMinus); + hpipep_ML_classifier->Fill(MLPClassifierPlus); + japp->RootFillUnLock(this); + + japp->RootFillLock(this); + hphiJT->Fill(Jphi, weight); + hFCALElasticity->Fill(FCALElasticity, weight); + hinvmass_ee->Fill(W_2e, weight); + japp->RootFillUnLock(this); + + + const DEventWriterEVIO* locEventWriterEVIO = NULL; + loop->GetSingle(locEventWriterEVIO); + locEventWriterEVIO->Write_EVIOEvent(loop,"epem_selection"); + ++events_written; + return NOERROR; + } + + // } //uncomment HERE for skimming modulo N, and the line containing if( eventnumber%100 == 0){ + + return NOERROR; +} + +//------------------ +// erun +//------------------ +jerror_t JEventProcessor_epem_ml_skim::erun(void) +{ + // This is called whenever the run number changes, before it is + // changed to give you a chance to clean up before processing + // events from the next run number. + return NOERROR; +} + +//------------------ +// fini +//------------------ +jerror_t JEventProcessor_epem_ml_skim::fini(void) +{ + // Called before program exit after event processing is finished. + jout << "read " << events_read << " events; written " << events_written << endl; + return NOERROR; +} + diff --git a/src/plugins/Utilities/epem_ml_skim/JEventProcessor_epem_ml_skim.h b/src/plugins/Utilities/epem_ml_skim/JEventProcessor_epem_ml_skim.h new file mode 100644 index 0000000000..1f6a53dba6 --- /dev/null +++ b/src/plugins/Utilities/epem_ml_skim/JEventProcessor_epem_ml_skim.h @@ -0,0 +1,42 @@ +// $Id$ +// +// File: JEventProcessor_epem_ml_skim.h +// Created: Mon Jun 5 10:42:13 EDT 2023 +// Creator: acschick (on Linux ifarm1801.jlab.org 3.10.0-1160.90.1.el7.x86_64 x86_64) +// + +#ifndef _JEventProcessor_epem_ml_skim_ +#define _JEventProcessor_epem_ml_skim_ + +#include +#include "evio_writer/DEventWriterEVIO.h" +#include "TLorentzRotation.h" + +#include +#include +#include +#include +#include +#include +#include +#include + + +class JEventProcessor_epem_ml_skim:public jana::JEventProcessor{ + public: + JEventProcessor_epem_ml_skim(); + ~JEventProcessor_epem_ml_skim(); + const char* className(void){return "JEventProcessor_epem_ml_skim";} + + private: + jerror_t init(void); ///< Called once at program start. + jerror_t brun(jana::JEventLoop *eventLoop, int32_t runnumber); ///< Called everytime a new run number is detected. + jerror_t evnt(jana::JEventLoop *eventLoop, uint64_t eventnumber); ///< Called every event. + jerror_t erun(void); ///< Called everytime run number changes, provided brun has been called. + jerror_t fini(void); ///< Called after last event of last event source has been processed. + + long int events_read, events_written; +}; + +#endif // _JEventProcessor_epem_ml_skim_ + diff --git a/src/plugins/Utilities/epem_ml_skim/SConscript b/src/plugins/Utilities/epem_ml_skim/SConscript new file mode 100644 index 0000000000..4b356ff7cd --- /dev/null +++ b/src/plugins/Utilities/epem_ml_skim/SConscript @@ -0,0 +1,9 @@ +import sbms + +# get env object and clone it +Import('*') +env = env.Clone() + +sbms.AddDANA(env) +sbms.AddROOT(env) +sbms.plugin(env) \ No newline at end of file diff --git a/src/plugins/Utilities/eta2g_primexd_skim/JEventProcessor_eta2g_primexd_skim.cc b/src/plugins/Utilities/eta2g_primexd_skim/JEventProcessor_eta2g_primexd_skim.cc index f12203b802..591cdf7b9f 100644 --- a/src/plugins/Utilities/eta2g_primexd_skim/JEventProcessor_eta2g_primexd_skim.cc +++ b/src/plugins/Utilities/eta2g_primexd_skim/JEventProcessor_eta2g_primexd_skim.cc @@ -156,6 +156,17 @@ jerror_t JEventProcessor_eta2g_primexd_skim::brun(JEventLoop *eventLoop, int32_t //------------------ jerror_t JEventProcessor_eta2g_primexd_skim::evnt(JEventLoop *loop, uint64_t eventnumber) { + /* + const DL1Trigger *trig = NULL; + try { + eventLoop->GetSingle(trig); + } catch (...) { + } + if (trig == NULL) { return NOERROR; } + + uint32_t trigmask = trig->trig_mask; + uint32_t fp_trigmask = trig->fp_trig_mask; + */ vector< const DFCALShower* > locFCALShowers; vector< const DBCALShower* > locBCALShowers; @@ -178,36 +189,39 @@ jerror_t JEventProcessor_eta2g_primexd_skim::evnt(JEventLoop *loop, uint64_t eve vector< const DTrackTimeBased* > locTrackTimeBased; loop->Get(locTrackTimeBased); - - vector < const DFCALShower * > matchedShowers; const DEventWriterEVIO* locEventWriterEVIO = NULL; loop->GetSingle(locEventWriterEVIO); + vector locFCALHits; + + loop->Get(locFCALHits); + // always write out BOR events if(loop->GetJEvent().GetStatusBit(kSTATUS_BOR_EVENT)) { //jout << "Found BOR!" << endl; - locEventWriterEVIO->Write_EVIOEvent( loop, "eta2g_primexd_skim" ); + locEventWriterEVIO->Write_EVIOEvent( loop, "eta2g-skim" ); return NOERROR; } // write out the first few EPICS events to save run number & other meta info if(loop->GetJEvent().GetStatusBit(kSTATUS_EPICS_EVENT) && (num_epics_events<5)) { //jout << "Found EPICS!" << endl; - locEventWriterEVIO->Write_EVIOEvent( loop, "eta2g_primexd_skim" ); + locEventWriterEVIO->Write_EVIOEvent( loop, "eta2g-skim" ); num_epics_events++; return NOERROR; } - vector< const JObject* > locObjectsToSave; + ////vector< const JObject* > locObjectsToSave; bool Candidate = false; DVector3 vertex; vertex.SetXYZ(m_beamSpotX, m_beamSpotY, m_targetZ); + /* for (unsigned int i = 0 ; i < tof_points.size(); i++) { locObjectsToSave.push_back(static_cast(tof_points[i])); } @@ -233,6 +247,7 @@ jerror_t JEventProcessor_eta2g_primexd_skim::evnt(JEventLoop *loop, uint64_t eve double kinfitVertexX = m_beamSpotX; double kinfitVertexY = m_beamSpotY; double kinfitVertexZ = m_targetZ; + //DVector3 vertex(m_beamSpotX, m_beamSpotY, m_targetZ); for (unsigned int i = 0 ; i < kinfitVertex.size(); i++) { if(i==0) locObjectsToSave.push_back(static_cast(kinfitVertex[0])); @@ -243,24 +258,41 @@ jerror_t JEventProcessor_eta2g_primexd_skim::evnt(JEventLoop *loop, uint64_t eve if(locEventRFBunches.size() > 0) { locObjectsToSave.push_back(static_cast(locEventRFBunches[0])); } + */ + + double FCAL_trg_Esum = 0; + + for (vector::const_iterator hit = locFCALHits.begin(); hit != locFCALHits.end(); hit++ ) { + if ((**hit).E > 0.150) + FCAL_trg_Esum += (**hit).E; + } DVector3 norm(0.0,0.0,-1); DVector3 pos,mom; Double_t BCAL_energy_sum = 0; Double_t CCAL_energy_sum = 0; + //Double_t FCAL_energy_sum = 0; for (unsigned int i=0; iE; BCAL_energy_sum += E; - } for (unsigned int i=0; iE; CCAL_energy_sum += E; - } - for (unsigned int i=0; igetEnergy(); + DVector3 position1 = locFCALShowers[i]->getPosition_log() - vertex; + double r1 = position1.Mag(); + double t1 = locFCALShowers[i]->getTime() - (r1 / TMath::C() * 1e7); + double p1x = e1 * sin(position1.Theta()) * cos(position1.Phi()); + double p1y = e1 * sin(position1.Theta()) * sin(position1.Phi()); + double p1z = e1 * cos(position1.Theta()); + TLorentzVector PhotonVec1(p1x, p1y, p1z, e1); + /* const DFCALShower *s1 = locFCALShowers[i]; vector associated_clusters1; @@ -272,8 +304,18 @@ jerror_t JEventProcessor_eta2g_primexd_skim::evnt(JEventLoop *loop, uint64_t eve Double_t E1 = s1->getEnergy(); Double_t t1 = s1->getTime(); TLorentzVector sh1_p(E1*dx1/R1, E1*dy1/R1, E1*dz1/R1, E1); + */ - for (unsigned int j=i+1; jgetEnergy(); + DVector3 position2 = locFCALShowers[j]->getPosition_log() - vertex; + double r2 = position2.Mag(); + double t2 = locFCALShowers[j]->getTime() - (r2 / TMath::C() * 1e7); + double p2x = e2 * sin(position2.Theta()) * cos(position2.Phi()); + double p2y = e2 * sin(position2.Theta()) * sin(position2.Phi()); + double p2z = e2 * cos(position2.Theta()); + TLorentzVector PhotonVec2(p2x, p2y, p2z, e2); + /* const DFCALShower *s2 = locFCALShowers[j]; vector associated_clusters2; @@ -287,26 +329,31 @@ jerror_t JEventProcessor_eta2g_primexd_skim::evnt(JEventLoop *loop, uint64_t eve TLorentzVector sh2_p(E2*dx2/R2, E2*dy2/R2, E2*dz2/R2, E2); TLorentzVector ptot = sh1_p+sh2_p; - Double_t inv_mass = ptot.M(); + */ + Double_t inv_mass = (PhotonVec1 + PhotonVec2).M(); //Candidate |= (E1 > 0.5 && E2 > 0.5 && s1->getPosition().Pt() > 20*k_cm && s2->getPosition().Pt() > 20*k_cm && (fabs (t1-t2) < 10) && (inv_mass<0.30) ) ; - Candidate |= (E1 > 0.1 && E2 > 0.1 && (fabs (t1-t2) < 15) && (inv_mass>0.340) ) ; + //Candidate |= (E1 > 0.1 && E2 > 0.1 && (fabs (t1-t2) < 15) && (inv_mass>0.380) /*&& BCAL_energy_sum < 0.1 && CCAL_energy_sum < 0.1*/) ; + //Candidate |= (e1 > 0.1 && e2 > 0.1 && (fabs (t1-t2) < 15) && (inv_mass>0.380) /*&& BCAL_energy_sum < 0.1 && CCAL_energy_sum < 0.1*/) ; //if(E1 > 0.5 && E2 > 0.5 && s1->getPosition().Pt() > 20*k_cm && s2->getPosition().Pt() > 20*k_cm && (fabs (t1-t2) < 10) && (inv_mass<0.30) ) { - if(E1 > 0.1 && E2 > 0.1 && (fabs (t1-t2) < 15) && (inv_mass>0.380) ) { - if(find(locObjectsToSave.begin(), locObjectsToSave.end(), locFCALShowers[i]) == locObjectsToSave.end()) + if(e1 > 0.1 && e2 > 0.1 && (fabs (t1-t2) < 25) && (inv_mass>0.330) ) { + /* + if(find(locObjectsToSave.begin(), locObjectsToSave.end(), locFCALShowers[i]) == locObjectsToSave.end()) locObjectsToSave.push_back(static_cast(locFCALShowers[i])); - if(find(locObjectsToSave.begin(), locObjectsToSave.end(), locFCALShowers[j]) == locObjectsToSave.end()) + if(find(locObjectsToSave.begin(), locObjectsToSave.end(), locFCALShowers[j]) == locObjectsToSave.end()) locObjectsToSave.push_back(static_cast(locFCALShowers[j])); + */ + Candidate = true; } } } - if( Candidate ){ + if( Candidate /*&& FCAL_trg_Esum > 5.0*/){ if( WRITE_EVIO ){ //locEventWriterEVIO->Write_EVIOEvent( loop, "eta2g_primexd_skim", locObjectsToSave ); - locEventWriterEVIO->Write_EVIOEvent( loop, "eta2g_primexd_skim"); + locEventWriterEVIO->Write_EVIOEvent( loop, "eta2g-skim"); } if( WRITE_HDDM ) { vector locEventWriterHDDMVector; diff --git a/src/plugins/Utilities/eta6g_primexd_skim/JEventProcessor_eta6g_skim.cc b/src/plugins/Utilities/eta6g_primexd_skim/JEventProcessor_eta6g_skim.cc index e1b0e54d29..f41278ecd7 100644 --- a/src/plugins/Utilities/eta6g_primexd_skim/JEventProcessor_eta6g_skim.cc +++ b/src/plugins/Utilities/eta6g_primexd_skim/JEventProcessor_eta6g_skim.cc @@ -166,9 +166,6 @@ jerror_t JEventProcessor_eta6g_skim::evnt(JEventLoop *loop, uint64_t eventnumber vector tof_points; vector< const DBeamPhoton* > locBeamPhotons; vector< const DSCHit* > locSCHit; - vector locFCALHits; - - loop->Get(locFCALHits); loop->Get(locFCALShowers); loop->Get(locBCALShowers); @@ -209,8 +206,10 @@ jerror_t JEventProcessor_eta6g_skim::evnt(JEventLoop *loop, uint64_t eventnumber vector< const JObject* > locObjectsToSave; - bool Candidate = false; + //bool Candidate = false; + vector locFCALHits; + loop->Get(locFCALHits); DVector3 vertex; vertex.SetXYZ(m_beamSpotX, m_beamSpotY, m_targetZ); for (unsigned int i = 0 ; i < tof_points.size(); i++) { @@ -253,7 +252,7 @@ jerror_t JEventProcessor_eta6g_skim::evnt(JEventLoop *loop, uint64_t eventnumber } vector PhotonList; PhotonList.clear(); - int photon_nb = locBCALShowers.size() + locFCALShowers.size() + locCCALShowers.size(); + //int photon_nb = locBCALShowers.size() + locFCALShowers.size() + locCCALShowers.size(); for (unsigned int i = 0; i < locBCALShowers.size(); i ++) { double e = locBCALShowers[i]->E; double x = locBCALShowers[i]->x - kinfitVertexX; @@ -284,7 +283,6 @@ jerror_t JEventProcessor_eta6g_skim::evnt(JEventLoop *loop, uint64_t eventnumber TLorentzVector PhotonVec(px, py, pz, e); if (e > 0.2) PhotonList.push_back(PhotonVec); } -/* for (unsigned int i = 0; i < locCCALShowers.size(); i ++) { double e = locCCALShowers[i]->E; double x = locCCALShowers[i]->x - kinfitVertexX; @@ -298,14 +296,29 @@ jerror_t JEventProcessor_eta6g_skim::evnt(JEventLoop *loop, uint64_t eventnumber double py = p * sin(vertex.Theta()) * sin(vertex.Phi()); double pz = p * cos(vertex.Theta()); TLorentzVector PhotonVec(px, py, pz, e); - PhotonList.push_back(PhotonVec); + //PhotonList.push_back(PhotonVec); } -*/ + + double FCAL_trg_Esum = 0; + + for (vector::const_iterator hit = locFCALHits.begin(); hit != locFCALHits.end(); hit++ ) { + if ((**hit).E > 0.150) + FCAL_trg_Esum += (**hit).E; + } + + int pi0_nb = 0; + for (unsigned int i = 0; i < PhotonList.size(); i ++) { + for (unsigned int j = i + 1; j < PhotonList.size(); j ++) { + Double_t inv_mass = (PhotonList[i] + PhotonList[j]).M(); + if (0.09 <= inv_mass && inv_mass <= 0.2) pi0_nb ++; + } + } + + /* Double_t bestChi2Eta = 1.0e30; Double_t bestChi2EtaPrim = 1.0e30; vector PhotonEta6gList;PhotonEta6gList.clear(); vector PhotonEtaprim6gList;PhotonEtaprim6gList.clear(); - /* Combined6g(PhotonList, bestChi2Eta, bestChi2EtaPrim, @@ -316,23 +329,17 @@ jerror_t JEventProcessor_eta6g_skim::evnt(JEventLoop *loop, uint64_t eventnumber bestChi2EtaPrim, PhotonEta6gList, PhotonEtaprim6gList); - */ - photon_nb = PhotonList.size(); - double FCAL_trg_Esum = 0; - - for (vector::const_iterator hit = locFCALHits.begin(); hit != locFCALHits.end(); hit++ ) { - if ((**hit).E > 0.150) - FCAL_trg_Esum += (**hit).E; - } - - Candidate |= ( (6 <= photon_nb && photon_nb <= 15) ); + Candidate |= ( (6 <= photon_nb && photon_nb <= 7) && (PhotonEta6gList.size() > 0 || PhotonEtaprim6gList.size() > 0) ); + */ + + - if ( FCAL_trg_Esum > 3.5 && PhotonList.size() >= 6 ) { + if (FCAL_trg_Esum > 3.5 && PhotonList.size() >= 6) { //cout <<"eta6g_skim"<Write_EVIOEvent( loop, "eta6g_skim", locObjectsToSave ); - locEventWriterEVIO->Write_EVIOEvent( loop, "eta6g_skim"); + locEventWriterEVIO->Write_EVIOEvent( loop, "eta6g-skim"); } if( WRITE_HDDM ) { vector locEventWriterHDDMVector; diff --git a/src/plugins/Utilities/evio_writer/DEventWriterEVIO.cc b/src/plugins/Utilities/evio_writer/DEventWriterEVIO.cc index 8c93238b1b..bf3a5ed4d7 100644 --- a/src/plugins/Utilities/evio_writer/DEventWriterEVIO.cc +++ b/src/plugins/Utilities/evio_writer/DEventWriterEVIO.cc @@ -204,8 +204,10 @@ bool DEventWriterEVIO::Write_EVIOEvent(JEventLoop* locEventLoop, string locOutpu //check to see if the EVIO file is open if(Get_EVIOOutputters().find(locOutputFileName) == Get_EVIOOutputters().end()) { //not open, open it - if(!Open_OutputFile(locEventLoop, locOutputFileName)) - return false; //failed to open + if(!Open_OutputFile(locEventLoop, locOutputFileName)){ + japp->Unlock("EVIOWriter"); // release lock + return false; //failed to open + } } //open: get handle, write event diff --git a/src/plugins/Utilities/npp_skim/JEventProcessor_npp_skim.cc b/src/plugins/Utilities/npp_skim/JEventProcessor_npp_skim.cc new file mode 100644 index 0000000000..c15c74c06e --- /dev/null +++ b/src/plugins/Utilities/npp_skim/JEventProcessor_npp_skim.cc @@ -0,0 +1,281 @@ +// $Id$ +// +// File: JEventProcessor_npp_skim.cc +// Created: Tue Apr 16 10:14:04 EDT 2024 +// Creator: gxproj2 (on Linux ifarm1802.jlab.org 3.10.0-1160.102.1.el7.x86_64 x86_64) +// + +#include "JEventProcessor_npp_skim.h" +using namespace jana; + + +// Routine used to create our JEventProcessor +#include +#include +extern "C"{ + void InitPlugin(JApplication *app){ + InitJANAPlugin(app); + app->AddProcessor(new JEventProcessor_npp_skim()); + } +} // "C" + + +//------------------ +// JEventProcessor_npp_skim (Constructor) +//------------------ +JEventProcessor_npp_skim::JEventProcessor_npp_skim() +{ + +} + +//------------------ +// ~JEventProcessor_npp_skim (Destructor) +//------------------ +JEventProcessor_npp_skim::~JEventProcessor_npp_skim() +{ + +} + +//------------------ +// init +//------------------ +jerror_t JEventProcessor_npp_skim::init(void) +{ + // This is called once at program startup. + + return NOERROR; +} + +//------------------ +// brun +//------------------ +jerror_t JEventProcessor_npp_skim::brun(JEventLoop *eventLoop, int32_t runnumber) +{ + // This is called whenever the run number changes + num_epics_events = 0; + return NOERROR; +} + +//------------------ +// evnt +//------------------ +jerror_t JEventProcessor_npp_skim::evnt(JEventLoop *loop, uint64_t eventnumber) +{ + // This is called for every event. Use of common resources like writing + // to a file or filling a histogram should be mutex protected. Using + // loop->Get(...) to get reconstructed objects (and thereby activating the + // reconstruction algorithm) should be done outside of any mutex lock + // since multiple threads may call this method at the same time. + // Here's an example: + // + // vector mydataclasses; + // loop->Get(mydataclasses); + // + // japp->RootFillLock(this); + // ... fill historgrams or trees ... + // japp->RootFillUnLock(this); + + + vector locFCALHits; + loop->Get(locFCALHits); + if(locFCALHits.size()>200) return NOERROR; + + vector< const DFCALShower* > locFCALShowers; + loop->Get(locFCALShowers); + + vector< const DBCALShower* > locBCALShowers; + loop->Get(locBCALShowers); + + const DEventWriterEVIO* locEventWriterEVIO = NULL; + loop->GetSingle(locEventWriterEVIO); + if(locEventWriterEVIO == NULL) { + cerr << "from JEventProcessor_npp_skim: locEventWriterEVIO is not available" << endl; + exit(1); + } + + if(loop->GetJEvent().GetStatusBit(kSTATUS_BOR_EVENT)) { // Begin of Run event + locEventWriterEVIO->Write_EVIOEvent(loop,"npp_2g"); + locEventWriterEVIO->Write_EVIOEvent(loop,"npp_2pi0"); + return NOERROR; + } + + if(loop->GetJEvent().GetStatusBit(kSTATUS_EPICS_EVENT)) { // Epics event + if(num_epics_events<5) { + locEventWriterEVIO->Write_EVIOEvent(loop,"npp_2g"); + locEventWriterEVIO->Write_EVIOEvent(loop,"npp_2pi0"); + } + ++num_epics_events; + return NOERROR; + } + + bool write_2g = false, write_2pi0 = false; + + for(unsigned int i=0; igetEnergy(); + x1 = s1->getPosition().X(); + y1 = s1->getPosition().Y(); + z1 = s1->getPosition().Z() - z_CPP_Target; + if(e1<0.3) continue; + } else { + const DBCALShower *s1 = locBCALShowers[i-locFCALShowers.size()]; + e1 = s1->E; + x1 = s1->x; + y1 = s1->y; + z1 = s1->z - z_CPP_Target; + if(e1<0.1) continue; + } + + for(unsigned int j=i+1; jgetEnergy(); + x2 = s2->getPosition().X(); + y2 = s2->getPosition().Y(); + z2 = s2->getPosition().Z() - z_CPP_Target; + if(e2<0.3) continue; + } else { + const DBCALShower *s2 = locBCALShowers[j-locFCALShowers.size()]; + e2 = s2->E; + x2 = s2->x; + y2 = s2->y; + z2 = s2->z - z_CPP_Target; + if(e2<0.1) continue; + } + + if(e1+e2<3.3) continue; + + double mraw= mgg(x1,y1,z1,e1,x2,y2,z2,e2); + + if(mraw<0.1) continue; + + write_2g = true; + + } + } + + + for(unsigned int i=0; igetEnergy(); + x1 = s1->getPosition().X(); + y1 = s1->getPosition().Y(); + z1 = s1->getPosition().Z() - z_CPP_Target; + if(e1<0.3) continue; + } else { + const DBCALShower *s1 = locBCALShowers[i-locFCALShowers.size()]; + e1 = s1->E; + x1 = s1->x; + y1 = s1->y; + z1 = s1->z - z_CPP_Target; + if(e1<0.1) continue; + } + + for(unsigned int j=i+1; jgetEnergy(); + x2 = s2->getPosition().X(); + y2 = s2->getPosition().Y(); + z2 = s2->getPosition().Z() - z_CPP_Target; + if(e2<0.3) continue; + } else { + const DBCALShower *s2 = locBCALShowers[j-locFCALShowers.size()]; + e2 = s2->E; + x2 = s2->x; + y2 = s2->y; + z2 = s2->z-1.; + if(e2<0.1) continue; + } + + if(e1+e2<0.5) continue; + double mraw12 = mgg(x1,y1,z1,e1,x2,y2,z2,e2); + if(mraw12<0.1) continue; + + for(unsigned int i2=i+1; i2i + if(i2==j) continue; + double x3, y3, z3, e3; + if(i2getEnergy(); + x3 = s3->getPosition().X(); + y3 = s3->getPosition().Y(); + z3 = s3->getPosition().Z() - z_CPP_Target; + if(e3<0.3) continue; + } else { + const DBCALShower *s3 = locBCALShowers[i2-locFCALShowers.size()]; + e3 = s3->E; + x3 = s3->x; + y3 = s3->y; + z3 = s3->z - z_CPP_Target; + if(e3<0.1) continue; + } + + for(unsigned int j2=i2+1; j2i2>i + if(j2==j) continue; + double x4, y4, z4, e4; + if(j2getEnergy(); + x4 = s4->getPosition().X(); + y4 = s4->getPosition().Y(); + z4 = s4->getPosition().Z() - z_CPP_Target; + if(e4<0.3) continue; + } else { + const DBCALShower *s4 = locBCALShowers[j2-locFCALShowers.size()]; + e4 = s4->E; + x4 = s4->x; + y4 = s4->y; + z4 = s4->z - z_CPP_Target; + if(e4<0.1) continue; + } + + if(e3+e4<0.5) continue; + if(e1+e2+e3+e4<3.5) continue; + + double mraw34 = mgg(x3,y3,z3,e3,x4,y4,z4,e4); + if(mraw34<0.1) continue; + + write_2pi0 = true; + } + } + } + } + + if(write_2g) { + locEventWriterEVIO->Write_EVIOEvent(loop,"npp_2g"); + } + + if(write_2pi0) { + locEventWriterEVIO->Write_EVIOEvent(loop,"npp_2pi0"); + } + + return NOERROR; +} + +//------------------ +// erun +//------------------ +jerror_t JEventProcessor_npp_skim::erun(void) +{ + // This is called whenever the run number changes, before it is + // changed to give you a chance to clean up before processing + // events from the next run number. + return NOERROR; +} + +//------------------ +// fini +//------------------ +jerror_t JEventProcessor_npp_skim::fini(void) +{ + // Called before program exit after event processing is finished. + return NOERROR; +} + diff --git a/src/plugins/Utilities/npp_skim/JEventProcessor_npp_skim.h b/src/plugins/Utilities/npp_skim/JEventProcessor_npp_skim.h new file mode 100644 index 0000000000..bf4cc1f31d --- /dev/null +++ b/src/plugins/Utilities/npp_skim/JEventProcessor_npp_skim.h @@ -0,0 +1,60 @@ +// $Id$ +// +// File: JEventProcessor_npp_skim.h +// Created: Tue Apr 16 10:14:04 EDT 2024 +// Creator: gxproj2 (on Linux ifarm1802.jlab.org 3.10.0-1160.102.1.el7.x86_64 x86_64) +// + +#ifndef _JEventProcessor_npp_skim_ +#define _JEventProcessor_npp_skim_ + +#include +#include "evio_writer/DEventWriterEVIO.h" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +class JEventProcessor_npp_skim:public jana::JEventProcessor{ + public: + JEventProcessor_npp_skim(); + ~JEventProcessor_npp_skim(); + const char* className(void){return "JEventProcessor_npp_skim";} + int num_epics_events; + + private: + jerror_t init(void); ///< Called once at program start. + jerror_t brun(jana::JEventLoop *eventLoop, int32_t runnumber); ///< Called everytime a new run number is detected. + jerror_t evnt(jana::JEventLoop *eventLoop, uint64_t eventnumber); ///< Called every event. + jerror_t erun(void); ///< Called everytime run number changes, provided brun has been called. + jerror_t fini(void); ///< Called after last event of last event source has been processed. + const double z_CPP_Target = 1.; + + double mgg(double x1,double y1, double z1, double e1,double x2,double y2, double z2, double e2) { + double r1 = sqrt(x1*x1+y1*y1+z1*z1); + double r2 = sqrt(x2*x2+y2*y2+z2*z2); + double px1= x1/r1*e1; + double py1= y1/r1*e1; + double pz1= z1/r1*e1; + double px2= x2/r2*e2; + double py2= y2/r2*e2; + double pz2= z2/r2*e2; + + double m2 = e1*e2-px1*px2-py1*py2-pz1*pz2; + m2 = sqrt(2.*m2); + + return m2; + } + +}; + +#endif // _JEventProcessor_npp_skim_ + diff --git a/src/plugins/Utilities/npp_skim/SConscript b/src/plugins/Utilities/npp_skim/SConscript new file mode 100644 index 0000000000..2d9eacdd33 --- /dev/null +++ b/src/plugins/Utilities/npp_skim/SConscript @@ -0,0 +1,11 @@ +import sbms + +# get env object and clone it +Import('*') +env = env.Clone() + +sbms.AddJANA(env) +sbms.AddDANA(env) +sbms.AddROOT(env) +sbms.plugin(env) + diff --git a/src/plugins/monitoring/BCAL_online/bcal_hit_occupancy.C b/src/plugins/monitoring/BCAL_online/bcal_hit_occupancy.C new file mode 100644 index 0000000000..c198a1e7a5 --- /dev/null +++ b/src/plugins/monitoring/BCAL_online/bcal_hit_occupancy.C @@ -0,0 +1,48 @@ + +// hnamepath: /bcal/bcal_fadc_occ +// hnamepath: /bcal/bcal_tdc_occ +// + +{ + TDirectory *savedir = gDirectory; + TDirectory *dir = (TDirectory*)gDirectory->FindObjectAny("bcal"); + if(dir) dir->cd(); + + TH2I *bcal_adc_occ = (TH2I*)gDirectory->FindObjectAny("bcal_fadc_occ"); + TH2I *bcal_tdc_occ = (TH2I*)gDirectory->FindObjectAny("bcal_tdc_occ"); + + // Just for testing + if(gPad == NULL){ + TCanvas *c1 = new TCanvas("c1"); + c1->cd(0); + c1->Draw(); + c1->Update(); + } + if(!gPad) {savedir->cd(); return;} + + TCanvas *c1 = gPad->GetCanvas(); + c1->cd(0); + + c1->Divide(2,1); + + TVirtualPad *pad1 = c1->cd(1); + pad1->SetTicks(); + pad1->SetLeftMargin(0.15); + pad1->SetRightMargin(0.15); + if(bcal_adc_occ){ + bcal_adc_occ->SetStats(0); + bcal_adc_occ->Draw("colz"); + } + + TVirtualPad *pad2 = c1->cd(2); + pad2->SetTicks(); + pad2->SetLeftMargin(0.15); + pad2->SetRightMargin(0.15); + if(bcal_tdc_occ){ + bcal_tdc_occ->SetStats(0); + bcal_tdc_occ->Draw("colz"); + } + +} + + diff --git a/src/plugins/monitoring/CDC_Efficiency/JEventProcessor_CDC_Efficiency.cc b/src/plugins/monitoring/CDC_Efficiency/JEventProcessor_CDC_Efficiency.cc index b0d7055679..c87928e615 100644 --- a/src/plugins/monitoring/CDC_Efficiency/JEventProcessor_CDC_Efficiency.cc +++ b/src/plugins/monitoring/CDC_Efficiency/JEventProcessor_CDC_Efficiency.cc @@ -164,10 +164,96 @@ jerror_t JEventProcessor_CDC_Efficiency::init(void) gDirectory->cd("/CDC_Efficiency"); gDirectory->mkdir("Track_Quality")->cd(); + hChi2OverNDF = new TH1I("hChi2OverNDF","hChi2OverNDF", 500, 0.0, 1.0); ChargeVsTrackLength = new TH2I("ChargeVsTrackLength", "ChargeVsTrackLength", 1000, 0, 8.0, 2000, 0, 5000000); hResVsT = new TH2I("hResVsT","Tracking Residual (Biased) Vs Drift Time; Drift Time [ns]; Residual [cm]", 500, 0.0, 700.0, 1000, -0.5, 0.5); - main->cd(); + + gDirectory->cd("/CDC_Efficiency"); + gDirectory->mkdir("Offline")->cd(); + + hExpectedHitsVsPathLength = new TH1F("Expected Hits Vs Path Length", "Expected Hits", 100, 0 , 4.0); + hExpectedHitsVsDOCA = new TH1F("Expected Hits Vs DOCA", "Expected Hits", 100, 0 , 0.78); + hExpectedHitsVsTrackingFOM = new TH1F("Expected Hits Vs Tracking FOM", "Expected Hits", 100, 0 , 1.0); + hExpectedHitsVsTheta = new TH1F("Expected Hits Vs theta", "Expected Hits", 100, 0, 180); + hExpectedHitsVsMom = new TH1F("Expected Hits Vs p", "Expected Hits", 100, 0 , 4.0); + hExpectedHitsVsDelta = new TH1F("Expected Hits Vs delta", "Expected Hits", 100, -0.3 , 0.3); + hExpectedHitsMomVsTheta = new TH2F("Expected hits p Vs Theta", "Expected Hits", 100, 0, 180, 100, 0 , 4.0); + hExpectedHitsVsN = new TH1F("Expected Hits Vs N", "Expected Hits", 3522, 0.5, 3522.5); + + hMeasuredHitsVsPathLength = new TH1F("Measured Hits Vs Path Length", "Measured Hits", 100, 0 , 4.0); + hMeasuredHitsVsDOCA = new TH1F("Measured Hits Vs DOCA", "Measured Hits", 100, 0 , 0.78); + hMeasuredHitsVsTrackingFOM = new TH1F("Measured Hits Vs Tracking FOM", "Measured Hits", 100, 0 , 1.0); + hMeasuredHitsVsTheta = new TH1F("Measured Hits Vs theta", "Measured Hits", 100, 0, 180); + hMeasuredHitsVsMom = new TH1F("Measured Hits Vs p", "Measured Hits", 100, 0 , 4.0); + hMeasuredHitsVsDelta = new TH1F("Measured Hits Vs delta", "Measured Hits", 100, -0.3 , 0.3); + hMeasuredHitsMomVsTheta = new TH2F("Measured hits p Vs Theta", "Measured Hits", 100, 0, 180, 100, 0 , 4.0); + hMeasuredHitsVsN = new TH1F("Measured Hits Vs N", "Measured Hits", 3522, 0.5, 3522.5); + + if (FILL_DEDX_HISTOS) { + hMeasuredHitsWithDEDxVsPathLength = new TH1F("Measured Hits with dE/dx info Vs Path Length", "Measured Hits with dE/dx info", 100, 0 , 4.0); + hMeasuredHitsWithDEDxVsDOCA = new TH1F("Measured Hits with dE/dx info Vs DOCA", "Measured Hits with dE/dx info", 100, 0 , 0.78); + hMeasuredHitsWithDEDxVsTrackingFOM = new TH1F("Measured Hits with dE/dx info Vs Tracking FOM", "Measured Hits with dE/dx info", 100, 0 , 1.0); + hMeasuredHitsWithDEDxVsTheta = new TH1F("Measured Hits with dE/dx info Vs theta", "Measured Hits with dE/dx info", 100, 0, 180); + hMeasuredHitsWithDEDxVsMom = new TH1F("Measured Hits with dE/dx info Vs p", "Measured Hits with dE/dx info", 100, 0 , 4.0); + hMeasuredHitsWithDEDxVsDelta = new TH1F("Measured Hits with dE/dx info Vs delta", "Measured Hits with dE/dx info", 100, -0.3 , 0.3); + hMeasuredHitsWithDEDxMomVsTheta = new TH2F("Measured Hits with dE/dx info p Vs Theta", "Measured Hits with dE/dx info", 100, 0, 180, 100, 0 , 4.0); + hMeasuredHitsWithDEDxVsN = new TH1F("Measured Hits with dE/dx info Vs N", "Measured Hits with dE/dx info", 3522, 0.5, 3522.5); + } + + gDirectory->cd("/CDC_Efficiency"); + gDirectory->mkdir("Online")->cd(); + + hEfficiencyVsPathLength = new TProfile("Efficiency Vs Path Length", "Efficiency", 100, 0 , 4.0); + hEfficiencyVsDOCA = new TProfile("Efficiency Vs DOCA", "Efficiency", 100, 0 , 0.78); + hEfficiencyVsTrackingFOM = new TProfile("Efficiency Vs Tracking FOM", "Efficiency", 100, 0 , 1.0); + hEfficiencyVsTheta = new TProfile("Efficiency Vs theta", "Efficiency", 100, 0, 180); + hEfficiencyVsMom = new TProfile("Efficiency Vs p", "Efficiency", 100, 0 , 4.0); + hEfficiencyVsDelta = new TProfile("Efficiency Vs delta", "Efficiency", 100, -0.3 , 0.3); + hEfficiencyVsN = new TProfile("Efficiency Vs N", "Efficiency", 3522, 0.5, 3522.5); + + if (FILL_DEDX_HISTOS) { + hEfficiencyWithDEDxVsPathLength = new TProfile("Efficiency (with dE/dx) Vs Path Length", "Efficiency (with dE/dx) ", 100, 0 , 4.0); + hEfficiencyWithDEDxVsDOCA = new TProfile("Efficiency (with dE/dx) Vs DOCA", "Efficiency (with dE/dx) ", 100, 0 , 0.78); + hEfficiencyWithDEDxVsTrackingFOM = new TProfile("Efficiency (with dE/dx) Vs Tracking FOM", "Efficiency (with dE/dx) ", 100, 0 , 1.0); + hEfficiencyWithDEDxVsTheta = new TProfile("Efficiency (with dE/dx) Vs theta", "Efficiency (with dE/dx) ", 100, 0, 180); + hEfficiencyWithDEDxVsMom = new TProfile("Efficiency (with dE/dx) Vs p", "Efficiency (with dE/dx) ", 100, 0 , 4.0); + hEfficiencyWithDEDxVsDelta = new TProfile("Efficiency (with dE/dx) Vs delta", "Efficiency (with dE/dx) ", 100, -0.3 , 0.3); + hEfficiencyWithDEDxVsN = new TProfile("Efficiency (with dE/dx) Vs N", "Efficiency (with dE/dx) ", 3522, 0.5, 3522.5); + } + + int ROCnums[] = {25, 26, 27, 28}; + hEfficiencyVsChannel = new TProfile("Efficiency Vs Channel Number", "Efficiency; Channel Number; Efficiency", 73, -0.5 , 72.5); + for(int i=0; i<4; i++) { + char name [200]; + sprintf(name, "Slot Efficiency ROCID %.2i", ROCnums[i]); + hEfficiencyVsSlotROC[ROCnums[i]] = new TProfile(name, "Efficiency; Slot Number; Efficiency", 21, -0.5 , 20.5); + sprintf(name, "Channel Efficiency ROCID %.2i", ROCnums[i]); + hEfficiencyVsChannelROC[ROCnums[i]] = new TProfile(name, "Efficiency; Channel; Efficiency", 1501, 299.5 , 1800.5); + } + + if (FILL_DEDX_HISTOS) { + hEfficiencyWithDEDxVsChannel = new TProfile("Efficiency (with dE/dx) Vs Channel Number", "Efficiency; Channel Number; Efficiency", 73, -0.5 , 72.5); + for(int i=0; i<4; i++) { + char name [200]; + sprintf(name, "Slot Efficiency (with dE/dx) ROCID %.2i", ROCnums[i]); + hEfficiencyWithDEDxVsSlotROC[ROCnums[i]] = new TProfile(name, "Efficiency; Slot Number; Efficiency", 21, -0.5 , 20.5); + sprintf(name, "Channel Efficiency (with dE/dx) ROCID %.2i", ROCnums[i]); + hEfficiencyWithDEDxVsChannelROC[ROCnums[i]] = new TProfile(name, "Efficiency; Channel; Efficiency", 1501, 299.5 , 1800.5); + } + } + + hEfficiencyMomVsTheta = new TProfile2D("Efficiency p Vs Theta", "Efficiency; Track #Theta [deg]; Momentum [GeV]", 100, 0, 180, 100, 0 , 4.0); + hEfficiencyDistanceVsDelta = new TProfile2D("Efficiency distance Vs delta", "Efficiency;#delta [cm]; DOCA [cm]", 100, -0.3, 0.3, 100, 0 , 1.2); + hEfficiencyZVsDelta = new TProfile2D("Efficiency z Vs delta", "Efficiency;#delta [cm]; z [cm] (CDC local coordinates)", 100, -0.3, 0.3, 150, -75 , 75); + + if (FILL_DEDX_HISTOS) { + hEfficiencyWithDEDxMomVsTheta = new TProfile2D("Efficiency (with dE/dx) p Vs Theta", "Efficiency (with dE/dx); Track #Theta [deg]; Momentum [GeV]", 100, 0, 180, 100, 0 , 4.0); + hEfficiencyWithDEDxDistanceVsDelta = new TProfile2D("Efficiency (with dE/dx) distance Vs delta", "Efficiency (with dE/dx);#delta [cm]; DOCA [cm]", 100, -0.3, 0.3, 100, 0 , 1.2); + hEfficiencyWithDEDxZVsDelta = new TProfile2D("Efficiency (with dE/dx) z Vs delta", "Efficiency (with dE/dx);#delta [cm]; z [cm] (CDC local coordinates)", 100, -0.3, 0.3, 150, -75 , 75); + } + + main->cd(); dTargetCenterZ = 65.0; dTargetLength = 30.0; @@ -452,16 +538,19 @@ void JEventProcessor_CDC_Efficiency::Fill_Efficiency_Histos(unsigned int ringNum //FILL EXPECTED HISTOGRAMS double dx = pid_algorithm->CalcdXHit(mom,pos,wire); double locTheta = thisTimeBasedTrack->momentum().Theta()*TMath::RadToDeg(); - Fill1DHistogram("CDC_Efficiency", "Offline", "Expected Hits Vs Path Length", dx, "Expected Hits", 100, 0 , 4.0); - Fill1DHistogram("CDC_Efficiency", "Offline", "Expected Hits Vs DOCA", distanceToWire, "Expected Hits", 100, 0 , 0.78); - Fill1DHistogram("CDC_Efficiency", "Offline", "Expected Hits Vs Tracking FOM", thisTimeBasedTrack->FOM, "Expected Hits", 100, 0 , 1.0); - Fill1DHistogram("CDC_Efficiency", "Offline", "Expected Hits Vs theta", locTheta, "Expected Hits", 100, 0, 180); - Fill1DHistogram("CDC_Efficiency", "Offline", "Expected Hits Vs p", thisTimeBasedTrack->pmag(), "Expected Hits", 100, 0 , 4.0); - Fill1DHistogram("CDC_Efficiency", "Offline", "Expected Hits Vs delta", delta, "Expected Hits", 100, -0.3 , 0.3); - Fill2DHistogram("CDC_Efficiency", "Offline", "Expected hits p Vs Theta", locTheta, thisTimeBasedTrack->pmag(), "Expected Hits", 100, 0, 180, 100, 0 , 4.0); - //expected hits by straw number - Fill1DHistogram("CDC_Efficiency", "Offline", "Expected Hits Vs N", Nstraws_previous[ringNum-1]+wireNum, "Expected Hits", 3522, 0.5, 3522.5); - + + japp->RootFillLock(this); //ACQUIRE ROOT FILL LOCK + hExpectedHitsVsPathLength->Fill(dx); + hExpectedHitsVsDOCA->Fill(distanceToWire); + hExpectedHitsVsTrackingFOM->Fill(thisTimeBasedTrack->FOM); + hExpectedHitsVsTheta->Fill(locTheta); + hExpectedHitsVsMom->Fill(thisTimeBasedTrack->pmag()); + hExpectedHitsVsDelta->Fill(delta); + hExpectedHitsMomVsTheta->Fill(locTheta, thisTimeBasedTrack->pmag()); + hExpectedHitsVsN->Fill(Nstraws_previous[ringNum-1]+wireNum); //expected hits by straw number + japp->RootFillUnLock(this); //RELEASE ROOT FILL LOCK + + // look for a CDC hit match // We need a backwards map from ring/straw to flash channel. Unfortunately there is no easy way // Will construct the map manually @@ -491,91 +580,83 @@ void JEventProcessor_CDC_Efficiency::Fill_Efficiency_Histos(unsigned int ringNum ChannelFromRingStraw[ringNum - 1][wireNum - 1] = thisPulse->channel; } + japp->RootFillLock(this); //ACQUIRE ROOT FILL LOCK - - Fill1DHistogram("CDC_Efficiency", "Offline", "Measured Hits Vs Path Length", dx, "Measured Hits", 100, 0 , 4.0); - Fill1DHistogram("CDC_Efficiency", "Offline", "Measured Hits Vs DOCA", distanceToWire, "Measured Hits", 100, 0 , 0.78); - Fill1DHistogram("CDC_Efficiency", "Offline", "Measured Hits Vs Tracking FOM", thisTimeBasedTrack->FOM, "Measured Hits", 100, 0 , 1.0); - Fill1DHistogram("CDC_Efficiency", "Offline", "Measured Hits Vs theta", locTheta, "Measured Hits", 100, 0, 180); - Fill1DHistogram("CDC_Efficiency", "Offline", "Measured Hits Vs p", thisTimeBasedTrack->pmag(), "Measured Hits", 100, 0 , 4.0); - Fill1DHistogram("CDC_Efficiency", "Offline", "Measured Hits Vs delta", delta, "Measured Hits", 100, -0.3 , 0.3); - Fill2DHistogram("CDC_Efficiency", "Offline", "Measured hits p Vs Theta", locTheta, thisTimeBasedTrack->pmag(), "Measured Hits", 100, 0, 180, 100, 0 , 4.0); - - //expected hits by straw number - Fill1DHistogram("CDC_Efficiency", "Offline", "Measured Hits Vs N", Nstraws_previous[ringNum-1]+wireNum, "Measured Hits", 3522, 0.5 , 3522.5); + hMeasuredHitsVsPathLength->Fill(dx); + hMeasuredHitsVsDOCA->Fill(distanceToWire); + hMeasuredHitsVsTrackingFOM->Fill(thisTimeBasedTrack->FOM); + hMeasuredHitsVsTheta->Fill(locTheta); + hMeasuredHitsVsMom->Fill(thisTimeBasedTrack->pmag()); + hMeasuredHitsVsDelta->Fill(delta); + hMeasuredHitsMomVsTheta->Fill(locTheta, thisTimeBasedTrack->pmag()); + hMeasuredHitsVsN->Fill(Nstraws_previous[ringNum-1]+wireNum); //expected hits by straw number if (FILL_DEDX_HISTOS) { if (foundHitWithdEdx) { // fill histos for which hit contributes to dE/dx - Fill1DHistogram("CDC_Efficiency", "Offline", "Measured Hits with dE/dx info Vs Path Length", dx, "Measured Hits with dE/dx info", 100, 0 , 4.0); - Fill1DHistogram("CDC_Efficiency", "Offline", "Measured Hits with dE/dx info Vs DOCA", distanceToWire, "Measured Hits with dE/dx info", 100, 0 , 0.78); - Fill1DHistogram("CDC_Efficiency", "Offline", "Measured Hits with dE/dx info Vs Tracking FOM", thisTimeBasedTrack->FOM, "Measured Hits with dE/dx info", 100, 0 , 1.0); - Fill1DHistogram("CDC_Efficiency", "Offline", "Measured Hits with dE/dx info Vs theta", locTheta, "Measured Hits with dE/dx info", 100, 0, 180); - Fill1DHistogram("CDC_Efficiency", "Offline", "Measured Hits with dE/dx info Vs p", thisTimeBasedTrack->pmag(), "Measured Hits with dE/dx info", 100, 0 , 4.0); - Fill1DHistogram("CDC_Efficiency", "Offline", "Measured Hits with dE/dx info Vs delta", delta, "Measured Hits with dE/dx info", 100, -0.3 , 0.3); - Fill2DHistogram("CDC_Efficiency", "Offline", "Measured Hits with dE/dx info p Vs Theta", locTheta, thisTimeBasedTrack->pmag(), "Measured Hits with dE/dx info", 100, 0, 180, 100, 0 , 4.0); - - //expected hits by straw number - Fill1DHistogram("CDC_Efficiency", "Offline", "Measured Hits with dE/dx info Vs N", Nstraws_previous[ringNum-1]+wireNum, "Measured Hits with dE/dx info", 3522, 0.5 , 3522.5); + hMeasuredHitsWithDEDxVsPathLength->Fill(dx); + hMeasuredHitsWithDEDxVsDOCA->Fill(distanceToWire); + hMeasuredHitsWithDEDxVsTrackingFOM->Fill(thisTimeBasedTrack->FOM); + hMeasuredHitsWithDEDxVsTheta->Fill(locTheta); + hMeasuredHitsWithDEDxVsMom->Fill(thisTimeBasedTrack->pmag()); + hMeasuredHitsWithDEDxVsDelta->Fill(delta); + hMeasuredHitsWithDEDxMomVsTheta->Fill(locTheta, thisTimeBasedTrack->pmag()); + hMeasuredHitsWithDEDxVsN->Fill(Nstraws_previous[ringNum-1]+wireNum); //expected hits by straw number } } + japp->RootFillUnLock(this); //RELEASE ROOT FILL LOCK } + japp->RootFillLock(this); //ACQUIRE ROOT FILL LOCK + //FILL PROFILES: BASED ON FOUND OR NOT - Fill1DProfile("CDC_Efficiency", "Online", "Efficiency Vs Path Length", dx,foundHit, "Efficiency; dx [cm]; Efficiency", 100, 0 , 4.0); - Fill1DProfile("CDC_Efficiency", "Online", "Efficiency Vs DOCA", distanceToWire,foundHit, "Efficiency; DOCA [cm]; Efficiency", 100, 0 , 0.78); - Fill1DProfile("CDC_Efficiency", "Online", "Efficiency Vs Tracking FOM", thisTimeBasedTrack->FOM,foundHit, "Efficiency; Tracking FOM; Efficiency", 100, 0 , 1.0); - Fill1DProfile("CDC_Efficiency", "Online", "Efficiency Vs theta", locTheta,foundHit, "Efficiency; Track #Theta [deg]; Efficiency", 100, 0, 180); - Fill1DProfile("CDC_Efficiency", "Online", "Efficiency Vs p", thisTimeBasedTrack->pmag(),foundHit, "Efficiency; Momentum [GeV]; Efficiency", 100, 0 , 4.0); - Fill1DProfile("CDC_Efficiency", "Online", "Efficiency Vs delta", delta,foundHit, "Efficiency; #delta [cm]; Efficiency", 100, -0.3 , 0.3); + hEfficiencyVsPathLength->Fill(dx,foundHit); + hEfficiencyVsDOCA->Fill(distanceToWire,foundHit); + hEfficiencyVsTrackingFOM->Fill(thisTimeBasedTrack->FOM,foundHit); + hEfficiencyVsTheta->Fill(locTheta,foundHit); + hEfficiencyVsMom->Fill(thisTimeBasedTrack->pmag(),foundHit); + hEfficiencyVsDelta->Fill(delta,foundHit); + hEfficiencyVsN->Fill(Nstraws_previous[ringNum-1]+wireNum,foundHit); //expected hits by straw number - //expected hits by straw number - Fill1DProfile("CDC_Efficiency", "Online", "Efficiency Vs N", Nstraws_previous[ringNum-1]+wireNum, foundHit,"Efficiency; N; Efficiency", 3522, 0.5 , 3522.5); // repeat for hits contributing to dE/dx if (FILL_DEDX_HISTOS) { - Fill1DProfile("CDC_Efficiency", "Online", "Efficiency (with dE/dx) Vs Path Length", dx,foundHitWithdEdx, "Efficiency (with dE/dx); dx [cm]; Efficiency (with dE/dx)", 100, 0 , 4.0); - Fill1DProfile("CDC_Efficiency", "Online", "Efficiency (with dE/dx) Vs DOCA", distanceToWire,foundHitWithdEdx, "Efficiency (with dE/dx); DOCA [cm]; Efficiency (with dE/dx)", 100, 0 , 0.78); - Fill1DProfile("CDC_Efficiency", "Online", "Efficiency (with dE/dx) Vs Tracking FOM", thisTimeBasedTrack->FOM,foundHitWithdEdx, "Efficiency (with dE/dx); Tracking FOM; Efficiency (with dE/dx)", 100, 0 , 1.0); - Fill1DProfile("CDC_Efficiency", "Online", "Efficiency (with dE/dx) Vs theta", locTheta,foundHitWithdEdx, "Efficiency (with dE/dx); Track #Theta [deg]; Efficiency (with dE/dx)", 100, 0, 180); - Fill1DProfile("CDC_Efficiency", "Online", "Efficiency (with dE/dx) Vs p", thisTimeBasedTrack->pmag(),foundHitWithdEdx, "Efficiency (with dE/dx); Momentum [GeV]; Efficiency (with dE/dx)", 100, 0 , 4.0); - Fill1DProfile("CDC_Efficiency", "Online", "Efficiency (with dE/dx) Vs delta", delta,foundHitWithdEdx, "Efficiency (with dE/dx); #delta [cm]; Efficiency (with dE/dx)", 100, -0.3 , 0.3); - - //expected hits by straw number - Fill1DProfile("CDC_Efficiency", "Online", "Efficiency (with dE/dx) Vs N", Nstraws_previous[ringNum-1]+wireNum, foundHitWithdEdx,"Efficiency (with dE/dx); N; Efficiency (with dE/dx)", 3522, 0.5 , 3522.5); + hEfficiencyWithDEDxVsPathLength->Fill(dx,foundHitWithdEdx); + hEfficiencyWithDEDxVsDOCA->Fill(distanceToWire,foundHitWithdEdx); + hEfficiencyWithDEDxVsTrackingFOM->Fill(thisTimeBasedTrack->FOM,foundHitWithdEdx); + hEfficiencyWithDEDxVsTheta->Fill(locTheta,foundHitWithdEdx); + hEfficiencyWithDEDxVsMom->Fill(thisTimeBasedTrack->pmag(),foundHitWithdEdx); + hEfficiencyWithDEDxVsDelta->Fill(delta,foundHitWithdEdx); + hEfficiencyWithDEDxVsN->Fill(Nstraws_previous[ringNum-1]+wireNum,foundHitWithdEdx); //expected hits by straw number } if( ChannelFromRingStraw[ringNum - 1][wireNum - 1] != -1) { - Fill1DProfile("CDC_Efficiency", "Online", "Efficiency Vs Channel Number", ChannelFromRingStraw[ringNum - 1][wireNum - 1],foundHit, "Efficiency; Channel Number; Efficiency", 73, -0.5 , 72.5); - char name [200]; - sprintf(name, "Slot Efficiency ROCID %.2i", ROCIDFromRingStraw[ringNum - 1][wireNum - 1]); - Fill1DProfile("CDC_Efficiency", "Online", name, SlotFromRingStraw[ringNum - 1][wireNum - 1],foundHit, "Efficiency; Slot Number; Efficiency", 21, -0.5 , 20.5); - sprintf(name, "Channel Efficiency ROCID %.2i", ROCIDFromRingStraw[ringNum - 1][wireNum - 1]); - Fill1DProfile("CDC_Efficiency", "Online", name, SlotFromRingStraw[ringNum - 1][wireNum - 1] * 100 + ChannelFromRingStraw[ringNum - 1][wireNum - 1],foundHit, "Efficiency; Channel; Efficiency", 1501, 299.5 , 1800.5); + hEfficiencyVsChannel->Fill(ChannelFromRingStraw[ringNum - 1][wireNum - 1],foundHit); + hEfficiencyVsSlotROC[ ROCIDFromRingStraw[ringNum - 1][wireNum - 1] ]->Fill(SlotFromRingStraw[ringNum - 1][wireNum - 1],foundHit); + hEfficiencyVsChannelROC[ ROCIDFromRingStraw[ringNum - 1][wireNum - 1] ]->Fill(SlotFromRingStraw[ringNum - 1][wireNum - 1] * 100 + ChannelFromRingStraw[ringNum - 1][wireNum - 1],foundHit); if (FILL_DEDX_HISTOS) { // repeat w dedx info - Fill1DProfile("CDC_Efficiency", "Online", "Efficiency (with dE/dx) Vs Channel Number", ChannelFromRingStraw[ringNum - 1][wireNum - 1],foundHitWithdEdx, "Efficiency (with dE/dx); Channel Number; Efficiency (with dE/dx)", 73, -0.5 , 72.5); - sprintf(name, "Slot Efficiency (with dE/dx) ROCID %.2i", ROCIDFromRingStraw[ringNum - 1][wireNum - 1]); - Fill1DProfile("CDC_Efficiency", "Online", name, SlotFromRingStraw[ringNum - 1][wireNum - 1],foundHitWithdEdx, "Efficiency (with dE/dx); Slot Number; Efficiency (with dE/dx)", 21, -0.5 , 20.5); - sprintf(name, "Channel Efficiency (with dE/dx) ROCID %.2i", ROCIDFromRingStraw[ringNum - 1][wireNum - 1]); - Fill1DProfile("CDC_Efficiency", "Online", name, SlotFromRingStraw[ringNum - 1][wireNum - 1] * 100 + ChannelFromRingStraw[ringNum - 1][wireNum - 1],foundHitWithdEdx, "Efficiency (with dE/dx); Channel; Efficiency (with dE/dx)", 1501, 299.5 , 1800.5); + hEfficiencyWithDEDxVsChannel->Fill(ChannelFromRingStraw[ringNum - 1][wireNum - 1],foundHitWithdEdx); + hEfficiencyWithDEDxVsSlotROC[ ROCIDFromRingStraw[ringNum - 1][wireNum - 1] ]->Fill(SlotFromRingStraw[ringNum - 1][wireNum - 1],foundHitWithdEdx); + hEfficiencyWithDEDxVsSlotROC[ ROCIDFromRingStraw[ringNum - 1][wireNum - 1] ]->Fill(SlotFromRingStraw[ringNum - 1][wireNum - 1] * 100 + ChannelFromRingStraw[ringNum - 1][wireNum - 1],foundHitWithdEdx); } } - Fill2DProfile("CDC_Efficiency", "Online", "Efficiency p Vs Theta", locTheta, thisTimeBasedTrack->pmag(),foundHit, "Efficiency; Track #Theta [deg]; Momentum [GeV]", 100, 0, 180, 100, 0 , 4.0); - Fill2DProfile("CDC_Efficiency", "Online", "Efficiency distance Vs delta", delta,distanceToWire,foundHit, "Efficiency;#delta [cm]; DOCA [cm]", 100, -0.3, 0.3, 100, 0 , 1.2); - Fill2DProfile("CDC_Efficiency", "Online", "Efficiency z Vs delta", delta,dz,foundHit, "Efficiency;#delta [cm]; z [cm] (CDC local coordinates)", 100, -0.3, 0.3, 150, -75 , 75); + hEfficiencyMomVsTheta->Fill(locTheta, thisTimeBasedTrack->pmag(),foundHit); + hEfficiencyDistanceVsDelta->Fill(delta,distanceToWire,foundHit); + hEfficiencyZVsDelta->Fill(delta,dz,foundHit); if (FILL_DEDX_HISTOS) { // repeat w dedx info - Fill2DProfile("CDC_Efficiency", "Online", "Efficiency (with dE/dx) p Vs Theta", locTheta, thisTimeBasedTrack->pmag(),foundHitWithdEdx, "Efficiency (with dE/dx); Track #Theta [deg]; Momentum [GeV]", 100, 0, 180, 100, 0 , 4.0); - Fill2DProfile("CDC_Efficiency", "Online", "Efficiency (with dE/dx) distance Vs delta", delta,distanceToWire,foundHitWithdEdx, "Efficiency (with dE/dx);#delta [cm]; DOCA [cm]", 100, -0.3, 0.3, 100, 0 , 1.2); - Fill2DProfile("CDC_Efficiency", "Online", "Efficiency (with dE/dx) z Vs delta", delta,dz,foundHitWithdEdx, "Efficiency (with dE/dx);#delta [cm]; z [cm] (CDC local coordinates)", 100, -0.3, 0.3, 150, -75 , 75); + hEfficiencyWithDEDxMomVsTheta->Fill(locTheta, thisTimeBasedTrack->pmag(),foundHitWithdEdx); + hEfficiencyWithDEDxDistanceVsDelta->Fill(delta,distanceToWire,foundHitWithdEdx); + hEfficiencyWithDEDxZVsDelta->Fill(delta,dz,foundHitWithdEdx); } + japp->RootFillUnLock(this); //RELEASE ROOT FILL LOCK //FILL AS FUNCTION OF DOCA diff --git a/src/plugins/monitoring/CDC_Efficiency/JEventProcessor_CDC_Efficiency.h b/src/plugins/monitoring/CDC_Efficiency/JEventProcessor_CDC_Efficiency.h index be76289427..25934bc471 100644 --- a/src/plugins/monitoring/CDC_Efficiency/JEventProcessor_CDC_Efficiency.h +++ b/src/plugins/monitoring/CDC_Efficiency/JEventProcessor_CDC_Efficiency.h @@ -19,8 +19,10 @@ using namespace std; #include #include #include +#include #include + #include #include #include @@ -97,9 +99,67 @@ class JEventProcessor_CDC_Efficiency:public jana::JEventProcessor{ TH2I *ChargeVsTrackLength; TH1I * hChi2OverNDF; TH2I *hResVsT; - + - + TH1F *hExpectedHitsVsPathLength; + TH1F *hExpectedHitsVsDOCA; + TH1F *hExpectedHitsVsTrackingFOM; + TH1F *hExpectedHitsVsTheta; + TH1F *hExpectedHitsVsMom; + TH1F *hExpectedHitsVsDelta; + TH2F *hExpectedHitsMomVsTheta; + TH1F *hExpectedHitsVsN; + + TH1F *hMeasuredHitsVsPathLength; + TH1F *hMeasuredHitsVsDOCA; + TH1F *hMeasuredHitsVsTrackingFOM; + TH1F *hMeasuredHitsVsTheta; + TH1F *hMeasuredHitsVsMom; + TH1F *hMeasuredHitsVsDelta; + TH2F *hMeasuredHitsMomVsTheta; + TH1F *hMeasuredHitsVsN; + + TH1F *hMeasuredHitsWithDEDxVsPathLength; + TH1F *hMeasuredHitsWithDEDxVsDOCA; + TH1F *hMeasuredHitsWithDEDxVsTrackingFOM; + TH1F *hMeasuredHitsWithDEDxVsTheta; + TH1F *hMeasuredHitsWithDEDxVsMom; + TH1F *hMeasuredHitsWithDEDxVsDelta; + TH2F *hMeasuredHitsWithDEDxMomVsTheta; + TH1F *hMeasuredHitsWithDEDxVsN; + + TProfile *hEfficiencyVsPathLength; + TProfile *hEfficiencyVsDOCA; + TProfile *hEfficiencyVsTrackingFOM; + TProfile *hEfficiencyVsTheta; + TProfile *hEfficiencyVsMom; + TProfile *hEfficiencyVsDelta; + TProfile *hEfficiencyVsN; + + TProfile *hEfficiencyWithDEDxVsPathLength; + TProfile *hEfficiencyWithDEDxVsDOCA; + TProfile *hEfficiencyWithDEDxVsTrackingFOM; + TProfile *hEfficiencyWithDEDxVsTheta; + TProfile *hEfficiencyWithDEDxVsMom; + TProfile *hEfficiencyWithDEDxVsDelta; + TProfile *hEfficiencyWithDEDxVsN; + + TProfile *hEfficiencyVsChannel; + map hEfficiencyVsSlotROC; + map hEfficiencyVsChannelROC; + + TProfile *hEfficiencyWithDEDxVsChannel; + map hEfficiencyWithDEDxVsSlotROC; + map hEfficiencyWithDEDxVsChannelROC; + + TProfile2D *hEfficiencyMomVsTheta; + TProfile2D *hEfficiencyDistanceVsDelta; + TProfile2D *hEfficiencyZVsDelta; + + TProfile2D *hEfficiencyWithDEDxMomVsTheta; + TProfile2D *hEfficiencyWithDEDxDistanceVsDelta; + TProfile2D *hEfficiencyWithDEDxZVsDelta; + }; diff --git a/src/plugins/monitoring/CDC_PerStrawReco/JEventProcessor_CDC_PerStrawReco.cc b/src/plugins/monitoring/CDC_PerStrawReco/JEventProcessor_CDC_PerStrawReco.cc index 0fbd6dbddd..adb0048c75 100644 --- a/src/plugins/monitoring/CDC_PerStrawReco/JEventProcessor_CDC_PerStrawReco.cc +++ b/src/plugins/monitoring/CDC_PerStrawReco/JEventProcessor_CDC_PerStrawReco.cc @@ -23,6 +23,7 @@ void InitPlugin(JApplication *app){ } } // "C" +static const double binwidth = 0.005; //------------------ // JEventProcessor_CDC_PerStrawReco (Constructor) @@ -40,11 +41,17 @@ JEventProcessor_CDC_PerStrawReco::~JEventProcessor_CDC_PerStrawReco() } +enum { + kMIDDLE = 0, + kDOWNSTREAM +}; + //------------------ // init //------------------ jerror_t JEventProcessor_CDC_PerStrawReco::init(void) { + EXCLUDERING=0; if (gPARMS){ gPARMS->SetDefaultParameter("CDCCOSMIC:EXCLUDERING", EXCLUDERING, "Ring Excluded from the fit"); @@ -53,6 +60,8 @@ jerror_t JEventProcessor_CDC_PerStrawReco::init(void) if(EXCLUDERING == 0 ){ jout << "Did not set CDCCOSMIC:EXCLUDERING on the command line -- Using Biased fits" << endl; } + + return NOERROR; } @@ -61,6 +70,22 @@ jerror_t JEventProcessor_CDC_PerStrawReco::init(void) //------------------ jerror_t JEventProcessor_CDC_PerStrawReco::brun(JEventLoop *eventLoop, int32_t runnumber) { + + int numrings = 28; + char folder[100]; + char name[100]; + char title[256]; +// char strawname[100]; +// char strawtitle[256]; +// char residualname[100]; +// char residualtitle[256]; +// char binname[150]; +// char bintitle[150]; + +// unsigned int numstraws[28]={42,42,54,54,66,66,80,80,93,93,106,106,123,123, +// 135,135,146,146,158,158,170,170,182,182,197,197, +// 209,209}; + DApplication* dapp=dynamic_cast(eventLoop->GetJApplication()); JCalibration *jcalib = dapp->GetJCalibration(runnumber); // This is called whenever the run number changes @@ -91,6 +116,313 @@ jerror_t JEventProcessor_CDC_PerStrawReco::brun(JEventLoop *eventLoop, int32_t r } } } + + // make histograms here, since we need the sag information + japp->RootWriteLock(); + if(hResiduals.size() == 0) { + + vector empty_h1d; + vector empty_h2d; + vector> empty_h1d_vec; + vector> empty_h2d_vec; + + TDirectory *main = gDirectory; + gDirectory->mkdir("CDCReco_Middle")->cd(); + + hResiduals.push_back(empty_h1d); + hResidualsVsMomentum.push_back(empty_h2d); + hResidualsVsTheta.push_back(empty_h2d); + hResidualsVsZ.push_back(empty_h2d); + hResidualsVsTrackingFOM.push_back(empty_h2d); + + hDriftTime.push_back(empty_h1d); + hDriftDistance.push_back(empty_h1d); + hPredictedDriftDistance.push_back(empty_h1d); + + hResidualsVsDriftTime.push_back(empty_h2d); + hResidualsVsDriftDistance.push_back(empty_h2d); + hResidualsVsPredictedDriftDistance.push_back(empty_h2d); + hPredictedDriftDistanceVsDriftTime.push_back(empty_h2d); + + for(int ring=1; ring<=numrings; ring++) { + + sprintf(folder, "Ring %.2i", ring); + gDirectory->mkdir(folder)->cd(); + + hResiduals.at(kMIDDLE).push_back( new TH1F("Residuals", "Residuals; Residual [cm]; Entries", 200, -0.05, 0.05) ); + hResidualsVsMomentum.at(kMIDDLE).push_back( new TH2F("Residual Vs. Momentum", + "Residual Vs. Momentum; Momentum [GeV/c]; Residual [cm]", 50, 0.0, 12.0, 100, -0.05, 0.05) ); + hResidualsVsTheta.at(kMIDDLE).push_back( new TH2F("Residual Vs. Theta", + "Residual Vs. Theta; Theta [deg]; Residual [cm]", 60, 0.0, 180.0, 100, -0.05, 0.05) ); + hResidualsVsZ.at(kMIDDLE).push_back( new TH2F("Residual Vs. Z", + "Residual Vs. Z; Z (Measured from CDC center) [cm]; Residual [cm]", 100, -75.0, 75.0, 100, -0.05, 0.05) ); + hResidualsVsTrackingFOM.at(kMIDDLE).push_back( new TH2F("Residual Vs. Tracking FOM", + "Residual Vs. Tracking FOM; Tracking FOM; Residual [cm]", 100, 0.0, 1.0, 100, -0.05, 0.05) ); + + hDriftTime.at(kMIDDLE).push_back( new TH1F("Drift Time", "Drift Time; Drift Time [ns]; Entries", 500, -10, 1500) ); + hDriftDistance.at(kMIDDLE).push_back( new TH1F("Drift Distance", "Drift Distance; Drift Distance [cm]; Entries", 250, 0.0, 1.2) ); + hPredictedDriftDistance.at(kMIDDLE).push_back( new TH1F("Predicted Drift Distance", + "Predicted Drift Distance; Drift Distance [cm]; Entries", 250, 0.0, 1.2) ); + + hResidualsVsDriftTime.at(kMIDDLE).push_back( new TH2F("Residual Vs. Drift Time", + "Residual Vs. Drift Time; Drift Time [ns]; Residual [cm]", 500, -10, 1500, 100, -0.05, 0.05) ); + hResidualsVsDriftDistance.at(kMIDDLE).push_back( new TH2F("Residual Vs. Drift Distance", + "Residual Vs. Drift Distance; Drift Distance [cm]; Residual [cm]", 50, 0.0, 1.0, 100, -0.05, 0.05) ); + hResidualsVsPredictedDriftDistance.at(kMIDDLE).push_back( new TH2F("Residual Vs. Predicted Drift Distance", + "Residual Vs. Predicted Drift Distance; Predicted Drift Distance [cm]; Residual [cm]", 50, 0.0, 1.0, 100, -0.05, 0.05) ); + hPredictedDriftDistanceVsDriftTime.at(kMIDDLE).push_back( new TH2F("Predicted Drift Distance Vs. Drift Time", + "Predicted Drift Distance Vs. Drift Time; Drift Time [ns]; Predicted Drift Distance [cm]", 500, -10, 1500, 100, 0.0, 1.0) ); + + gDirectory->cd(".."); + } + + + main->cd(); + gDirectory->mkdir("CDCPerStrawReco_Middle")->cd(); + + hStrawDriftTimeVsPhiDOCA.push_back( empty_h2d_vec ); + hStrawPredictedDistanceVsPhiDOCA.push_back( empty_h2d_vec ); + hStrawResidual.push_back( empty_h1d_vec ); + hStrawResidualVsZ.push_back( empty_h2d_vec ); + + hStrawResidualVsDelta.push_back( empty_h2d_vec ); + hStrawPredictedDriftDistanceVsDriftTime.push_back( empty_h2d_vec ); + hStrawPredictedDriftDistanceVsDelta.push_back( empty_h2d_vec ); + + hPredictedDriftDistanceVsDriftTime_PosDelta.push_back( empty_h2d_vec ); + hResidualVsDriftTime_PosDelta.push_back( empty_h2d_vec ); + hResidual_PosDelta.push_back( empty_h1d_vec ); + + hPredictedDriftDistanceVsDriftTime_NegDelta.push_back( empty_h2d_vec ); + hResidualVsDriftTime_NegDelta.push_back( empty_h2d_vec ); + hResidual_NegDelta.push_back( empty_h1d_vec ); + + for(int ring=1; ring<=numrings; ring++) { + + sprintf(folder, "Ring %.2i", ring); + gDirectory->mkdir(folder)->cd(); + + hStrawDriftTimeVsPhiDOCA.at(kMIDDLE).push_back( empty_h2d ); + hStrawPredictedDistanceVsPhiDOCA.at(kMIDDLE).push_back( empty_h2d ); + hStrawResidual.at(kMIDDLE).push_back( empty_h1d ); + hStrawResidualVsZ.at(kMIDDLE).push_back( empty_h2d ); + + hStrawResidualVsDelta.at(kMIDDLE).push_back( empty_h2d ); + hStrawPredictedDriftDistanceVsDriftTime.at(kMIDDLE).push_back( empty_h2d ); + hStrawPredictedDriftDistanceVsDelta.at(kMIDDLE).push_back( empty_h2d ); + + hPredictedDriftDistanceVsDriftTime_PosDelta.at(kMIDDLE).push_back( empty_h2d ); + hResidualVsDriftTime_PosDelta.at(kMIDDLE).push_back( empty_h2d ); + hResidual_PosDelta.at(kMIDDLE).push_back( empty_h1d ); + + hPredictedDriftDistanceVsDriftTime_NegDelta.at(kMIDDLE).push_back( empty_h2d ); + hResidualVsDriftTime_NegDelta.at(kMIDDLE).push_back( empty_h2d ); + hResidual_NegDelta.at(kMIDDLE).push_back( empty_h1d ); + + + for(unsigned int straw=1; straw<=numstraws[ring-1]; straw++) { + sprintf(name,"Straw %.3i Drift time Vs phi_DOCA", straw); + sprintf(title,"Ring %.2i Straw %.3i Drift time Vs phi_DOCA;#phi_{DOCA};Drift Time [ns]", ring, straw); + hStrawDriftTimeVsPhiDOCA.at(kMIDDLE).at(ring-1).push_back( new TH2F(name, title, 8, -3.14, 3.14, 500, -10, 1500) ); + + sprintf(name,"Straw %.3i Predicted Drift Distance Vs phi_DOCA", straw); + sprintf(title,"Ring %.2i Straw %.3i Predicted Drift Distance Vs phi_DOCA; #phi_{DOCA};Predicted Distance [cm]", ring, straw); + hStrawPredictedDistanceVsPhiDOCA.at(kMIDDLE).at(ring-1).push_back( new TH2F(name, title, 16, -3.14, 3.14, 400, 0.0, 1.2) ); + sprintf(name,"Straw %.3i Residual", straw); + sprintf(title,"Ring %.2i Straw %.3i Residual;Residual [cm]", ring, straw); + hStrawResidual.at(kMIDDLE).at(ring-1).push_back( new TH1F(name, title, 200, -0.05, 0.05) ); + sprintf(name,"Straw %.3i Residual Vs. Z", straw); + sprintf(title,"Ring %.2i Straw %.3i Residual;Z [cm]; Residual [cm]", ring, straw); + hStrawResidualVsZ.at(kMIDDLE).at(ring-1).push_back( new TH2F(name, title, 30, -75.0,75.0,200, -0.05, 0.05) ); + + sprintf(name,"Straw %.3i residual Vs delta", straw); + sprintf(title,"Ring %.2i Straw %.3i Residual Vs #delta; #delta [cm]; Residual [cm]",ring, straw); + hStrawResidualVsDelta.at(kMIDDLE).at(ring-1).push_back( new TH2F(name, title, Int_t(2 * max_sag[ring - 1][straw - 1] / binwidth), -1 * max_sag[ring - 1][straw - 1], max_sag[ring - 1][straw - 1], 100, -0.05, 0.05) ); + sprintf(name,"Straw %.3i Predicted Drift Distance Vs. Drift Time", straw); + sprintf(title,"Ring %.2i Straw %.3i Predicted Drift Distance Vs. Drift Time", ring, straw); + hStrawPredictedDriftDistanceVsDriftTime.at(kMIDDLE).at(ring-1).push_back( new TH2F(name, title, 250, -50, 200, 250, 0.0, 0.4) ); + sprintf(name,"Straw %.3i Predicted Drift Distance Vs. delta", straw); + sprintf(title,"Ring %.2i Straw %.3i Predicted Drift Distance Vs. #delta;#delta [cm]; Predicted Drift Distance - Nominal Radius [cm]", ring, straw); + hStrawPredictedDriftDistanceVsDelta.at(kMIDDLE).at(ring-1).push_back( new TH2F(name, title, 20, -0.25, 0.25, 250, -0.25, 0.25) ); + + sprintf(name,"Straw %.3i Predicted Drift Distance Vs. Drift Time Positive Delta", straw); + sprintf(title,"Ring %.2i Straw %.3i Predicted Drift Distance Vs. Drift Time (Positive Delta)", ring, straw); + hPredictedDriftDistanceVsDriftTime_PosDelta.at(kMIDDLE).at(ring-1).push_back( new TH2F(name, title, 250, -10, 1500, 50, 0.0, 1.2) ); + sprintf(name,"Straw %.3i Residual Vs. Drift Time Positive Delta", straw); + sprintf(title,"Ring %.2i Straw %.3i Residual Vs. Drift Time (Positive Delta)", ring, straw); + hResidualVsDriftTime_PosDelta.at(kMIDDLE).at(ring-1).push_back( new TH2F(name, title, 100, -10, 1500, 100, -0.05, 0.05) ); + sprintf(name,"Straw %.3i Residual Positive Delta", straw); + sprintf(title,"Ring %.2i Straw %.3i Residual (Positive Delta); Residual [cm]; Entries", ring, straw); + hResidual_PosDelta.at(kMIDDLE).at(ring-1).push_back( new TH1F(name, title, 200, -0.05, 0.05) ); + + sprintf(name,"Straw %.3i Predicted Drift Distance Vs. Drift Time Negative Delta", straw); + sprintf(title,"Ring %.2i Straw %.3i Predicted Drift Distance Vs. Drift Time (Negative Delta)", ring, straw); + hPredictedDriftDistanceVsDriftTime_NegDelta.at(kMIDDLE).at(ring-1).push_back( new TH2F(name, title, 250, -10, 1500, 50, 0.0, 1.2) ); + sprintf(name,"Straw %.3i Residual Vs. Drift Time Negative Delta", straw); + sprintf(title,"Ring %.2i Straw %.3i Residual Vs. Drift Time (Negative Delta)", ring, straw); + hResidualVsDriftTime_NegDelta.at(kMIDDLE).at(ring-1).push_back( new TH2F(name, title, 100, -10, 1500, 100, -0.05, 0.05) ); + sprintf(name,"Straw %.3i Residual Negative Delta", straw); + sprintf(title,"Ring %.2i Straw %.3i Residual (Negative Delta); Residual [cm]; Entries", ring, straw); + hResidual_NegDelta.at(kMIDDLE).at(ring-1).push_back( new TH1F(name, title, 200, -0.05, 0.05) ); + + } + + + gDirectory->cd(".."); + } + + + main->cd(); + gDirectory->mkdir("CDCReco_Downstream")->cd(); + + hResiduals.push_back(empty_h1d); + hResidualsVsMomentum.push_back(empty_h2d); + hResidualsVsTheta.push_back(empty_h2d); + hResidualsVsZ.push_back(empty_h2d); + hResidualsVsTrackingFOM.push_back(empty_h2d); + + hDriftTime.push_back(empty_h1d); + hDriftDistance.push_back(empty_h1d); + hPredictedDriftDistance.push_back(empty_h1d); + + hResidualsVsDriftTime.push_back(empty_h2d); + hResidualsVsDriftDistance.push_back(empty_h2d); + hResidualsVsPredictedDriftDistance.push_back(empty_h2d); + hPredictedDriftDistanceVsDriftTime.push_back(empty_h2d); + + for(int ring=1; ring<=numrings; ring++) { + + sprintf(folder, "Ring %.2i", ring); + gDirectory->mkdir(folder)->cd(); + + hResiduals.at(kDOWNSTREAM).push_back( new TH1F("Residuals", "Residuals; Residual [cm]; Entries", 200, -0.05, 0.05) ); + hResidualsVsMomentum.at(kDOWNSTREAM).push_back( new TH2F("Residual Vs. Momentum", + "Residual Vs. Momentum; Momentum [GeV/c]; Residual [cm]", 50, 0.0, 12.0, 100, -0.05, 0.05) ); + hResidualsVsTheta.at(kDOWNSTREAM).push_back( new TH2F("Residual Vs. Theta", + "Residual Vs. Theta; Theta [deg]; Residual [cm]", 60, 0.0, 180.0, 100, -0.05, 0.05) ); + hResidualsVsZ.at(kDOWNSTREAM).push_back( new TH2F("Residual Vs. Z", + "Residual Vs. Z; Z (Measured from CDC center) [cm]; Residual [cm]", 100, -75.0, 75.0, 100, -0.05, 0.05) ); + hResidualsVsTrackingFOM.at(kDOWNSTREAM).push_back( new TH2F("Residual Vs. Tracking FOM", + "Residual Vs. Tracking FOM; Tracking FOM; Residual [cm]", 100, 0.0, 1.0, 100, -0.05, 0.05) ); + + hDriftTime.at(kDOWNSTREAM).push_back( new TH1F("Drift Time", "Drift Time; Drift Time [ns]; Entries", 500, -10, 1500) ); + hDriftDistance.at(kDOWNSTREAM).push_back( new TH1F("Drift Distance", "Drift Distance; Drift Distance [cm]; Entries", 250, 0.0, 1.2) ); + hPredictedDriftDistance.at(kDOWNSTREAM).push_back( new TH1F("Predicted Drift Distance", + "Predicted Drift Distance; Drift Distance [cm]; Entries", 250, 0.0, 1.2) ); + + hResidualsVsDriftTime.at(kDOWNSTREAM).push_back( new TH2F("Residual Vs. Drift Time", + "Residual Vs. Drift Time; Drift Time [ns]; Residual [cm]", 500, -10, 1500, 100, -0.05, 0.05) ); + hResidualsVsDriftDistance.at(kDOWNSTREAM).push_back( new TH2F("Residual Vs. Drift Distance", + "Residual Vs. Drift Distance; Drift Distance [cm]; Residual [cm]", 50, 0.0, 1.0, 100, -0.05, 0.05) ); + hResidualsVsPredictedDriftDistance.at(kDOWNSTREAM).push_back( new TH2F("Residual Vs. Predicted Drift Distance", + "Residual Vs. Predicted Drift Distance; Predicted Drift Distance [cm]; Residual [cm]", 50, 0.0, 1.0, 100, -0.05, 0.05) ); + hPredictedDriftDistanceVsDriftTime.at(kDOWNSTREAM).push_back( new TH2F("Predicted Drift Distance Vs. Drift Time", + "Predicted Drift Distance Vs. Drift Time; Drift Time [ns]; Predicted Drift Distance [cm]", 500, -10, 1500, 100, 0.0, 1.0) ); + + gDirectory->cd(".."); + } + + + main->cd(); + gDirectory->mkdir("CDCPerStrawReco_Downstream")->cd(); + + hStrawDriftTimeVsPhiDOCA.push_back( empty_h2d_vec ); + hStrawPredictedDistanceVsPhiDOCA.push_back( empty_h2d_vec ); + hStrawResidual.push_back( empty_h1d_vec ); + hStrawResidualVsZ.push_back( empty_h2d_vec ); + + hStrawResidualVsDelta.push_back( empty_h2d_vec ); + hStrawPredictedDriftDistanceVsDriftTime.push_back( empty_h2d_vec ); + hStrawPredictedDriftDistanceVsDelta.push_back( empty_h2d_vec ); + + hPredictedDriftDistanceVsDriftTime_PosDelta.push_back( empty_h2d_vec ); + hResidualVsDriftTime_PosDelta.push_back( empty_h2d_vec ); + hResidual_PosDelta.push_back( empty_h1d_vec ); + + hPredictedDriftDistanceVsDriftTime_NegDelta.push_back( empty_h2d_vec ); + hResidualVsDriftTime_NegDelta.push_back( empty_h2d_vec ); + hResidual_NegDelta.push_back( empty_h1d_vec ); + + for(int ring=1; ring<=numrings; ring++) { + + sprintf(folder, "Ring %.2i", ring); + gDirectory->mkdir(folder)->cd(); + + hStrawDriftTimeVsPhiDOCA.at(kDOWNSTREAM).push_back( empty_h2d ); + hStrawPredictedDistanceVsPhiDOCA.at(kDOWNSTREAM).push_back( empty_h2d ); + hStrawResidual.at(kDOWNSTREAM).push_back( empty_h1d ); + hStrawResidualVsZ.at(kDOWNSTREAM).push_back( empty_h2d ); + + hStrawResidualVsDelta.at(kDOWNSTREAM).push_back( empty_h2d ); + hStrawPredictedDriftDistanceVsDriftTime.at(kDOWNSTREAM).push_back( empty_h2d ); + hStrawPredictedDriftDistanceVsDelta.at(kDOWNSTREAM).push_back( empty_h2d ); + + hPredictedDriftDistanceVsDriftTime_PosDelta.at(kDOWNSTREAM).push_back( empty_h2d ); + hResidualVsDriftTime_PosDelta.at(kDOWNSTREAM).push_back( empty_h2d ); + hResidual_PosDelta.at(kDOWNSTREAM).push_back( empty_h1d ); + + hPredictedDriftDistanceVsDriftTime_NegDelta.at(kDOWNSTREAM).push_back( empty_h2d ); + hResidualVsDriftTime_NegDelta.at(kDOWNSTREAM).push_back( empty_h2d ); + hResidual_NegDelta.at(kDOWNSTREAM).push_back( empty_h1d ); + + + for(unsigned int straw=1; straw<=numstraws[ring-1]; straw++) { + + sprintf(name,"Straw %.3i Drift time Vs phi_DOCA", straw); + sprintf(title,"Ring %.2i Straw %.3i Drift time Vs phi_DOCA;#phi_{DOCA};Drift Time [ns]", ring, straw); + hStrawDriftTimeVsPhiDOCA.at(kDOWNSTREAM)[ring-1].push_back( new TH2F(name, title, 8, -3.14, 3.14, 500, -10, 1500) ); + sprintf(name,"Straw %.3i Predicted Drift Distance Vs phi_DOCA", straw); + sprintf(title,"Ring %.2i Straw %.3i Predicted Drift Distance Vs phi_DOCA; #phi_{DOCA};Predicted Distance [cm]", ring, straw); + hStrawPredictedDistanceVsPhiDOCA.at(kDOWNSTREAM)[ring-1].push_back( new TH2F(name, title, 16, -3.14, 3.14, 400, 0.0, 1.2) ); + sprintf(name,"Straw %.3i Residual", straw); + sprintf(title,"Ring %.2i Straw %.3i Residual;Residual [cm]", ring, straw); + hStrawResidual.at(kDOWNSTREAM)[ring-1].push_back( new TH1F(name, title, 200, -0.05, 0.05) ); + sprintf(name,"Straw %.3i Residual Vs. Z", straw); + sprintf(title,"Ring %.2i Straw %.3i Residual;Z [cm]; Residual [cm]", ring, straw); + hStrawResidualVsZ.at(kDOWNSTREAM)[ring-1].push_back( new TH2F(name, title, 30, -75.0,75.0,200, -0.05, 0.05) ); + + sprintf(name,"Straw %.3i residual Vs delta", straw); + sprintf(title,"Ring %.2i Straw %.3i Residual Vs #delta; #delta [cm]; Residual [cm]",ring, straw); + hStrawResidualVsDelta.at(kDOWNSTREAM)[ring-1].push_back( new TH2F(name, title, Int_t(2 * max_sag[ring - 1][straw - 1] / binwidth), -1 * max_sag[ring - 1][straw - 1], max_sag[ring - 1][straw - 1], 100, -0.05, 0.05) ); + sprintf(name,"Straw %.3i Predicted Drift Distance Vs. Drift Time", straw); + sprintf(title,"Ring %.2i Straw %.3i Predicted Drift Distance Vs. Drift Time", ring, straw); + hStrawPredictedDriftDistanceVsDriftTime.at(kDOWNSTREAM)[ring-1].push_back( new TH2F(name, title, 250, -50, 200, 250, 0.0, 0.4) ); + sprintf(name,"Straw %.3i Predicted Drift Distance Vs. delta", straw); + sprintf(title,"Ring %.2i Straw %.3i Predicted Drift Distance Vs. #delta;#delta [cm]; Predicted Drift Distance - Nominal Radius [cm]", ring, straw); + hStrawPredictedDriftDistanceVsDelta.at(kDOWNSTREAM)[ring-1].push_back( new TH2F(name, title, 20, -0.25, 0.25, 250, -0.25, 0.25) ); + + sprintf(name,"Straw %.3i Predicted Drift Distance Vs. Drift Time Positive Delta", straw); + sprintf(title,"Ring %.2i Straw %.3i Predicted Drift Distance Vs. Drift Time (Positive Delta)", ring, straw); + hPredictedDriftDistanceVsDriftTime_PosDelta.at(kDOWNSTREAM)[ring-1].push_back( new TH2F(name, title, 250, -10, 1500, 50, 0.0, 1.2) ); + sprintf(name,"Straw %.3i Residual Vs. Drift Time Positive Delta", straw); + sprintf(title,"Ring %.2i Straw %.3i Residual Vs. Drift Time (Positive Delta)", ring, straw); + hResidualVsDriftTime_PosDelta.at(kDOWNSTREAM)[ring-1].push_back( new TH2F(name, title, 100, -10, 1500, 100, -0.05, 0.05) ); + sprintf(name,"Straw %.3i Residual Positive Delta", straw); + sprintf(title,"Ring %.2i Straw %.3i Residual (Positive Delta); Residual [cm]; Entries", ring, straw); + hResidual_PosDelta.at(kDOWNSTREAM)[ring-1].push_back( new TH1F(name, title, 200, -0.05, 0.05) ); + + sprintf(name,"Straw %.3i Predicted Drift Distance Vs. Drift Time Negative Delta", straw); + sprintf(title,"Ring %.2i Straw %.3i Predicted Drift Distance Vs. Drift Time (Negative Delta)", ring, straw); + hPredictedDriftDistanceVsDriftTime_NegDelta.at(kDOWNSTREAM)[ring-1].push_back( new TH2F(name, title, 250, -10, 1500, 50, 0.0, 1.2) ); + sprintf(name,"Straw %.3i Residual Vs. Drift Time Negative Delta", straw); + sprintf(title,"Ring %.2i Straw %.3i Residual Vs. Drift Time (Negative Delta)", ring, straw); + hResidualVsDriftTime_NegDelta.at(kDOWNSTREAM)[ring-1].push_back( new TH2F(name, title, 100, -10, 1500, 100, -0.05, 0.05) ); + sprintf(name,"Straw %.3i Residual Negative Delta", straw); + sprintf(title,"Ring %.2i Straw %.3i Residual (Negative Delta); Residual [cm]; Entries", ring, straw); + hResidual_NegDelta.at(kDOWNSTREAM)[ring-1].push_back( new TH1F(name, title, 200, -0.05, 0.05) ); + + } + + gDirectory->cd(".."); + } + + + main->cd(); + + } + japp->RootUnLock(); + + return NOERROR; } @@ -144,125 +476,60 @@ jerror_t JEventProcessor_CDC_PerStrawReco::evnt(JEventLoop *loop, uint64_t event char folder[100]; sprintf(folder, "Ring %.2i", ring); - const char * regionString = ""; - const char * regionStringPerStraw = ""; + int region = 0; // safe, because either isMiddle or isDownstream are true if (isMiddle) { - regionString = "CDCReco_Middle"; - regionStringPerStraw = "CDCPerStrawReco_Middle"; + region = kMIDDLE; } else if (isDownstream){ - regionString = "CDCReco_Downstream"; - regionStringPerStraw = "CDCPerStrawReco_Downstream"; + region = kDOWNSTREAM; } - - - Fill1DHistogram(regionString, folder, "Residuals", residual, "Residuals; Residual [cm]; Entries", 200, -0.05, 0.05); - Fill2DHistogram(regionString, folder, "Residual Vs. Momentum", - thisTimeBasedTrack->pmag(), residual, - "Residual Vs. Momentum; Momentum [GeV/c]; Residual [cm]", - 50, 0.0, 12.0, 100, -0.05, 0.05); - Fill2DHistogram(regionString, folder, "Residual Vs. Theta", - thisTimeBasedTrack->momentum().Theta()*TMath::RadToDeg(), residual, - "Residual Vs. Theta; Theta [deg]; Residual [cm]", - 60, 0.0, 180.0, 100, -0.05, 0.05); - Fill2DHistogram(regionString, folder, "Residual Vs. Z", - dz, residual, - "Residual Vs. Z; Z (Measured from CDC center) [cm]; Residual [cm]", - 100, -75.0, 75.0, 100, -0.05, 0.05); - Fill2DHistogram(regionString, folder, "Residual Vs. Tracking FOM", - thisTimeBasedTrack->FOM, residual, - "Residual Vs. Tracking FOM; Tracking FOM; Residual [cm]", - 100, 0.0, 1.0, 100, -0.05, 0.05); - Fill1DHistogram(regionString, folder, "Drift Time", time, "Drift Time; Drift Time [ns]; Entries", 500, -10, 1500); - Fill1DHistogram(regionString, folder, "Drift Distance", distance, "Drift Distance; Drift Distance [cm]; Entries", 250, 0.0, 1.2); - Fill1DHistogram(regionString, folder, "Predicted Drift Distance", predictedDistance, "Predicted Drift Distance; Drift Distance [cm]; Entries", 250, 0.0, 1.2); - - char strawname[100]; - char strawtitle[256]; - sprintf(strawname,"Straw %.3i Drift time Vs phi_DOCA", straw); - sprintf(strawtitle,"Ring %.2i Straw %.3i Drift time Vs phi_DOCA;#phi_{DOCA};Drift Time [ns]", ring, straw); - Fill2DHistogram(regionStringPerStraw,folder,strawname, docaphi, time, - strawtitle, 8, -3.14, 3.14, 500, -10, 1500); - sprintf(strawname,"Straw %.3i Predicted Drift Distance Vs phi_DOCA", straw); - sprintf(strawtitle,"Ring %.2i Straw %.3i Predicted Drift Distance Vs phi_DOCA; #phi_{DOCA};Predicted Distance [cm]", ring, straw); - Fill2DHistogram(regionStringPerStraw,folder,strawname, docaphi, predictedDistance, - strawtitle, 16, -3.14, 3.14, 400, 0.0, 1.2); - char residualname[100]; - char residualtitle[256]; - sprintf(residualname,"Straw %.3i Residual", straw); - sprintf(residualtitle,"Ring %.2i Straw %.3i Residual;Residual [cm]", ring, straw); - Fill1DHistogram(regionStringPerStraw,folder,residualname, residual, residualtitle, 200, -0.05, 0.05); - sprintf(residualname,"Straw %.3i Residual Vs. Z", straw); - sprintf(residualtitle,"Ring %.2i Straw %.3i Residual;Z [cm]; Residual [cm]", ring, straw); - Fill2DHistogram(regionStringPerStraw,folder,residualname, - dz,residual, - residualtitle, - 30, -75.0,75.0,200, -0.05, 0.05); + + // fill per-ring histograms + hResiduals[region][ring-1]->Fill(residual); + hResidualsVsMomentum[region][ring-1]->Fill(thisTimeBasedTrack->pmag(), residual); + hResidualsVsTheta[region][ring-1]->Fill(thisTimeBasedTrack->momentum().Theta()*TMath::RadToDeg(), residual); + hResidualsVsZ[region][ring-1]->Fill(dz, residual); + hResidualsVsTrackingFOM[region][ring-1]->Fill(thisTimeBasedTrack->FOM, residual); + + hDriftTime[region][ring-1]->Fill(time); + hDriftDistance[region][ring-1]->Fill(distance); + hPredictedDriftDistance[region][ring-1]->Fill(predictedDistance); + + hResidualsVsDriftTime[region][ring-1]->Fill(time, residual); + hResidualsVsDriftDistance[region][ring-1]->Fill(distance, residual); + hResidualsVsPredictedDriftDistance[region][ring-1]->Fill(predictedDistance, residual); + hPredictedDriftDistanceVsDriftTime[region][ring-1]->Fill(time, predictedDistance); + + + // fill per-straw histograms + hStrawDriftTimeVsPhiDOCA[region][ring-1][straw-1]->Fill(docaphi, time); + hStrawPredictedDistanceVsPhiDOCA[region][ring-1][straw-1]->Fill(docaphi, predictedDistance); + hStrawResidual[region][ring-1][straw-1]->Fill(residual); + hStrawResidualVsZ[region][ring-1][straw-1]->Fill(dz,residual); //Time to distance relation in bins // Calcuate delta double delta = max_sag[ring - 1][straw - 1]*(1.-dz*dz/5625.) *cos(docaphi + sag_phi_offset[ring - 1][straw - 1]); - sprintf(strawname,"Straw %.3i residual Vs delta", straw); - sprintf(strawtitle,"Ring %.2i Straw %.3i Residual Vs #delta; #delta [cm]; Residual [cm]",ring, straw); - double binwidth = 0.005; + if ( 2 * max_sag[ring - 1][straw - 1] > binwidth){ - Fill2DHistogram(regionStringPerStraw,folder,strawname, delta, residual, - strawtitle, Int_t(2 * max_sag[ring - 1][straw - 1] / binwidth), -1 * max_sag[ring - 1][straw - 1], max_sag[ring - 1][straw - 1], 100, -0.05, 0.05); + hStrawResidualVsDelta[region][ring-1][straw-1]->Fill(delta, residual); } - char binname[150]; - char bintitle[150]; - sprintf(binname,"Straw %.3i Predicted Drift Distance Vs. Drift Time", straw); - sprintf(bintitle,"Ring %.2i Straw %.3i Predicted Drift Distance Vs. Drift Time", ring, straw); - Fill2DHistogram(regionStringPerStraw,folder,binname, time, predictedDistance, - bintitle, 250, -50, 200, 250, 0.0, 0.4); - - sprintf(binname,"Straw %.3i Predicted Drift Distance Vs. delta", straw); - sprintf(bintitle,"Ring %.2i Straw %.3i Predicted Drift Distance Vs. #delta;#delta [cm]; Predicted Drift Distance - Nominal Radius [cm]", ring, straw); - Fill2DHistogram(regionStringPerStraw,folder,binname, delta, predictedDistance - 0.78, - bintitle, 20, -0.25, 0.25, 250, -0.25, 0.25); + hStrawPredictedDriftDistanceVsDriftTime[region][ring-1][straw-1]->Fill(time, predictedDistance); + hStrawPredictedDriftDistanceVsDelta[region][ring-1][straw-1]->Fill(delta, predictedDistance - 0.78); if (delta > 0){ // Long side of straw - sprintf(binname,"Straw %.3i Predicted Drift Distance Vs. Drift Time Positive Delta", straw); - sprintf(bintitle,"Ring %.2i Straw %.3i Predicted Drift Distance Vs. Drift Time (Positive Delta)", ring, straw); - Fill2DHistogram(regionStringPerStraw,folder,binname, time, predictedDistance, - bintitle, 250, -10, 1500, 50, 0.0, 1.2); - sprintf(binname,"Straw %.3i Residual Vs. Drift Time Positive Delta", straw); - sprintf(bintitle,"Ring %.2i Straw %.3i Residual Vs. Drift Time (Positive Delta)", ring, straw); - Fill2DHistogram(regionStringPerStraw,folder,binname, time, residual, - bintitle, 100, -10, 1500, 100, -0.05, 0.05); - sprintf(binname,"Straw %.3i Residual Positive Delta", straw); - sprintf(bintitle,"Ring %.2i Straw %.3i Residual (Positive Delta); Residual [cm]; Entries", ring, straw); - Fill1DHistogram(regionStringPerStraw,folder,binname, residual, bintitle, 200, -0.05, 0.05); + hPredictedDriftDistanceVsDriftTime_PosDelta[region][ring-1][straw-1]->Fill(time, predictedDistance); + hResidualVsDriftTime_PosDelta[region][ring-1][straw-1]->Fill(time, residual); + hResidual_PosDelta[region][ring-1][straw-1]->Fill(residual); } else { // Short side of straw - sprintf(binname,"Straw %.3i Predicted Drift Distance Vs. Drift Time Negative Delta", straw); - sprintf(bintitle,"Ring %.2i Straw %.3i Predicted Drift Distance Vs. Drift Time (Negative Delta)", ring, straw); - Fill2DHistogram(regionStringPerStraw,folder,binname, time, predictedDistance, - bintitle, 250, -10, 1500, 50, 0.0, 1.2); - sprintf(binname,"Straw %.3i Residual Vs. Drift Time Negative Delta", straw); - sprintf(bintitle,"Ring %.2i Straw %.3i Residual Vs. Drift Time (Negative Delta)", ring, straw); - Fill2DHistogram(regionStringPerStraw,folder,binname, time, residual, - bintitle, 100, -10, 1500, 100, -0.05, 0.05); - sprintf(binname,"Straw %.3i Residual Negative Delta", straw); - sprintf(bintitle,"Ring %.2i Straw %.3i Residual (Negative Delta); Residual [cm]; Entries", ring, straw); - Fill1DHistogram(regionStringPerStraw,folder,binname, residual, bintitle, 200, -0.05, 0.05); + hPredictedDriftDistanceVsDriftTime_NegDelta[region][ring-1][straw-1]->Fill(time, predictedDistance); + hResidualVsDriftTime_NegDelta[region][ring-1][straw-1]->Fill(time, residual); + hResidual_NegDelta[region][ring-1][straw-1]->Fill(residual); } - Fill2DHistogram(regionString, folder, "Residual Vs. Drift Time", time, residual, - "Residual Vs. Drift Time; Drift Time [ns]; Residual [cm]", - 500, -10, 1500, 100, -0.05, 0.05); - Fill2DHistogram(regionString, folder, "Residual Vs. Drift Distance", distance, residual, - "Residual Vs. Drift Distance; Drift Distance [cm]; Residual [cm]", - 50, 0.0, 1.0, 100, -0.05, 0.05); - Fill2DHistogram(regionString, folder, "Residual Vs. Predicted Drift Distance", predictedDistance, residual, - "Residual Vs. Predicted Drift Distance; Predicted Drift Distance [cm]; Residual [cm]", - 50, 0.0, 1.0, 100, -0.05, 0.05); - - Fill2DHistogram(regionString, folder, "Predicted Drift Distance Vs. Drift Time", time, predictedDistance, - "Predicted Drift Distance Vs. Drift Time; Drift Time [ns]; Predicted Drift Distance [cm]", - 500, -10, 1500, 100, 0.0, 1.0); } } diff --git a/src/plugins/monitoring/CDC_PerStrawReco/JEventProcessor_CDC_PerStrawReco.h b/src/plugins/monitoring/CDC_PerStrawReco/JEventProcessor_CDC_PerStrawReco.h index 1279eecf5d..899afc71b8 100644 --- a/src/plugins/monitoring/CDC_PerStrawReco/JEventProcessor_CDC_PerStrawReco.h +++ b/src/plugins/monitoring/CDC_PerStrawReco/JEventProcessor_CDC_PerStrawReco.h @@ -10,6 +10,9 @@ #include +#include +#include + class JEventProcessor_CDC_PerStrawReco:public jana::JEventProcessor{ public: JEventProcessor_CDC_PerStrawReco(); @@ -25,6 +28,42 @@ class JEventProcessor_CDC_PerStrawReco:public jana::JEventProcessor{ int EXCLUDERING; vector >max_sag; vector >sag_phi_offset; + + vector> hResiduals; + vector> hResidualsVsMomentum; + vector> hResidualsVsTheta; + vector> hResidualsVsZ; + vector> hResidualsVsTrackingFOM; + + vector> hDriftTime; + vector> hDriftDistance; + vector> hPredictedDriftDistance; + + vector> hResidualsVsDriftTime; + vector> hResidualsVsDriftDistance; + vector> hResidualsVsPredictedDriftDistance; + vector> hPredictedDriftDistanceVsDriftTime; + + + vector>> hStrawResidual; + vector>> hStrawDriftTimeVsPhiDOCA; + vector>> hStrawPredictedDistanceVsPhiDOCA; + vector>> hStrawResidualVsZ; + + vector>> hStrawResidualVsDelta; + vector>> hStrawPredictedDriftDistanceVsDriftTime; + vector>> hStrawPredictedDriftDistanceVsDelta; + + vector>> hPredictedDriftDistanceVsDriftTime_PosDelta; + vector>> hResidualVsDriftTime_PosDelta; + vector>> hResidual_PosDelta; + + vector>> hPredictedDriftDistanceVsDriftTime_NegDelta; + vector>> hResidualVsDriftTime_NegDelta; + vector>> hResidual_NegDelta; + + + }; #endif // _JEventProcessor_CDC_PerStrawReco_ diff --git a/src/plugins/monitoring/FCAL_cpp/HistMacro_FCAL_cpp.C b/src/plugins/monitoring/FCAL_cpp/HistMacro_FCAL_cpp.C new file mode 100644 index 0000000000..3365e4acd1 --- /dev/null +++ b/src/plugins/monitoring/FCAL_cpp/HistMacro_FCAL_cpp.C @@ -0,0 +1,92 @@ +// hnamepath: /FCAL_cpp/h_fcal_nclust +// hnamepath: /FCAL_cpp/h_fcal_nhitonly +// hnamepath: /FCAL_cpp/h_fcal_hcr +// hnamepath: /FCAL_cpp/locProfile_FCALTimeShiftMap + +{ + //Goto Path + TDirectory *locDirectory = (TDirectory*)gDirectory->FindObjectAny("FCAL_cpp"); + if(!locDirectory) + return; + locDirectory->cd(); + + //Get Histograms + TH2F* locHist_FCALClusterOccupancy = (TH2F*)gDirectory->Get("h_fcal_nclust"); + TH2F* locHist_FCALMissedTriggerHit = (TH2F*)gDirectory->Get("h_fcal_nhitonly"); + TH2F* locHist_FCALNoiseHitOccupancy = (TH2F*)gDirectory->Get("h_fcal_hcr"); + TProfile2D* locProfile_FCALTimeShiftMap = (TProfile2D*)gDirectory->Get("h_fcalshower_tall_map"); + + //Get/Make Canvas + TCanvas *locCanvas = NULL; + if(TVirtualPad::Pad() == NULL) + locCanvas = new TCanvas("FCAL_Cpp", "FCAL_Cpp", 1200, 800); //for testing + else + locCanvas = gPad->GetCanvas(); + locCanvas->Divide(2, 2); + + //Draw + locCanvas->cd(1); + gPad->SetTicks(); + gPad->SetGrid(); + if(locHist_FCALClusterOccupancy != NULL) + { + locHist_FCALClusterOccupancy->GetXaxis()->SetTitleSize(0.04); + locHist_FCALClusterOccupancy->GetYaxis()->SetTitleSize(0.04); + locHist_FCALClusterOccupancy->GetXaxis()->SetLabelSize(0.04); + locHist_FCALClusterOccupancy->GetYaxis()->SetLabelSize(0.04); + locHist_FCALClusterOccupancy->GetXaxis()->SetTitle("FCAL Column"); + locHist_FCALClusterOccupancy->GetYaxis()->SetTitle("FCAL Row"); + locHist_FCALClusterOccupancy->SetStats(0); + locHist_FCALClusterOccupancy->Draw("COLZ"); + gPad->SetLogz(); + } + + locCanvas->cd(2); + gPad->SetTicks(); + gPad->SetGrid(); + if(locHist_FCALMissedTriggerHit != NULL) + { + locHist_FCALMissedTriggerHit->GetXaxis()->SetTitleSize(0.04); + locHist_FCALMissedTriggerHit->GetYaxis()->SetTitleSize(0.04); + locHist_FCALMissedTriggerHit->GetXaxis()->SetLabelSize(0.04); + locHist_FCALMissedTriggerHit->GetYaxis()->SetLabelSize(0.04); + locHist_FCALMissedTriggerHit->GetXaxis()->SetTitle("FCAL Column"); + locHist_FCALMissedTriggerHit->GetYaxis()->SetTitle("FCAL Row"); + locHist_FCALMissedTriggerHit->SetStats(0); + locHist_FCALMissedTriggerHit->Draw("COLZ"); +// gPad->SetLogz(); + } + + locCanvas->cd(3); + gPad->SetTicks(); + gPad->SetGrid(); + if(locHist_FCALNoiseHitOccupancy != NULL) + { + locHist_FCALNoiseHitOccupancy->GetXaxis()->SetTitleSize(0.04); + locHist_FCALNoiseHitOccupancy->GetYaxis()->SetTitleSize(0.04); + locHist_FCALNoiseHitOccupancy->GetXaxis()->SetLabelSize(0.04); + locHist_FCALNoiseHitOccupancy->GetYaxis()->SetLabelSize(0.04); + locHist_FCALNoiseHitOccupancy->GetXaxis()->SetTitle("FCAL Column"); + locHist_FCALNoiseHitOccupancy->GetYaxis()->SetTitle("FCAL Row"); + locHist_FCALNoiseHitOccupancy->SetStats(0); + locHist_FCALNoiseHitOccupancy->Draw("COLZ"); + } + + locCanvas->cd(4); + gPad->SetTicks(); + gPad->SetGrid(); + if(locProfile_FCALTimeShiftMap != NULL) + { + locProfile_FCALTimeShiftMap->GetXaxis()->SetTitleSize(0.04); + locProfile_FCALTimeShiftMap->GetYaxis()->SetTitleSize(0.04); + locProfile_FCALTimeShiftMap->GetXaxis()->SetLabelSize(0.04); + locProfile_FCALTimeShiftMap->GetYaxis()->SetLabelSize(0.04); + locProfile_FCALTimeShiftMap->GetXaxis()->SetTitle("FCAL Column"); + locProfile_FCALTimeShiftMap->GetYaxis()->SetTitle("FCAL Row"); + locProfile_FCALTimeShiftMap->GetZaxis()->SetRangeUser(-10,10); + locProfile_FCALTimeShiftMap->SetStats(0); + locProfile_FCALTimeShiftMap->Draw("COLZ"); + } + +} + diff --git a/src/plugins/monitoring/FCAL_cpp/JEventProcessor_FCAL_cpp.cc b/src/plugins/monitoring/FCAL_cpp/JEventProcessor_FCAL_cpp.cc new file mode 100644 index 0000000000..157d3d23b0 --- /dev/null +++ b/src/plugins/monitoring/FCAL_cpp/JEventProcessor_FCAL_cpp.cc @@ -0,0 +1,247 @@ +// $Id$ +// +// File: JEventProcessor_FCAL_cpp.cc +// Created: Mon Feb 19 16:33:33 EST 2024 +// Creator: ilarin (on Linux ifarm1801.jlab.org 3.10.0-1160.102.1.el7.x86_64 x86_64) +// + +#include "JEventProcessor_FCAL_cpp.h" +using namespace jana; + + +// Routine used to create our JEventProcessor +#include +#include + + +#include +#include +#include +#include + + +extern "C"{ +void InitPlugin(JApplication *app){ + InitJANAPlugin(app); + app->AddProcessor(new JEventProcessor_FCAL_cpp()); +} +} // "C" + + +//------------------ +// JEventProcessor_FCAL_cpp (Constructor) +//------------------ +JEventProcessor_FCAL_cpp::JEventProcessor_FCAL_cpp() +{ + +} + +//------------------ +// ~JEventProcessor_FCAL_cpp (Destructor) +//------------------ +JEventProcessor_FCAL_cpp::~JEventProcessor_FCAL_cpp() +{ + +} + +//------------------ +// init +//------------------ +jerror_t JEventProcessor_FCAL_cpp::init(void) +{ + // This is called once at program startup. + + memset(fcal_nhit,0,sizeof(fcal_nhit)); + memset(fcal_nclust,0,sizeof(fcal_nclust)); + memset(fcal_nhitonly,0,sizeof(fcal_nhitonly)); + nfcaltriggers = 0; ntoftriggers = 0; + + // create root folder for this plugin and cd to it, store main dir + TDirectory *main = gDirectory; + gDirectory->mkdir("FCAL_cpp")->cd(); + + + h_fcalshower_tall = new TProfile("h_fcalshower_tall", "Shower Time Alignment", N_FCAL_BLOCKS, -0.5, N_FCAL_BLOCKS-0.5, -50., 50.); + h_fcalshower_tw = new TProfile("h_fcalshower_tw", "Shower Time Walk", 100, 0., 10, -20., 20.); + h_fcal_nclust = new TH2F("h_fcal_nclust","Cluster Occupancy", 59, -0.5, 58.5, 59, -0.5, 58.5); + h_fcal_nhitonly = new TH2F("h_fcal_nhitonly","Missed Trigger Hit Occupancy", 59, -0.5, 58.5, 59, -0.5, 58.5); + h_fcal_hcr = new TH2F("h_fcal_hcr","Noise Hit Occupancy", 59, -0.5, 58.5, 59, -0.5, 58.5); + + h_fcalshower_tall_map = new TProfile2D("h_fcalshower_tall_map","FCAL Shower Time Shift Map", 59, -0.5, 58.5, 59, -0.5, 58.5); + h_fcalehit_tall_map = new TProfile2D("h_fcalehit_tall_map","FCAL Low-Energy Hit Map", 59, -0.5, 58.5, 59, -0.5, 58.5); + + main->cd(); + + return NOERROR; +} + +//------------------ +// brun +//------------------ +jerror_t JEventProcessor_FCAL_cpp::brun(JEventLoop *loop, int32_t runnumber) +{ + // This is called whenever the run number changes + + vector fcalGeomVect; + loop->Get(fcalGeomVect); + fcalGeom = fcalGeomVect[0]; + + return NOERROR; +} + +//------------------ +// evnt +//------------------ +jerror_t JEventProcessor_FCAL_cpp::evnt(JEventLoop *loop, uint64_t eventnumber) +{ + + vector l1trig; + loop->Get(l1trig); + + int fcaltrigger = 0, toftrigger = 0; + if(l1trig.size()) { + if( (l1trig[0]->trig_mask & (1 << (1-1))) ) fcaltrigger = 1; + if( (l1trig[0]->trig_mask & (1 << (2-1))) && ! fcaltrigger) toftrigger = 1; + } + + if(!fcaltrigger&&!toftrigger) return NOERROR; + if(fcaltrigger) ++nfcaltriggers; + if(toftrigger) ++ntoftriggers; + + vector fcal_hits; + loop->Get(fcal_hits); + + vector fcal_clusters; + loop->Get(fcal_clusters); + + vector fcal_showers; + loop->Get(fcal_showers); + + double efcaltot = 0., efcalmax = 0.; + for(unsigned int i = 0; iE; + if(fcale>0.05) efcaltot += fcale; + if(fcale>efcalmax) efcalmax = fcale; + } + + for(unsigned int i = 0; iE; + int row = fcal_hit->row; + int col = fcal_hit->column; + + if(fcaltrigger&&fcale>1.0&&(efcaltot-fcale)<1.0&&fcale>0.9*efcalmax) fcal_nhitonly[row][col][0] += 1.; + if(toftrigger&&fcale>1.0&&(efcaltot-fcale)<1.0&&fcale>0.9*efcalmax) fcal_nhitonly[row][col][1] += 1.; + + if(fcaltrigger&&fcale>0.3) fcal_nhit[row][col] += 1.; + if(fcale<0.3) { + japp->RootFillLock(this); //ACQUIRE ROOT FILL LOCK + h_fcalehit_tall_map->Fill(col,row,fcale); + japp->RootFillUnLock(this); //RELEASE ROOT FILL LOCK + } + } + + for(unsigned int i = 0; igetChannelEmax(); + double e = fcal_cluster->getEnergy(); + int dim = fcal_cluster->getHits(); + int row = fcalGeom->row(block); + int col = fcalGeom->column(block); + if(fcaltrigger&&e>0.3&&dim>2) fcal_nclust[row][col] += 1.; + } + + for(unsigned int i = 0; igetTime(); + double e = fcal_shower->getEnergy(); + const DFCALCluster* locAssociatedCluster = NULL; + fcal_shower->GetSingle(locAssociatedCluster); + if(!locAssociatedCluster) continue; + int id = locAssociatedCluster->getChannelEmax(); + int row = fcalGeom->row(id); + int col = fcalGeom->column(id); + for(unsigned int j = i+1; jgetTime(); + double e2 = fcal_shower2->getEnergy(); + if(e2>1.0&&e2<3.0) { + japp->RootFillLock(this); //ACQUIRE ROOT FILL LOCK + if(e>1.0&&e<3.0) { + h_fcalshower_tall->Fill(id,t-t2); + h_fcalshower_tall_map->Fill(col,row,t-t2); + } + if(e2>1.5&&e2<2.5) h_fcalshower_tw->Fill(e,t-t2); + japp->RootFillUnLock(this); //RELEASE ROOT FILL LOCK + } + } + } + + return NOERROR; +} + +//------------------ +// erun +//------------------ +jerror_t JEventProcessor_FCAL_cpp::erun(void) +{ + // This is called whenever the run number changes, before it is + // changed to give you a chance to clean up before processing + // events from the next run number. + return NOERROR; +} + +//------------------ +// fini +//------------------ +jerror_t JEventProcessor_FCAL_cpp::fini(void) +{ + // Called before program exit after event processing is finished. + + if(nfcaltriggers>1000) + for(int i = 0; i<59; ++i) + for(int j = 0; j<59; ++j) { + + h_fcal_nclust->SetBinContent(i+1, j+1, fcal_nclust[j][i]/double(nfcaltriggers)); + h_fcal_nclust->SetBinError(i+1, j+1, sqrt(fcal_nclust[j][i])/double(nfcaltriggers)); + + if(ntoftriggers) { + int n0 = fcal_nhitonly[j][i][0], n1 = fcal_nhitonly[j][i][1]; + + double p = 0., ep = 0.; + + if(n0==0 && n1==0) { + p = 0.; + ep = 1.; + } + + if(n0==0 && n1>0) { + p = 1.; + ep = 1./double(n1); + } + + if(n0>0 && n1==0) { + p = 0.; + ep = 1./double(n0); + } + + if(n0>0 && n1>0) { + p = double(n1) / double(n0+n1); + ep = sqrt( p*(1.-p)/double(n0+n1) ); + } + + h_fcal_nhitonly->SetBinContent(i+1, j+1, p); + h_fcal_nhitonly->SetBinError(i+1, j+1, ep); + } + + if(fcal_nclust[i][j]) { + double r = fcal_nhit[j][i]/fcal_nclust[j][i]; + h_fcal_hcr->SetBinContent(i+1, j+1, r); + h_fcal_hcr->SetBinError(i+1, j+1, sqrt(fcal_nhit[j][i]*(1.+r))/fcal_nclust[j][i]); + } + } + + return NOERROR; +} + diff --git a/src/plugins/monitoring/FCAL_cpp/JEventProcessor_FCAL_cpp.h b/src/plugins/monitoring/FCAL_cpp/JEventProcessor_FCAL_cpp.h new file mode 100644 index 0000000000..6b4f56ac77 --- /dev/null +++ b/src/plugins/monitoring/FCAL_cpp/JEventProcessor_FCAL_cpp.h @@ -0,0 +1,46 @@ +// $Id$ +// +// File: JEventProcessor_FCAL_cpp.h +// Created: Mon Feb 19 16:33:33 EST 2024 +// Creator: ilarin (on Linux ifarm1801.jlab.org 3.10.0-1160.102.1.el7.x86_64 x86_64) +// + +#ifndef _JEventProcessor_FCAL_cpp_ +#define _JEventProcessor_FCAL_cpp_ + +#include +#include "FCAL/DFCALGeometry.h" + +#include +#include +#include "TProfile.h" +#include +#include + +const int N_FCAL_BLOCKS = 2800, NROW = 59, NCOL = 59; + +class JEventProcessor_FCAL_cpp:public jana::JEventProcessor{ + public: + JEventProcessor_FCAL_cpp(); + ~JEventProcessor_FCAL_cpp(); + const char* className(void){return "JEventProcessor_FCAL_cpp";} + + private: + jerror_t init(void); ///< Called once at program start. + jerror_t brun(jana::JEventLoop *eventLoop, int32_t runnumber); ///< Called everytime a new run number is detected. + jerror_t evnt(jana::JEventLoop *eventLoop, uint64_t eventnumber); ///< Called every event. + jerror_t erun(void); ///< Called everytime run number changes, provided brun has been called. + jerror_t fini(void); ///< Called after last event of last event source has been processed. + + + double fcal_nhit[NROW][NCOL], fcal_nclust[NROW][NCOL], fcal_nhitonly[NROW][NCOL][2], nfcaltriggers, ntoftriggers; + + const DFCALGeometry *fcalGeom; + + TH2F *h_fcal_nclust, *h_fcal_nhitonly, *h_fcal_hcr; + TProfile *h_fcalshower_tall, *h_fcalshower_tw; + TProfile2D *h_fcalshower_tall_map, *h_fcalehit_tall_map; +}; + +#endif // _JEventProcessor_FCAL_cpp_ + diff --git a/src/plugins/monitoring/FCAL_cpp/SConscript b/src/plugins/monitoring/FCAL_cpp/SConscript new file mode 100644 index 0000000000..8ef0539a2b --- /dev/null +++ b/src/plugins/monitoring/FCAL_cpp/SConscript @@ -0,0 +1,13 @@ + + +import sbms + +# get env object and clone it +Import('*') +env = env.Clone() + +sbms.AddROOTSpyMacros(env) +sbms.AddDANA(env) +sbms.plugin(env) + + diff --git a/src/plugins/monitoring/FDC_Efficiency/JEventProcessor_FDC_Efficiency.cc b/src/plugins/monitoring/FDC_Efficiency/JEventProcessor_FDC_Efficiency.cc index 21ea575843..c47c9ed14c 100644 --- a/src/plugins/monitoring/FDC_Efficiency/JEventProcessor_FDC_Efficiency.cc +++ b/src/plugins/monitoring/FDC_Efficiency/JEventProcessor_FDC_Efficiency.cc @@ -50,6 +50,21 @@ static TH1I *hPseudoTime_accepted[25]; static TH1I *hPullTime[25]; static TH1I *hDeltaTime[25]; +static TH1F *hExpectedHitsVsDOCA; +static TH1F *hExpectedHitsVsTrackingFOM; +static TH1F *hExpectedHitsVsTheta; +static TH1F *hExpectedHitsVsMom; +static TH1F *hExpectedHitsVsPhi; +static TH1F *hExpectedHitsVsHitCells; + +static TH1F *hMeasuredHitsVsDOCA; +static TH1F *hMeasuredHitsVsTrackingFOM; +static TH1F *hMeasuredHitsVsTheta; +static TH1F *hMeasuredHitsVsMom; +static TH1F *hMeasuredHitsVsPhi; +static TH1F *hMeasuredHitsVsHitCells; + + // Routine used to create our JEventProcessor #include #include @@ -103,7 +118,7 @@ jerror_t JEventProcessor_FDC_Efficiency::init(void) } - gDirectory->cd("/FDC_Efficiency"); + gDirectory->cd(".."); gDirectory->mkdir("Track_Quality")->cd(); hChi2OverNDF = new TH1I("hChi2OverNDF","hChi2OverNDF", 500, 0.0, 1.0); hChi2OverNDF_accepted = new TH1I("hChi2OverNDF_accepted","hChi2OverNDF_accepted", 500, 0.0, 1.0); @@ -120,7 +135,7 @@ jerror_t JEventProcessor_FDC_Efficiency::init(void) hRingsHit_vs_P = new TH2I("hRingsHit_vs_P", "Rings of CDC Contributing to Track vs P (accepted)", 25, -0.5, 24.5, 34, 0.6, 4); - gDirectory->cd("/FDC_Efficiency"); + gDirectory->cd(".."); gDirectory->mkdir("Residuals")->cd(); hPseudoRes = new TH1I("hPseudoRes","Pseudo Residual in R", 500, 0, 5); @@ -172,6 +187,24 @@ jerror_t JEventProcessor_FDC_Efficiency::init(void) } + main->cd("FDC_Efficiency"); + gDirectory->mkdir("Offline")->cd(); + + hExpectedHitsVsDOCA = new TH1F("Expected Hits Vs DOCA", "Expected Hits", 100, 0 , 0.5); + hExpectedHitsVsTrackingFOM = new TH1F("Expected Hits Vs Tracking FOM", "Expected Hits", 100, 0 , 1.0); + hExpectedHitsVsTheta = new TH1F("Expected Hits Vs theta", "Expected Hits", 100, 0, 180); + hExpectedHitsVsMom = new TH1F("Expected Hits Vs p", "Expected Hits", 100, 0 , 10.0); + hExpectedHitsVsPhi = new TH1F("Expected Hits Vs phi", "Expected Hits", 100, -180, 180); + hExpectedHitsVsHitCells = new TH1F("Expected Hits Vs Hit Cells", "Expected Hits", 25, -0.5 , 24.5); + + hMeasuredHitsVsDOCA = new TH1F("Measured Hits Vs DOCA", "Measured Hits", 100, 0 , 0.5); + hMeasuredHitsVsTrackingFOM = new TH1F("Measured Hits Vs Tracking FOM", "Measured Hits", 100, 0 , 1.0); + hMeasuredHitsVsTheta = new TH1F("Measured Hits Vs theta", "Measured Hits", 100, 0, 180); + hMeasuredHitsVsMom = new TH1F("Measured Hits Vs p", "Measured Hits", 100, 0 , 10.0); + hMeasuredHitsVsPhi = new TH1F("Measured Hits Vs phi", "Measured Hits", 100, -180, 180); + hMeasuredHitsVsHitCells = new TH1F("Measured Hits Vs Hit Cells", "Measured Hits", 25, -0.5 , 24.5); + + main->cd(); return NOERROR; @@ -275,8 +308,10 @@ jerror_t JEventProcessor_FDC_Efficiency::evnt(JEventLoop *loop, uint64_t eventnu vector pulls = thisTimeBasedTrack->pulls; for (unsigned int i = 0; i < pulls.size(); i++){ const DFDCPseudo * thisTrackFDCHit = pulls[i].fdc_hit; - if (thisTrackFDCHit != NULL){ + if (thisTrackFDCHit != NULL){ + japp->RootFillLock(this); //ACQUIRE ROOT FILL LOCK hPullTime[thisTrackFDCHit->wire->layer]->Fill(pulls[i].tdrift); + japp->RootFillUnLock(this); //RELEASE ROOT FILL LOCK if ( find(cellsHit.begin(), cellsHit.end(), thisTrackFDCHit->wire->layer) == cellsHit.end()) cellsHit.push_back(thisTrackFDCHit->wire->layer); } @@ -426,13 +461,16 @@ jerror_t JEventProcessor_FDC_Efficiency::evnt(JEventLoop *loop, uint64_t eventnu if (expectHit && fdc_wire_expected_cell[cellNum] != NULL && cellNum < 25){ - Fill1DHistogram("FDC_Efficiency", "Offline", "Expected Hits Vs DOCA", distanceToWire, "Expected Hits", 100, 0 , 0.5); - Fill1DHistogram("FDC_Efficiency", "Offline", "Expected Hits Vs Tracking FOM", thisTimeBasedTrack->FOM, "Expected Hits", 100, 0 , 1.0); - Fill1DHistogram("FDC_Efficiency", "Offline", "Expected Hits Vs theta", theta_deg, "Expected Hits", 100, 0, 180); - Fill1DHistogram("FDC_Efficiency", "Offline", "Expected Hits Vs phi", phi_deg, "Measured Hits", 100, -180, 180); - Fill1DHistogram("FDC_Efficiency", "Offline", "Expected Hits Vs p", tmom, "Expected Hits", 100, 0 , 10.0); - Fill1DHistogram("FDC_Efficiency", "Offline", "Expected Hits Vs Hit Cells", cells, "Expected Hits", 25, -0.5 , 24.5); - + + japp->RootFillLock(this); //ACQUIRE ROOT FILL LOCK + hExpectedHitsVsDOCA->Fill(distanceToWire); + hExpectedHitsVsTrackingFOM->Fill(thisTimeBasedTrack->FOM); + hExpectedHitsVsTheta->Fill(theta_deg); + hExpectedHitsVsMom->Fill(tmom); + hExpectedHitsVsPhi->Fill(phi_deg); + hExpectedHitsVsHitCells->Fill(cells); + japp->RootFillUnLock(this); //RELEASE ROOT FILL LOCK + Double_t w, v; if(fdc_wire_expected_cell[cellNum] != NULL && cellNum < 25){ // FILL HISTOGRAMS @@ -459,13 +497,15 @@ jerror_t JEventProcessor_FDC_Efficiency::evnt(JEventLoop *loop, uint64_t eventnu } } - Fill1DHistogram("FDC_Efficiency", "Offline", "Measured Hits Vs DOCA", distanceToWire, "Measured Hits", 100, 0 , 0.5); - Fill1DHistogram("FDC_Efficiency", "Offline", "Measured Hits Vs Tracking FOM", thisTimeBasedTrack->FOM, "Measured Hits", 100, 0 , 1.0); - Fill1DHistogram("FDC_Efficiency", "Offline", "Measured Hits Vs theta", theta_deg, "Measured Hits", 100, 0, 180); - Fill1DHistogram("FDC_Efficiency", "Offline", "Measured Hits Vs phi", phi_deg, "Measured Hits", 100, -180, 180); - Fill1DHistogram("FDC_Efficiency", "Offline", "Measured Hits Vs p", tmom, "Measured Hits", 100, 0 , 10.0); - Fill1DHistogram("FDC_Efficiency", "Offline", "Measured Hits Vs Hit Cells", cells, "Measured Hits", 25, -0.5 , 24.5); - + japp->RootFillLock(this); //ACQUIRE ROOT FILL LOCK + hMeasuredHitsVsDOCA->Fill(distanceToWire); + hMeasuredHitsVsTrackingFOM->Fill(thisTimeBasedTrack->FOM); + hMeasuredHitsVsTheta->Fill(theta_deg); + hMeasuredHitsVsMom->Fill(tmom); + hMeasuredHitsVsPhi->Fill(phi_deg); + hMeasuredHitsVsHitCells->Fill(cells); + japp->RootFillUnLock(this); //RELEASE ROOT FILL LOCK + japp->RootFillLock(this); //ACQUIRE ROOT FILL LOCK v = fdc_wire_measured_cell[cellNum]->GetBinContent(wireNum, 1) + 1.0; fdc_wire_measured_cell[cellNum]->SetBinContent(wireNum, 1, v); diff --git a/src/plugins/monitoring/FMWPC_Performance/JEventProcessor_FMWPC_Performance.cc b/src/plugins/monitoring/FMWPC_Performance/JEventProcessor_FMWPC_Performance.cc index 423ca3584e..d0c7a2f514 100644 --- a/src/plugins/monitoring/FMWPC_Performance/JEventProcessor_FMWPC_Performance.cc +++ b/src/plugins/monitoring/FMWPC_Performance/JEventProcessor_FMWPC_Performance.cc @@ -439,8 +439,9 @@ jerror_t JEventProcessor_FMWPC_Performance::evnt(JEventLoop *loop, uint64_t even double Jphi = atan2(JTy, JTx)*180/acos(-1); double MLPClassifierMinus=cppepem->pimem_ML_classifier; - hpimem_ML_classifier->Fill(MLPClassifierMinus); double MLPClassifierPlus=cppepem->pipep_ML_classifier; + japp->RootFillLock(this); //ACQUIRE ROOT FILL LOCK + hpimem_ML_classifier->Fill(MLPClassifierMinus); hpipep_ML_classifier->Fill(MLPClassifierPlus); if(MLPClassifierPlus > 0.8 && MLPClassifierMinus > 0.8){ hphiJT->Fill(Jphi, weight); @@ -483,6 +484,7 @@ jerror_t JEventProcessor_FMWPC_Performance::evnt(JEventLoop *loop, uint64_t even hCosTheta_mumu->Fill(CosTheta,weight); hCosTheta_vs_psi_mumu->Fill(psi*TMath::RadToDeg(), CosTheta); } + japp->RootFillUnLock(this); //RELEASE ROOT FILL LOCK } diff --git a/src/plugins/monitoring/FMWPC_online/CTOF_energy.C b/src/plugins/monitoring/FMWPC_online/CTOF_energy.C new file mode 100644 index 0000000000..3a411b6350 --- /dev/null +++ b/src/plugins/monitoring/FMWPC_online/CTOF_energy.C @@ -0,0 +1,145 @@ + +// The following are special comments used by RootSpy to know +// which histograms to fetch for the macro. +// +// hnamepath: /FMWPC/h1_ctof_dE +// hnamepath: /FMWPC/h2_ctof_t +// hnamepath: /FMWPC/h2_ctof_t_adc +// +// + +{ + TDirectory *savedir = gDirectory; + TDirectory *dir = (TDirectory*)gDirectory->FindObjectAny("FMWPC"); + if(dir) dir->cd(); + + TH1I *hr_u = (TH1I*)gDirectory->FindObjectAny("h1_ctof_occ_up"); + TH1I *hr_d = (TH1I*)gDirectory->FindObjectAny("h1_ctof_occ_down"); + + TH2F *h_de = (TH2F*)gDirectory->FindObjectAny("h1_ctof_dE"); + TH2D *h_t = (TH2D*)gDirectory->FindObjectAny("h2_ctof_t"); + TH2D *h_t_adc = (TH2D*)gDirectory->FindObjectAny("h2_ctof_t_adc"); + TH2D *h_adc_tdc = (TH2D*)gDirectory->FindObjectAny("h2_ctof_t_adc_tdc"); + + TLegend *legend_ru = new TLegend(0.5,0.85,0.7,0.9); + TLegend *legend_rd = new TLegend(0.7,0.85,0.9,0.9); + + if(hr_u){ + hr_u->SetBarWidth(0.5); + hr_u->SetBarOffset(0); + hr_u->SetFillColor(2); + hr_u->SetStats(0); + hr_u->SetXTitle("Bar Number"); + hr_u->SetYTitle("Occupancy"); + hr_u->SetTitleSize(0.05,"X"); + hr_u->GetXaxis()->CenterTitle(); + hr_u->SetTitleSize(0.05,"Y"); + hr_u->GetYaxis()->CenterTitle(); + hr_u->GetYaxis()->SetRangeUser(0,1.1*hr_u->GetMaximum()); + } + if(hr_d){ + hr_d->SetBarWidth(0.5); + hr_d->SetBarOffset(0.5); + hr_d->SetFillColor(3); + hr_d->SetStats(0); + } + + if(h_de){ + h_de->SetXTitle("Bar Number"); + h_de->SetYTitle("Energy GeV"); + h_de->SetStats(0); + h_de->SetTitleSize(0.05,"X"); + h_de->GetXaxis()->CenterTitle(); + h_de->SetTitleSize(0.05,"Y"); + h_de->GetYaxis()->CenterTitle(); + } + + if(h_t){ + h_t->SetXTitle("Bar Number"); + h_t->SetYTitle("Calibrated Time"); + h_t->SetStats(0); + h_t->SetTitleSize(0.05,"X"); + h_t->GetXaxis()->CenterTitle(); + h_t->SetTitleSize(0.05,"Y"); + h_t->GetYaxis()->CenterTitle(); + } + + if(h_t_adc){ + h_t_adc->SetXTitle("Bar Number"); + h_t_adc->SetYTitle("Calibrated ADC Time"); + h_t_adc->SetStats(0); + h_t_adc->SetTitleSize(0.05,"X"); + h_t_adc->GetXaxis()->CenterTitle(); + h_t_adc->SetTitleSize(0.05,"Y"); + h_t_adc->GetYaxis()->CenterTitle(); + } + + if(h_adc_tdc){ + h_adc_tdc->SetXTitle("Bar Number"); + h_adc_tdc->SetYTitle("ADC - TDC Time"); + h_adc_tdc->SetTitleSize(0.05,"X"); + h_adc_tdc->GetXaxis()->CenterTitle(); + h_adc_tdc->SetTitleSize(0.05,"Y"); + h_adc_tdc->GetYaxis()->CenterTitle(); + } + + legend_ru->AddEntry(hr_u,"Up","f"); + legend_rd->AddEntry(hr_d,"Down","f"); + + if(gPad == NULL){ + TCanvas *c1 = new TCanvas("c1"); + c1->cd(0); + c1->Draw(); + c1->Update(); + } + if(!gPad) {savedir->cd(); return;} + + TCanvas *c1 = gPad->GetCanvas(); + c1->cd(0); + c1->Clear(); + + c1->Divide(3,1); + + //TVirtualPad *pad1 = c1->cd(1); + //pad1->SetTicks(); + //pad1->SetGridy(); + //if(hr_u) hr_u->Draw("BAR"); + //if(hr_d) hr_d->Draw("BAR sames"); + + //legend_ru->Draw(); + //legend_rd->Draw(); + + TVirtualPad *pad1 = c1->cd(1); + pad1->SetTicks(); + pad1->SetGridy(); + if(h_de) h_de->Draw("BAR colz0"); + + TVirtualPad *pad2 = c1->cd(2); + pad2->SetTicks(); + pad2->SetGridy(); + if(h_t) h_t->Draw("BAR colz0"); + + //TVirtualPad *pad4 = c1->cd(4); + //pad4->SetTicks(); + //pad4->SetGridy(); + //if(h_t_adc) h_t_adc->Draw("BAR colz0"); + + TVirtualPad *pad3 = c1->cd(3); + pad3->SetTicks(); + pad3->SetGridy(); + if(h_adc_tdc) h_adc_tdc->Draw("BAR colz0"); + +#ifdef ROOTSPY_MACROS + // ------ The following is used by RSAI -------- + if( rs_GetFlag("Is_RSAI")==1 ){ + auto min_events = 5*rs_GetFlag("MIN_EVENTS_RSAI"); + if( min_events < 1 ) min_events = 5E5; + if( adc_events >= min_events ) { + cout << "CTOF Flagging AI check after " << adc_events << " events (>=" << min_events << ")" << endl; + rs_SavePad("CTOF_occupancy", 0); + rs_ResetAllMacroHistos("//CTOF_occupancy"); + } + } +#endif + +} diff --git a/src/plugins/monitoring/FMWPC_online/CTOF_occupancy.C b/src/plugins/monitoring/FMWPC_online/CTOF_occupancy.C index 45a87f835f..184c473e4d 100644 --- a/src/plugins/monitoring/FMWPC_online/CTOF_occupancy.C +++ b/src/plugins/monitoring/FMWPC_online/CTOF_occupancy.C @@ -80,6 +80,7 @@ h_d->SetStats(0); } + legend_ua->AddEntry(ha_u,"Up","f"); legend_da->AddEntry(ha_d,"Down","f"); @@ -100,7 +101,7 @@ c1->cd(0); c1->Clear(); - c1->Divide(1,2); + c1->Divide(2,1); TVirtualPad *pad1 = c1->cd(1); pad1->SetTicks(); pad1->SetGridy(); @@ -117,7 +118,7 @@ if(h_d) h_d->Draw("BAR sames"); legend_u->Draw(); - legend_d->Draw(); + legend_d->Draw(); #ifdef ROOTSPY_MACROS // ------ The following is used by RSAI -------- diff --git a/src/plugins/monitoring/FMWPC_online/FMWPC_energy.C b/src/plugins/monitoring/FMWPC_online/FMWPC_energy.C new file mode 100644 index 0000000000..8062085864 --- /dev/null +++ b/src/plugins/monitoring/FMWPC_online/FMWPC_energy.C @@ -0,0 +1,90 @@ +// The following are special comments used by RootSpy to know +// which histograms to fetch for the macro. +// +// hnamepath: /FMWPC/h2_fmwpc_time_chamber +// hnamepath: /FMWPC/h2_fmwpc_pic_chamber +{ + TDirectory *savedir = gDirectory; + TDirectory *dir = (TDirectory*)gDirectory->FindObjectAny("FMWPC"); + if(dir) dir->cd(); + + //Calibrated Hit + TH1F *fmwpc_hit_layer_1 = (TH1F*)gDirectory->FindObjectAny("fmwpc_hit_layer_1"); + TH1F *fmwpc_hit_layer_2 = (TH1F*)gDirectory->FindObjectAny("fmwpc_hit_layer_2"); + TH1F *fmwpc_hit_layer_3 = (TH1F*)gDirectory->FindObjectAny("fmwpc_hit_layer_3"); + TH1F *fmwpc_hit_layer_4 = (TH1F*)gDirectory->FindObjectAny("fmwpc_hit_layer_4"); + TH1F *fmwpc_hit_layer_5 = (TH1F*)gDirectory->FindObjectAny("fmwpc_hit_layer_5"); + TH1F *fmwpc_hit_layer_6 = (TH1F*)gDirectory->FindObjectAny("fmwpc_hit_layer_6"); + + //Chamber Times + TH1F *fmwpc_time_chamber_1 = (TH1F*)gDirectory->FindObjectAny("fmwpc_time_chamber_1"); + TH1F *fmwpc_time_chamber_2 = (TH1F*)gDirectory->FindObjectAny("fmwpc_time_chamber_2"); + TH1F *fmwpc_time_chamber_3 = (TH1F*)gDirectory->FindObjectAny("fmwpc_time_chamber_3"); + TH1F *fmwpc_time_chamber_4 = (TH1F*)gDirectory->FindObjectAny("fmwpc_time_chamber_4"); + TH1F *fmwpc_time_chamber_5 = (TH1F*)gDirectory->FindObjectAny("fmwpc_time_chamber_5"); + TH1F *fmwpc_time_chamber_6 = (TH1F*)gDirectory->FindObjectAny("fmwpc_time_chamber_6"); + + //Chamber Pulse Integral + TH1D *fmwpc_pulse_integral_chamber_1 = (TH1D*)gDirectory->FindObjectAny("fmwpc_pulse_integral_chamber_1"); + TH1D *fmwpc_pulse_integral_chamber_2 = (TH1D*)gDirectory->FindObjectAny("fmwpc_pulse_integral_chamber_2"); + TH1D *fmwpc_pulse_integral_chamber_3 = (TH1D*)gDirectory->FindObjectAny("fmwpc_pulse_integral_chamber_3"); + TH1D *fmwpc_pulse_integral_chamber_4 = (TH1D*)gDirectory->FindObjectAny("fmwpc_pulse_integral_chamber_4"); + TH1D *fmwpc_pulse_integral_chamber_5 = (TH1D*)gDirectory->FindObjectAny("fmwpc_pulse_integral_chamber_5"); + TH1D *fmwpc_pulse_integral_chamber_6 = (TH1D*)gDirectory->FindObjectAny("fmwpc_pulse_integral_chamber_6"); + + TH1I *fmwpc_occ_chamber = (TH1I*)gDirectory->FindObjectAny("h1_fmwpc_occ_chamber"); + + //For Rootspy + TH2F *h2_fmwpc_time_chamber = (TH2F*)gDirectory->FindObjectAny("h2_fmwpc_time_chamber"); + TH2D *h2_fmwpc_pi_chamber = (TH2D*)gDirectory->FindObjectAny("h2_fmwpc_pi_chamber"); + + // Just for testing + if(gPad == NULL){ + TCanvas *c1 = new TCanvas("c1"); + c1->cd(0); + c1->Draw(); + c1->Update(); + } + if(!gPad) {savedir->cd(); return;} + + TCanvas *c1 = gPad->GetCanvas(); + c1->Divide(2,1); + + TVirtualPad *pad1 = c1->cd(1); + pad1->SetTicks(); + pad1->SetLeftMargin(0.15); + pad1->SetRightMargin(0.15); + if(h2_fmwpc_time_chamber){ + h2_fmwpc_time_chamber->SetStats(0); + h2_fmwpc_time_chamber->GetXaxis()->SetLabelSize(0.05); + h2_fmwpc_time_chamber->GetYaxis()->SetLabelSize(0.05); + h2_fmwpc_time_chamber->GetXaxis()->SetTitleSize(0.05); + h2_fmwpc_time_chamber->Draw("h colz0"); + } + + TVirtualPad *pad2 = c1->cd(2); + pad2->SetTicks(); + pad2->SetLeftMargin(0.15); + pad2->SetRightMargin(0.15); + if(h2_fmwpc_pi_chamber){ + h2_fmwpc_pi_chamber->SetStats(0); + h2_fmwpc_pi_chamber->GetXaxis()->SetLabelSize(0.05); + h2_fmwpc_pi_chamber->GetYaxis()->SetLabelSize(0.05); + h2_fmwpc_pi_chamber->GetXaxis()->SetTitleSize(0.05); + h2_fmwpc_pi_chamber->Draw("h colz0"); + } + +#ifdef ROOTSPY_MACROS + // ------ The following is used by RSAI -------- + if( rs_GetFlag("Is_RSAI")==1 ){ + auto min_events = 5*rs_GetFlag("MIN_EVENTS_RSAI"); + if( min_events < 1 ) min_events = 5E5; + if( Nevents >= min_events ) { + cout << "FMWPC Flagging AI check after " << Nevents << " events (>=" << min_events << ")" << endl; + rs_SavePad("FMWPC_occupancy", 0); + rs_ResetAllMacroHistos("//FMWPC_occupancy"); + } + } +#endif + +} diff --git a/src/plugins/monitoring/FMWPC_online/FMWPC_occupancy.C b/src/plugins/monitoring/FMWPC_online/FMWPC_occupancy.C index 738652c22c..6f3242ecac 100644 --- a/src/plugins/monitoring/FMWPC_online/FMWPC_occupancy.C +++ b/src/plugins/monitoring/FMWPC_online/FMWPC_occupancy.C @@ -28,7 +28,7 @@ double Nevents = 1.0; TH1I *fmwpc_num_events = (TH1I*)gDirectory->FindObjectAny("fmwpc_num_events"); if(fmwpc_num_events) Nevents = (double)fmwpc_num_events->GetBinContent(1); - + // Just for testing if(gPad == NULL){ TCanvas *c1 = new TCanvas("c1"); @@ -138,6 +138,8 @@ fmwpc_norm_layer_6->Draw("h"); } + + #ifdef ROOTSPY_MACROS // ------ The following is used by RSAI -------- if( rs_GetFlag("Is_RSAI")==1 ){ diff --git a/src/plugins/monitoring/FMWPC_online/JEventProcessor_FMWPC_online.cc b/src/plugins/monitoring/FMWPC_online/JEventProcessor_FMWPC_online.cc index 24530cee1d..306f2db367 100644 --- a/src/plugins/monitoring/FMWPC_online/JEventProcessor_FMWPC_online.cc +++ b/src/plugins/monitoring/FMWPC_online/JEventProcessor_FMWPC_online.cc @@ -12,6 +12,7 @@ using namespace jana; #include "FMWPC/DFMWPCHit.h" #include "FMWPC/DCTOFDigiHit.h" #include "FMWPC/DCTOFTDCDigiHit.h" +#include "FMWPC/DCTOFHit.h" #include #include @@ -22,6 +23,9 @@ static TH1I *fmwpc_num_events; static TH1F *fmwpc_occ_layer[6]; static TH1F *fmwpc_hit_layer[6]; static TH2I *fmwpc_pedestal[6]; +static TH1I *h1_fmwpc_occ_chamber; +//static TH2F *h2_fmwpc_time; +//static TH2F *h2_fmwpc_q; static TH1I *ctof_adc_events; static TH1F *ctof_adc_occ_up; @@ -31,6 +35,16 @@ static TH1F *ctof_tdc_occ_up; static TH1F *ctof_tdc_occ_down; static TH2F *ctof_tdc_time; static TH2F *ctof_adc_time; +static TH1I *h1_ctof_occ_up; +static TH1I *h1_ctof_occ_down; +static TH2F *h2_ctof_dE; +static TH2D *h2_ctof_t; +static TH2D *h2_ctof_t_adc; +static TH2D *h2_ctof_t_adc_tdc; +static TH1F *fmwpc_time_chamber[6]; +static TH1D *fmwpc_pulse_integral_chamber[6]; +static TH2F *h2_fmwpc_time_chamber; +static TH2D *h2_fmwpc_pi_chamber; // Routine used to create our JEventProcessor #include @@ -90,8 +104,22 @@ jerror_t JEventProcessor_FMWPC_online::init(void) sprintf(htitle, "FMWPC Pedestal vs. wire %01d;Wire Number;Pedestal", iLayer+1); fmwpc_pedestal[iLayer] = new TH2I(hname, htitle, 144, 0.5, 144.5, 400, 0.0, 400.0); fmwpc_pedestal[iLayer]->SetStats(0); + + sprintf(hname,"fmwpc_time_chamber_%01d", iLayer+1); + sprintf(htitle, "Chamber %01d Time (ns)", iLayer+1); + fmwpc_time_chamber[iLayer] = new TH1F(hname, htitle, 150,0,2000); + fmwpc_time_chamber[iLayer]->SetStats(0); + + sprintf(hname,"fmwpc_pulse_integral_chamber_%01d", iLayer+1); + sprintf(htitle, "Chamber %01d Pulse Integral", iLayer+1); + fmwpc_pulse_integral_chamber[iLayer] = new TH1D(hname, htitle, 100,0,2000); + fmwpc_pulse_integral_chamber[iLayer]->SetStats(0); } + h1_fmwpc_occ_chamber = new TH1I("h1_fmwpc_occ_chamber","FMWPC Hits per Chamber",6,0,6); + h2_fmwpc_time_chamber = new TH2F("h2_fmwpc_time_chamber","Time (ns) per Chamber",6,0,6,100,0,2000); + h2_fmwpc_pi_chamber = new TH2D("h2_fmwpc_pi_chamber","Energy (GeV) per Chamber",6,0,6,150,0,7000); + ctof_adc_occ_up = new TH1F("ctof_adc_occ_up", "CTOF ADC Occupancy", 4, 0.5, 4.5); ctof_adc_occ_up->SetXTitle("Bar Number"); ctof_adc_occ_down = new TH1F("ctof_adc_occ_down", "CTOF ADC Occupancy", 4, 0.5, 4.5); @@ -103,6 +131,24 @@ jerror_t JEventProcessor_FMWPC_online::init(void) ctof_tdc_time=new TH2F("ctof_tdc_time","CTOF time from TDC;channel;t [ns]",8,-0.5,7.5,2000,-1000,1000); ctof_adc_time=new TH2F("ctof_adc_time","CTOF time from ADC;channel;t [ns]",8,-0.5,7.5,2000,-1000,1000); + + h1_ctof_occ_up = new TH1I("h1_ctof_occ_up", "CTOF Occupancy", 4, 0.5, 4.5); + h1_ctof_occ_down = new TH1I("h1_ctof_occ_down", "CTOF Occupancy", 4, 0.5, 4.5); + h1_ctof_occ_up->SetXTitle("Bar Number"); + h1_ctof_occ_down->SetXTitle("Bar Number"); + h2_ctof_dE = new TH2F("h1_ctof_dE", "Energy in Each BAR",4,0.5,4.5,100,0,0.003); + h2_ctof_dE->SetXTitle("Bar Number"); + h2_ctof_dE->SetYTitle("Energy (GeV)"); + h2_ctof_t = new TH2D("h2_ctof_t", "TDC Time in Each BAR",4,0.5,4.5,150,-170,170); + h2_ctof_t->SetXTitle("Bar Number"); + h2_ctof_t->SetYTitle("Time (ns)"); + h2_ctof_t_adc = new TH2D("h2_ctof_t_adc","ADC Time in Each BAR",4,0.5,4.5,150,-170,170); + h2_ctof_t_adc->SetXTitle("Bar Number"); + h2_ctof_t_adc->SetYTitle("ADC Time (ns)"); + h2_ctof_t_adc_tdc = new TH2D("h2_ctof_t_adc_tdc","TDC - ADC Time in Each BAR",4,0.5,4.5,150,-170,170); + h2_ctof_t_adc_tdc->SetXTitle("Bar Number"); + h2_ctof_t_adc_tdc->SetYTitle("ADC - TDC Time"); + // back to main dir main->cd(); @@ -171,6 +217,9 @@ jerror_t JEventProcessor_FMWPC_online::evnt(JEventLoop *loop, uint64_t eventnumb vectorctoftdcdigis; loop->Get(ctoftdcdigis); + vectorctofHits; + loop->Get(ctofHits); + // FILL HISTOGRAMS // Since we are filling histograms local to this plugin, it will not interfere with other ROOT operations: can use plugin-wide ROOT fill lock japp->RootFillLock(this); //ACQUIRE ROOT FILL LOCK @@ -179,15 +228,37 @@ jerror_t JEventProcessor_FMWPC_online::evnt(JEventLoop *loop, uint64_t eventnumb for (unsigned int i=0; ilayer-1]->Fill(digi->pulse_time); + fmwpc_pulse_integral_chamber[digi->layer-1]->Fill(digi->pulse_integral); + h2_fmwpc_time_chamber->Fill(digi->layer-1, digi->pulse_time); + h2_fmwpc_pi_chamber->Fill(digi->layer-1, digi->pulse_integral); fmwpc_occ_layer[digi->layer-1]->Fill(digi->wire); fmwpc_pedestal[digi->layer-1]->Fill(digi->wire, digi->pedestal); } for (unsigned int i=0; ilayer-1]->Fill(hit->wire); + //h2_fmwpc_time->Fill(hit->layer-1, hit->t); + //h2_fmwpc_q->Fill(hit->layer-1, hit->q); + if(hit->layer == 1){ + h1_fmwpc_occ_chamber->Fill(0); + } + if(hit->layer == 2){ + h1_fmwpc_occ_chamber->Fill(1); + } + if(hit->layer == 3){ + h1_fmwpc_occ_chamber->Fill(2); + } + if(hit->layer == 4){ + h1_fmwpc_occ_chamber->Fill(3); + } + if(hit->layer == 5){ + h1_fmwpc_occ_chamber->Fill(4); + } + if(hit->layer == 6){ + h1_fmwpc_occ_chamber->Fill(5); + } } ctof_adc_events->Fill(1); @@ -222,6 +293,20 @@ jerror_t JEventProcessor_FMWPC_online::evnt(JEventLoop *loop, uint64_t eventnumb ctof_tdc_time->Fill(ind,T); } + //For factory hits + for(unsigned int j = 0; j < ctofHits.size(); j++){ + const DCTOFHit *hit = ctofHits[j]; + h2_ctof_dE->Fill(hit->bar,hit->dE); + h2_ctof_t->Fill(hit->bar,hit->t); + h2_ctof_t_adc->Fill(hit->bar,hit->t_adc); + h2_ctof_t_adc_tdc->Fill(hit->bar,hit->t_adc - hit->t); + if(hit->end == 0){ + h1_ctof_occ_up->Fill(hit->bar); + } + if(hit->end == 1){ + h1_ctof_occ_down->Fill(hit->bar); + } + } japp->RootFillUnLock(this); //RELEASE ROOT FILL LOCK diff --git a/src/plugins/monitoring/RF_online/HistMacro_RF_p1.C b/src/plugins/monitoring/RF_online/HistMacro_RF_p1.C index 907242084d..9c172858e5 100644 --- a/src/plugins/monitoring/RF_online/HistMacro_RF_p1.C +++ b/src/plugins/monitoring/RF_online/HistMacro_RF_p1.C @@ -119,10 +119,10 @@ if( min_events < 1 ) min_events = 1E5; if( Nevents >= min_events ) { cout << "RF Flagging AI check after " << Nevents << " events (>=" << min_events << ")" << endl; - rs_SavePad("RF_FDC_selftiming", 1); - rs_SavePad("RF_TOF_selftiming", 2); - rs_SavePad("RF_TAGH_selftiming", 3); - rs_SavePad("RF_PSC_selftiming", 4); + rs_SavePad("RF_FDC_selftiming", 0); + rs_SavePad("RF_TOF_selftiming", 0); + rs_SavePad("RF_TAGH_selftiming", 0); + rs_SavePad("RF_PSC_selftiming", 0); rs_ResetAllMacroHistos("//HistMacro_RF_p1"); } diff --git a/src/plugins/monitoring/SConscript b/src/plugins/monitoring/SConscript index 3ba610ef7e..abec710145 100644 --- a/src/plugins/monitoring/SConscript +++ b/src/plugins/monitoring/SConscript @@ -15,6 +15,7 @@ subdirs = [ 'fa125_itrig', 'FCAL_online', 'FCAL_invmass', +'FCAL_cpp', 'FDC_online', 'FDC_Efficiency', 'FMWPC_online', diff --git a/src/plugins/monitoring/TAGM_online/HistMacro_TAGMCOL.C b/src/plugins/monitoring/TAGM_online/HistMacro_TAGMCOL.C new file mode 100644 index 0000000000..3a7cce978c --- /dev/null +++ b/src/plugins/monitoring/TAGM_online/HistMacro_TAGMCOL.C @@ -0,0 +1,106 @@ +// hnamepath: /tagm/tagmCol9 +// hnamepath: /tagm/tagmCol27 +// hnamepath: /tagm/tagmCol81 +// hnamepath: /tagm/tagmCol99 + +{ + cout<< "Entered macro: TAGM_online/HistMacro_TAGMCOL.C" << endl; + + //Goto directory tagm + TDirectory *locDirectory = (TDirectory*)gDirectory->FindObjectAny("tagm"); + if(!locDirectory) + return; + locDirectory->cd(); + + //fetch the histograms + TH1I *locHistTAGMcol9 = (TH1I*)gDirectory->Get("tagmCol9"); + TH1I *locHistTAGMcol27 = (TH1I*)gDirectory->Get("tagmCol27"); + TH1I *locHistTAGMcol81 = (TH1I*)gDirectory->Get("tagmCol81"); + TH1I *locHistTAGMcol99 = (TH1I*)gDirectory->Get("tagmCol99"); + + TCanvas *locCanvas = NULL; + if(TVirtualPad::Pad() == NULL) + locCanvas = new TCanvas("TAGM_Cols", "TAGM Columns", 1200, 800); //for testing + else + locCanvas = gPad->GetCanvas(); + locCanvas->Divide(2, 2); + + //Draw + locCanvas->cd(1); + gPad->SetTicks(); + gPad->SetGrid(); + if (locHistTAGMcol9 != NULL){ + TH1I* hist = locHistTAGMcol9; + hist->SetStats(0); + hist->GetXaxis()->SetTitleSize(0.05); + hist->GetYaxis()->SetTitleSize(0.05); + hist->GetXaxis()->SetLabelSize(0.05); + hist->GetYaxis()->SetLabelSize(0.05); + hist->Fit("gaus", "Q", "R", 1., 6.); + hist->Draw(); + } + locCanvas->cd(2); + gPad->SetTicks(); + gPad->SetGrid(); + if (locHistTAGMcol27 != NULL){ + TH1I* hist = locHistTAGMcol27; + hist->SetStats(0); + hist->GetXaxis()->SetTitleSize(0.05); + hist->GetYaxis()->SetTitleSize(0.05); + hist->GetXaxis()->SetLabelSize(0.05); + hist->GetYaxis()->SetLabelSize(0.05); + hist->Fit("gaus", "Q", "R", 1., 6.); + hist->Draw(); + } + locCanvas->cd(3); + gPad->SetTicks(); + gPad->SetGrid(); + if (locHistTAGMcol81 != NULL){ + TH1I* hist = locHistTAGMcol81; + hist->SetStats(0); + hist->GetXaxis()->SetTitleSize(0.05); + hist->GetYaxis()->SetTitleSize(0.05); + hist->GetXaxis()->SetLabelSize(0.05); + hist->GetYaxis()->SetLabelSize(0.05); + hist->Fit("gaus", "Q", "R", 1., 6.); + hist->Draw(); + } + locCanvas->cd(4); + gPad->SetTicks(); + gPad->SetGrid(); + if (locHistTAGMcol99 != NULL){ + TH1I* hist = locHistTAGMcol99; + hist->SetStats(0); + hist->GetXaxis()->SetTitleSize(0.05); + hist->GetYaxis()->SetTitleSize(0.05); + hist->GetXaxis()->SetLabelSize(0.05); + hist->GetYaxis()->SetLabelSize(0.05); + hist->Fit("gaus", "Q", "R", 1., 6.); + hist->Draw(); + } + + cout<< "Entered macro: TAGM_online/HistMacro_TAGMCOL.C" << endl; + +#ifdef ROOTSPY_MACROS + + // -- The following is used by RSAI -- + cout<< "the following code for RSAI is in macro TAGM_online/HistMacro_TAGMCOL.C" << endl; + + if (rs_GetFlag("Is_RSAI") == 1) { + + int Nhits = tagmCol9->GetEntries(); + if (Nhits>1e4) { + rs_SavePad("TAGM_ColumnsAll4",0); + //rs_SavePad("TAGM_Column9",1); + //rs_SavePad("TAGM_Column27",2); + //rs_SavePad("TAGM_Column81",3); + //rs_SavePad("TAGM_Column99",4); + + rs_ResetAllMacroHistos("//HistMacro_TAGMCOL"); + } + } + + +#endif + +} diff --git a/src/plugins/monitoring/TAGM_online/JEventProcessor_TAGM_online.cc b/src/plugins/monitoring/TAGM_online/JEventProcessor_TAGM_online.cc index 7b08345fbc..f7a29f9d8f 100644 --- a/src/plugins/monitoring/TAGM_online/JEventProcessor_TAGM_online.cc +++ b/src/plugins/monitoring/TAGM_online/JEventProcessor_TAGM_online.cc @@ -1,6 +1,6 @@ // $Id$ // -// File: JEventProcessor_FCAL_online.cc +// File: JEventProcessor_TAGM_online.cc // Created: Fri Nov 9 11:58:09 EST 2012 // Creator: wolin (on Linux stan.jlab.org 2.6.32-279.11.1.el6.x86_64 x86_64) @@ -133,6 +133,7 @@ static TH2F *tagm_adc_mult_2d, *tagms_adc_mult_2d; static TH2F *tagm_tdc_mult_2d, *tagms_tdc_mult_2d; static TH2F *tagm_adc_tdc_mult; +static TH1F *tagmCol9, *tagmCol27, *tagmCol81, *tagmCol99; //---------------------------------------------------------------------------------- @@ -169,6 +170,11 @@ jerror_t JEventProcessor_TAGM_online::init(void) { TDirectory *main = gDirectory; TDirectory *tagmdir = gDirectory->mkdir("tagm"); tagmdir->cd(); + + tagmCol9 = new TH1F("tagmCol9", "TAGM Hits in Column9", 7, -0.5, 6.5); + tagmCol27 = new TH1F("tagmCol27", "TAGM Hits in Column27", 7, -0.5, 6.5); + tagmCol81 = new TH1F("tagmCol81", "TAGM Hits in Column81", 7, -0.5, 6.5); + tagmCol99 = new TH1F("tagmCol99", "TAGM Hits in Column99", 7, -0.5, 6.5); // Book DTAGMDigiHit histosgrams tagm_adc_seen = new TH1F("tagm_adc_seen", @@ -649,6 +655,18 @@ jerror_t JEventProcessor_TAGM_online::evnt(JEventLoop *eventLoop, uint64_t event // Calculate the FADC250 multiplicities for each channel ++column_adc_hits[column - 1]; ++column_adc_hits_total; + } else { + // fill hits into col 9, 27, 81 and 99 + //cout<Fill(row); + } else if (column == 27){ + tagmCol27->Fill(row); + } else if (column == 81){ + tagmCol81->Fill(row); + } else if (column == 99){ + tagmCol99->Fill(row); + } } } diff --git a/src/plugins/monitoring/TrackingPulls/JEventProcessor_TrackingPulls.cc b/src/plugins/monitoring/TrackingPulls/JEventProcessor_TrackingPulls.cc index 29164d7009..59d99408f2 100644 --- a/src/plugins/monitoring/TrackingPulls/JEventProcessor_TrackingPulls.cc +++ b/src/plugins/monitoring/TrackingPulls/JEventProcessor_TrackingPulls.cc @@ -31,6 +31,11 @@ JEventProcessor_TrackingPulls::~JEventProcessor_TrackingPulls() {} jerror_t JEventProcessor_TrackingPulls::init(void) { // This is called once at program startup. + int numlayers = 24; + int numrings = 28; + unsigned int numstraws[28] = { + 42, 42, 54, 54, 66, 66, 80, 80, 93, 93, 106, 106, 123, 123, + 135, 135, 146, 146, 158, 158, 170, 170, 182, 182, 197, 197, 209, 209}; // Use -PTRACKINGPULLS:MAKE_TREE=1 to produce tree output MAKE_TREE = 0; @@ -57,6 +62,8 @@ jerror_t JEventProcessor_TrackingPulls::init(void) { locTreeBranchRegister.Register_Single("track_index"); locTreeBranchRegister.Register_Single("chi2"); locTreeBranchRegister.Register_Single("ndf"); + locTreeBranchRegister.Register_Single("ncdchits"); + locTreeBranchRegister.Register_Single("nfdchits"); locTreeBranchRegister.Register_Single("charge"); locTreeBranchRegister.Register_Single("mom"); locTreeBranchRegister.Register_Single("phi"); @@ -91,7 +98,190 @@ jerror_t JEventProcessor_TrackingPulls::init(void) { //REGISTER BRANCHES dTreeInterface->Create_Branches(locTreeBranchRegister); } - + + + TDirectory *main = gDirectory; + gDirectory->mkdir("TrackingPulls")->cd(); + + gDirectory->mkdir("TrackInfo")->cd(); + + hTrackingFOM = new TH1I("Tracking FOM", "Tracking FOM", 200, 0.0, 1.0); + hTrack_PVsTheta = new TH2I("P Vs. Theta", "P Vs. #theta; #theta [deg.]; |P| [GeV/c]", 70, 0.0, 140.0, 50, 0.0, 10.0); + hTrack_PhiVsTheta = new TH2I("Phi Vs. Theta", "#phi Vs. #theta; #theta [deg.]; #phi [deg.]", 70, 0.0, 140.0, 180, -180.0, 180.0); + hTrack_PVsPhi = new TH2I("P Vs. Phi", "P Vs. #phi; #phi [deg.]; |P| [GeV/c]", 180, -180, 180.0, 50, 0.0, 10.0); + + gDirectory->cd(".."); + + gDirectory->mkdir("TrackInfo_SmoothFailure")->cd(); + + hTrackingFOM_SmoothFailure = new TH1I("Tracking FOM", "Tracking FOM", 200, 0.0, 1.0); + hTrack_PVsTheta_SmoothFailure = new TH2I("P Vs. Theta", "P Vs. #theta; #theta [deg.]; |P| [GeV/c]", 70, 0.0, 140.0, 50, 0.0, 10.0); + hTrack_PhiVsTheta_SmoothFailure = new TH2I("Phi Vs. Theta", "#phi Vs. #theta; #theta [deg.]; #phi [deg.]", 70, 0.0, 140.0, 180, -180.0, 180.0); + hTrack_PVsPhi_SmoothFailure = new TH2I("P Vs. Phi", "P Vs. #phi; #phi [deg.]; |P| [GeV/c]", 180, -180, 180.0, 50, 0.0, 10.0); + + gDirectory->cd(".."); + + gDirectory->mkdir("TrackInfo_SmoothSuccess")->cd(); + + hTrackingFOM_SmoothSuccess = new TH1I("Tracking FOM", "Tracking FOM", 200, 0.0, 1.0); + hTrack_PVsTheta_SmoothSuccess = new TH2I("P Vs. Theta", "P Vs. #theta; #theta [deg.]; |P| [GeV/c]", 70, 0.0, 140.0, 50, 0.0, 10.0); + hTrack_PhiVsTheta_SmoothSuccess = new TH2I("Phi Vs. Theta", "#phi Vs. #theta; #theta [deg.]; #phi [deg.]", 70, 0.0, 140.0, 180, -180.0, 180.0); + hTrack_PVsPhi_SmoothSuccess = new TH2I("P Vs. Phi", "P Vs. #phi; #phi [deg.]; |P| [GeV/c]", 180, -180, 180.0, 50, 0.0, 10.0); + + gDirectory->cd(".."); + + gDirectory->mkdir("TrackInfo_SmoothSuccess_NaN")->cd(); + + hTrackingFOM_SmoothSuccess_NaN = new TH1I("Tracking FOM", "Tracking FOM", 200, 0.0, 1.0); + hTrack_PVsTheta_SmoothSuccess_NaN = new TH2I("P Vs. Theta", "P Vs. #theta; #theta [deg.]; |P| [GeV/c]", 70, 0.0, 140.0, 50, 0.0, 10.0); + hTrack_PhiVsTheta_SmoothSuccess_NaN = new TH2I("Phi Vs. Theta", "#phi Vs. #theta; #theta [deg.]; #phi [deg.]", 70, 0.0, 140.0, 180, -180.0, 180.0); + hTrack_PVsPhi_SmoothSuccess_NaN = new TH2I("P Vs. Phi", "P Vs. #phi; #phi [deg.]; |P| [GeV/c]", 180, -180, 180.0, 50, 0.0, 10.0); + + gDirectory->cd(".."); + + gDirectory->mkdir("TrackPulls")->cd(); + + hAllPulls = new TH1I("All Pulls", "Residual/Error", 100, -5.0, 5.0); + hAllPulls_Vs_P = new TH2I("All Pulls Vs. P", ";|P| ;Residual/Error", 100, 0.0, 10.0, 100, -5.0, 5.0); + hAllPulls_Vs_Phi = new TH2I("All Pulls Vs. Phi", ";#phi ;Residual/Error", 180, -180.0, 180.0, 100, -5.0, 5.0); + hAllPulls_Vs_Theta = new TH2I("All Pulls Vs. Theta", ";#theta ;Residual/Error", 140, 0.0, 140.0, 100, -5.0, 5.0); + hAllPulls_Vs_NDF = new TH2I("All Pulls Vs. NDF", ";Track NDF ;Residual/Error", 140, 0.0, 140.0, 100, -5.0, 5.0); + hAllPulls_Vs_TrackingFOM = new TH2I("All Pulls Vs. Tracking FOM", ";Track FOM ;Residual/Error", 140, 0.0, 140.0, 100, -5.0, 5.0); + hFDCWireError = new TH1I("FDC Wire Error", "Wire Residual Error", 100, 0.0, 0.1); + hFDCCathodeError = new TH1I("FDC Cathode Error", "Cathode Residual Error", 100, 0.0, 0.1); + hCDCError = new TH1I("CDCError", "Residual Error", 100, 0.0, 0.1); + + gDirectory->cd(".."); + + gDirectory->mkdir("FDCPulls")->cd(); + + hFDCAllWirePulls = new TH1I("All Wire Pulls", "Residual/Error", 100, -5.0, 5.0); + hFDCAllCathodeulls = new TH1I("All Cathode Pulls", "Residual/Error", 100, -5.0, 5.0); + hFDCAllWireResiduals = new TH1I("All Wire Residuals", "Residual", 100, -0.1, 0.1); + hFDCAllCathodeResiduals = new TH1I("All Cathode Residuals", "Residual", 100, -0.1, 0.1); + hFDCAllWireResidualsVsPlane = new TH2I("All Wire Residuals Vs. Plane", ";plane ;Residual", 24, 0.5, 24.5, 100, -0.1, 0.1); + hFDCAllCathodeResidualsVsPlane = new TH2I("All Cathode Residuals Vs. Plane", ";plane ;Residual", 24, 0.5, 24.5, 100, -0.1, 0.1); + hFDCAllWirePullsVsPlane = new TH2I("All Wire Pulls Vs. Plane", ";plane ;Residual/Error", 24, 0.5, 24.5, 100, -5.0, 5.0); + hFDCAllCathodePullsVsPlane = new TH2I("All Cathode Pulls Vs. Plane", ";plane ;Residual/Error", 24, 0.5, 24.5, 100, -5.0, 5.0); + hFDCAllWireResidualsVsDriftTime = new TH2I("All Wire Residuals Vs Drift Time", ";Drift Time;Residual", 170, -20.0, 150.0, 100, -0.1, 0.1); + hFDCAllWirePullsVsDriftTime = new TH2I("All Wire Pulls Vs Drift Time", ";Drift Time;Residual/Error", 170, -20.0, 150.0, 100, -5.0, 5.0); + hFDCAllWirePullsVsP = new TH2I("All Wire Pulls Vs. P", ";|P| ;Residual/Error", 100, 0.0, 10.0, 100, -5.0, 5.0); + hFDCAllWirePullsVsPhi = new TH2I("All Wire Pulls Vs. Phi", ";#phi ;Residual/Error", 180, -180.0, 180.0, 100, -5.0, 5.0); + hFDCAllWirePullsVsTheta = new TH2I("All Wire Pulls Vs. Theta", ";#theta ;Residual/Error", 50, 0.0, 25.0, 100, -5.0, 5.0); + hFDCAllCathodePullsVsP = new TH2I("All Cathode Pulls Vs. P", ";|P| ;Residual/Error", 100, 0.0, 10.0, 100, -5.0, 5.0); + hFDCAllCathodePullsVsPhi = new TH2I("All Cathode Pulls Vs. Phi", ";#phi ;Residual/Error", 180, -180.0, 180.0, 100, -5.0, 5.0); + hFDCAllCathodePullsVsTheta = new TH2I("All Cathode Pulls Vs. Theta", ";#theta ;Residual/Error", 50, 0.0, 25.0, 100, -5.0, 5.0); + hFDCAllWireResidualsVsP = new TH2I("All Wire Residuals Vs. P", ";|P| ;Residual/Error", 100, 0.0, 10.0, 100, -0.1, 0.1); + hFDCAllWireResidualsVsPhi = new TH2I("All Wire Residuals Vs. Phi", ";#phi ;Residual/Error", 180, -180.0, 180.0, 100, -0.1, 0.1); + hFDCAllWireResidualsVsTheta = new TH2I("All Wire Residuals Vs. Theta", ";#theta ;Residual/Error", 50, 0.0, 25.0, 100, -0.1, 0.1); + hFDCAllCathodeResidualsVsP = new TH2I("All Cathode Residuals Vs. P", ";|P| ;Residual/Error", 100, 0.0, 10.0, 100, -0.1, 0.1); + hFDCAllCathodeResidualsVsPhi = new TH2I( "All Cathode Residuals Vs. Phi", ";#phi ;Residual/Error", 180, -180.0, 180.0, 100, -0.1, 0.1); + hFDCAllCathodeResidualsVsTheta = new TH2I("All Cathode Residuals Vs. Theta", ";#theta ;Residual/Error", 50, 0.0, 25.0, 100, -0.1, 0.1); + hFDCAllWirePullsVsNDF = new TH2I("All Wire Pulls Vs. NDF", ";Track NDF ;Residual/Error", 50, 0.5, 50.5, 100, -5.0, 5.0); + hFDCAllWirePullsVsTrackingFOM = new TH2I("All Wire Pulls Vs. Tracking FOM", ";Track FOM ;Residual/Error", 100, 0.0, 1.0, 100, -5.0, 5.0); + hFDCAllCathodePullsVsNDF = new TH2I("All Cathode Pulls Vs. NDF", ";Track NDF ;Residual/Error", 50, 0.5, 50.5, 100, -5.0, 5.0); + hFDCAllCathodePullsVsTrackingFOM = new TH2I("All Cathode Pulls Vs. Tracking FOM", ";Track FOM ;Residual/Error", 100, 0.0, 1.0, 100, -5.0, 5.0); + + gDirectory->cd(".."); + + for(int layer=0; layermkdir(name)->cd(); + + hFDCAllWirePulls_ByLayer.push_back( new TH1I("All Wire Pulls", "Residual/Error", 100, -5.0, 5.0) ); + hFDCAllCathodeulls_ByLayer.push_back( new TH1I("All Cathode Pulls", "Residual/Error", 100, -5.0, 5.0) ); + hFDCAllWireResiduals_ByLayer.push_back( new TH1I("All Wire Residuals", "Residual", 100, -0.1, 0.1) ); + hFDCAllCathodeResiduals_ByLayer.push_back( new TH1I("All Cathode Residuals", "Residual", 100, -0.1, 0.1) ); + hFDCWireResidualsGoodTracks_ByLayer.push_back( new TH1I("wire_residual", "Residual", 200, -0.1, 0.1) ); + hFDCWireResidualsGoodTracksRight_ByLayer.push_back( new TH1I("wire_residual_right", "Residual", 200, -0.1, 0.1) ); + hFDCWireResidualsGoodTracksLeft_ByLayer.push_back( new TH1I("wire_residual_left", "Residual", 200, -0.1, 0.1) ); + hFDCAllWireResidualsVsDriftTime_ByLayer.push_back( new TH2I("All Wire Residuals Vs Drift Time", ";Drift Time;Residual", 170, -20.0, 150.0, 100, -0.1, 0.1) ); + hFDCAllWirePullsVsDriftTime_ByLayer.push_back( new TH2I("All Wire Pulls Vs Drift Time", ";Drift Time;Residual/Error", 170, -20.0, 150.0, 100, -5.0, 5.0) ); + hFDCAllWirePullsVsP_ByLayer.push_back( new TH2I("All Wire Pulls Vs. P", ";|P| ;Residual/Error", 100, 0.0, 10.0, 100, -5.0, 5.0) ); + hFDCAllWirePullsVsPhi_ByLayer.push_back( new TH2I("All Wire Pulls Vs. Phi", ";#phi ;Residual/Error", 180, -180.0, 180.0, 100, -5.0, 5.0) ); + hFDCAllWirePullsVsTheta_ByLayer.push_back( new TH2I("All Wire Pulls Vs. Theta", ";#theta ;Residual/Error", 50, 0.0, 25.0, 100, -5.0, 5.0) ); + hFDCAllCathodePullsVsP_ByLayer.push_back( new TH2I("All Cathode Pulls Vs. P", ";|P| ;Residual/Error", 100, 0.0, 10.0, 100, -5.0, 5.0) ); + hFDCAllCathodePullsVsPhi_ByLayer.push_back( new TH2I("All Cathode Pulls Vs. Phi", ";#phi ;Residual/Error", 180, -180.0, 180.0, 100, -5.0, 5.0) ); + hFDCAllCathodePullsVsTheta_ByLayer.push_back( new TH2I("All Cathode Pulls Vs. Theta", ";#theta ;Residual/Error", 50, 0.0, 25.0, 100, -5.0, 5.0) ); + hFDCAllWireResidualsVsP_ByLayer.push_back( new TH2I("All Wire Residuals Vs. P", ";|P| ;Residual/Error", 100, 0.0, 10.0, 100, -0.1, 0.1) ); + hFDCAllWireResidualsVsPhi_ByLayer.push_back( new TH2I("All Wire Residuals Vs. Phi", ";#phi ;Residual/Error", 180, -180.0, 180.0, 100, -0.1, 0.1) ); + hFDCAllWireResidualsVsTheta_ByLayer.push_back( new TH2I("All Wire Residuals Vs. Theta", ";#theta ;Residual/Error", 50, 0.0, 25.0, 100, -0.1, 0.1) ); + hFDCAllCathodeResidualsVsP_ByLayer.push_back( new TH2I("All Cathode Residuals Vs. P", ";|P| ;Residual/Error", 100, 0.0, 10.0, 100, -0.1, 0.1) ); + hFDCAllCathodeResidualsVsPhi_ByLayer.push_back( new TH2I( "All Cathode Residuals Vs. Phi", ";#phi ;Residual/Error", 180, -180.0, 180.0, 100, -0.1, 0.1) ); + hFDCAllCathodeResidualsVsTheta_ByLayer.push_back( new TH2I("All Cathode Residuals Vs. Theta", ";#theta ;Residual/Error", 50, 0.0, 25.0, 100, -0.1, 0.1) ); + + hFDCWirePulls_ByLayer.push_back( new TH2I("Wire Pulls", ";Wire Number ;Residual/Error", 96, 0.5, 96.5, 100, -5.0, 5.0) ); + hFDCWireResiduals_ByLayer.push_back( new TH2I("Wire Residuals", ";Wire Number ;Residual", 96, 0.5, 96.5, 100, -0.1, 0.1) ); + hFDC2DWirePulls_ByLayer.push_back( new TProfile2D("2D Wire Hit Pulls", "Mean of Wire Pulls vs. PseudoHit XY", 100, -50., 50., 100, -50., 50.) ); + hFDC2DWireResiduals_ByLayer.push_back( new TProfile2D("2D Wire Hit Residuals", "Mean of Wire Residuals vs. PseudoHit XY", 100, -50., 50., 100, -50., 50.) ); + hFDC2DWireResidualsLocal_ByLayer.push_back( new TProfile2D("2D Wire Hit Residuals Local", "Mean of Wire Residuals vs. PseudoHit WS;Perpendicular Distance to Wire; Distance Along the Wire", + 100, -50., 50., 100, -50., 50.) ); + hFDC2DCathodePulls_ByLayer.push_back( new TProfile2D("2D Cathode Hit Pulls", "Mean of Cathode Pulls vs. PseudoHit XY", 100, -50., 50., 100, -50., 50.) ); + hFDC2DCathodeResiduals_ByLayer.push_back( new TProfile2D("2D Cathode Hit Residuals", "Mean of Cathode Residuals vs. PseudoHit XY", 100, -50., 50., 100, -50., 50.) ); + hFDC2DCathodeResidualsLocal_ByLayer.push_back( new TProfile2D("2D Cathode Hit Residuals Local", "Mean of Cathode Residuals vs. PseudoHit WS;Perpendicular Distance to Wire; Distance Along the Wire", + 100, -50., 50., 100, -50., 50.) ); + + gDirectory->cd(".."); + } + + gDirectory->mkdir("CDCPulls")->cd(); + + hCDCAllPulls = new TH1I("All Pulls", "Residual/Error", 100, -5.0, 5.0); + hCDCAllResiduals = new TH1I("All Residuals", "Residual", 100, -0.1, 0.1); + hCDCAllResidualsVsRing = new TH2I("All Residuals Vs. Ring", ";Ring ;Residual", 24, 0.5, 24.5, 100, -0.1, 0.1); + hCDCAllPullsVsRing = new TH2I("All Pulls Vs. Ring", ";Ring ;Residual/Error", 24, 0.5, 24.5, 100, -5.0, 5.0); + hCDCAllResidualsVsDriftTime = new TH2I("All Residuals Vs. tdrift", ";Drift Time;Residual", 170, -20.0, 150.0, 100, -0.1, 0.1); + hCDCAllPullsVsDriftTime = new TH2I("All Pulls Vs. tdrift", ";Drift Time;Residual/Error", 170, -20.0, 150.0, 100, -5.0, 5.0); + hCDCAllPullsVsP = new TH2I("All Pulls Vs. P", ";|P| ;Residual/Error", 100, 0.0, 10.0, 100, -5.0, 5.0); + hCDCAllPullsVsPhi = new TH2I("All Pulls Vs. Phi", ";#phi ;Residual/Error", 180, -180.0, 180.0, 100, -5.0, 5.0); + hCDCAllPullsVsTheta = new TH2I("All Pulls Vs. Theta", ";#theta ;Residual/Error", 50, 0.0, 25.0, 100, -5.0, 5.0); + hCDCAllResidualsVsP = new TH2I("All Residuals Vs. P", ";|P| ;Residual/Error", 100, 0.0, 10.0, 100, -0.1, 0.1); + hCDCAllResidualsVsPhi = new TH2I("All Residuals Vs. Phi", ";#phi ;Residual/Error", 180, -180.0, 180.0, 100, -0.1, 0.1); + hCDCAllResidualsVsTheta = new TH2I("All Residuals Vs. Theta", ";#theta ;Residual/Error", 50, 0.0, 25.0, 100, -0.1, 0.1); + hCDCAllPullsVsNDF = new TH2I("All Pulls Vs. NDF", ";Track NDF ;Residual/Error", 50, 0.5, 50.5, 100, -5.0, 5.0); + hCDCAllPullsVsTrackingFOM = new TH2I("All Pulls Vs. Tracking FOM", ";Track FOM ;Residual/Error", 100, 0.0, 1.0, 100, -5.0, 5.0); + + gDirectory->cd(".."); + + for(int ring=0; ringmkdir(name)->cd(); + + hCDCAllPulls_ByRing.push_back( new TH1I("All Pulls", "Residual/Error", 100, -5.0, 5.0) ); + hCDCAllResiduals_ByRing.push_back( new TH1I("All Residuals", "Residual", 100, -0.1, 0.1) ); + hCDCAllResidualsVsDriftTime_ByRing.push_back( new TH2I("All Residuals Vs. tdrift", ";Drift Time;Residual", 200, 0.0, 1000.0, 100, -0.1, 0.1) ); + hCDCAllPullsVsDriftTime_ByRing.push_back( new TH2I("All Pulls Vs. tdrift", ";Drift Time;Residual/Error", 200, 0.0, 1000.0, 100, -5.0, 5.0) ); + hCDCAllResidualsVsZ_ByRing.push_back( new TH2I("All Residuals Vs. z", ";z [cm];Residual", 200, -30., 200., 100, -0.1, 0.1) ); + hCDCAllPullsVsZ_ByRing.push_back( new TH2I("All Pulls Vs. z", ";z [cm];Residual/Error", 200, -30., 200., 100, -5.0, 5.0) ); + hCDCAllPullsVsP_ByRing.push_back( new TH2I("All Pulls Vs. P", ";|P| ;Residual/Error", 50, 0.0, 10.0, 100, -5.0, 5.0) ); + hCDCAllPullsVsPhi_ByRing.push_back( new TH2I("All Pulls Vs. Phi", ";#phi ;Residual/Error", 180, -180.0, 180.0, 100, -5.0, 5.0) ); + hCDCAllPullsVsTheta_ByRing.push_back( new TH2I("All Pulls Vs. Theta", ";#theta ;Residual/Error", 50, 0.0, 25.0, 100, -5.0, 5.0) ); + hCDCAllResidualsVsP_ByRing.push_back( new TH2I("All Residuals Vs. P", ";|P| ;Residual/Error", 100, 0.0, 10.0, 100, -0.1, 0.1) ); + hCDCAllResidualsVsPhi_ByRing.push_back( new TH2I("All Residuals Vs. Phi", ";#phi ;Residual/Error", 180, -180.0, 180.0, 100, -0.1, 0.1) ); + hCDCAllResidualsVsTheta_ByRing.push_back( new TH2I("All Residuals Vs. Theta", ";#theta ;Residual/Error", 50, 0.0, 25.0, 100, -0.1, 0.1) ); + + hCDCStrawPulls_ByRing.push_back( new TH2I("Per Straw Pulls", ";Straw Number ;Residual/Error", nStraw, 0.5, nStraw + 0.5, 100, -5.0, 5.0) ); + hCDCStrawResiduals_ByRing.push_back( new TH2I("Per Straw Residuals", ";Straw Number ;Residual", nStraw, 0.5, nStraw + 0.5, 100, -0.1, 0.1) ); + + hCDCStrawResidualsVsPhiTheta_ByRing.push_back( new TProfile2D("Residual Vs Phi-Theta", ";#theta;#phi", 70, 0.0, 140.0, 180, -180.0, 180.0) ); + hCDCStrawResidualsVsPhiZ_ByRing.push_back( new TProfile2D("Residual Vs Phi-z", ";z;#phi", 200, 0.0, 200.0, 180, -180.0, 180.0) ); + hCDCStrawResidualsVsPhiIntersectZ_ByRing.push_back( new TProfile2D("Residual Vs PhiIntersect-z", ";z;#phi Intersect", 200, 0.0, 200.0, nStraw, -180.0, 180.0) ); + hCDCStrawResidualsVsPTheta_ByRing.push_back( new TProfile2D("Residual Vs P-Theta", ";#theta;|P|", 70, 0.0, 140.0, 50, 0.0, 10.0) ); + + gDirectory->cd(".."); + } + + main->cd(); + + return NOERROR; } @@ -103,9 +293,6 @@ jerror_t JEventProcessor_TrackingPulls::brun(JEventLoop *eventLoop, jerror_t JEventProcessor_TrackingPulls::evnt(JEventLoop *loop, uint64_t eventnumber) { - unsigned int numstraws[28] = { - 42, 42, 54, 54, 66, 66, 80, 80, 93, 93, 106, 106, 123, 123, - 135, 135, 146, 146, 158, 158, 170, 170, 182, 182, 197, 197, 209, 209}; static uint32_t evntCount = 0; evntCount++; // Loop over the tracks, get the tracking pulls, and fill some histograms. @@ -118,6 +305,8 @@ jerror_t JEventProcessor_TrackingPulls::evnt(JEventLoop *loop, vector chargedTrackVector; loop->Get(chargedTrackVector); + japp->RootWriteLock(); //ACQUIRE ROOT LOCK!! + for (size_t i = 0; i < chargedTrackVector.size(); i++) { // TODO: Should be changed to use PID FOM when ready const DChargedTrackHypothesis *bestHypothesis = @@ -142,19 +331,12 @@ jerror_t JEventProcessor_TrackingPulls::evnt(JEventLoop *loop, double pmag = bestHypothesis->momentum().Mag(); if (pmag < 0.5) continue; - + // Fill some track information - Fill1DHistogram("TrackingPulls", "TrackInfo", "Tracking FOM", trackingFOM, - "Tracking FOM", 200, 0.0, 1.0); - Fill2DHistogram("TrackingPulls", "TrackInfo", "P Vs. Theta", theta, pmag, - "P Vs. #theta; #theta [deg.]; |P| [GeV/c]", 70, 0.0, 140.0, - 50, 0.0, 10.0); - Fill2DHistogram("TrackingPulls", "TrackInfo", "Phi Vs. Theta", theta, phi, - "#phi Vs. #theta; #theta [deg.]; #phi [deg.]", 70, 0.0, - 140.0, 180, -180.0, 180.0); - Fill2DHistogram("TrackingPulls", "TrackInfo", "P Vs. Phi", phi, pmag, - "P Vs. #phi; #phi [deg.]; |P| [GeV/c]", 180, -180, 180.0, - 50, 0.0, 10.0); + hTrackingFOM->Fill(trackingFOM); + hTrack_PVsTheta->Fill(theta, pmag); + hTrack_PhiVsTheta->Fill(theta, phi); + hTrack_PVsPhi->Fill(phi, pmag); // Get the pulls vector from the track auto track = bestHypothesis->Get_TrackTimeBased(); @@ -193,6 +375,8 @@ jerror_t JEventProcessor_TrackingPulls::evnt(JEventLoop *loop, dTreeFillData.Fill_Single("track_index", (int)i); dTreeFillData.Fill_Single("chi2", track->chisq); dTreeFillData.Fill_Single("ndf", track->Ndof); + dTreeFillData.Fill_Single("ncdchits", track->measured_cdc_hits_on_track); + dTreeFillData.Fill_Single("nfdchits", track->measured_fdc_hits_on_track); dTreeFillData.Fill_Single("charge", track->charge()); dTreeFillData.Fill_Single("mom", track->momentum().Mag()); dTreeFillData.Fill_Single("phi", track->momentum().Phi() * TMath::RadToDeg()); @@ -204,34 +388,16 @@ jerror_t JEventProcessor_TrackingPulls::evnt(JEventLoop *loop, } if (!track->IsSmoothed) { - Fill1DHistogram("TrackingPulls", "TrackInfo_SmoothFailure", - "Tracking FOM", trackingFOM, "Tracking FOM", 200, 0.0, - 1.0); - Fill2DHistogram("TrackingPulls", "TrackInfo_SmoothFailure", "P Vs. Theta", - theta, pmag, "P Vs. #theta; #theta [deg.]; |P| [GeV/c]", - 70, 0.0, 140.0, 50, 0.0, 10.0); - Fill2DHistogram("TrackingPulls", "TrackInfo_SmoothFailure", - "Phi Vs. Theta", theta, phi, - "#phi Vs. #theta; #theta [deg.]; #phi [deg.]", 70, 0.0, - 140.0, 180, -180.0, 180.0); - Fill2DHistogram("TrackingPulls", "TrackInfo_SmoothFailure", "P Vs. Phi", - phi, pmag, "P Vs. #phi; #phi [deg.]; |P| [GeV/c]", 180, - -180, 180.0, 50, 0.0, 10.0); - continue; + hTrackingFOM_SmoothFailure->Fill(trackingFOM); + hTrack_PVsTheta_SmoothFailure->Fill(theta, pmag); + hTrack_PhiVsTheta_SmoothFailure->Fill(theta, phi); + hTrack_PVsPhi_SmoothFailure->Fill(phi, pmag); + continue; } else { - Fill1DHistogram("TrackingPulls", "TrackInfo_SmoothSuccess", - "Tracking FOM", trackingFOM, "Tracking FOM", 200, 0.0, - 1.0); - Fill2DHistogram("TrackingPulls", "TrackInfo_SmoothSuccess", "P Vs. Theta", - theta, pmag, "P Vs. #theta; #theta [deg.]; |P| [GeV/c]", - 70, 0.0, 140.0, 50, 0.0, 10.0); - Fill2DHistogram("TrackingPulls", "TrackInfo_SmoothSuccess", - "Phi Vs. Theta", theta, phi, - "#phi Vs. #theta; #theta [deg.]; #phi [deg.]", 70, 0.0, - 140.0, 180, -180.0, 180.0); - Fill2DHistogram("TrackingPulls", "TrackInfo_SmoothSuccess", "P Vs. Phi", - phi, pmag, "P Vs. #phi; #phi [deg.]; |P| [GeV/c]", 180, - -180, 180.0, 50, 0.0, 10.0); + hTrackingFOM_SmoothSuccess->Fill(trackingFOM); + hTrack_PVsTheta_SmoothSuccess->Fill(theta, pmag); + hTrack_PhiVsTheta_SmoothSuccess->Fill(theta, phi); + hTrack_PVsPhi_SmoothSuccess->Fill(phi, pmag); } vector pulls = track->pulls; @@ -251,22 +417,11 @@ jerror_t JEventProcessor_TrackingPulls::evnt(JEventLoop *loop, } } if (any_nan) { - Fill1DHistogram("TrackingPulls", "TrackInfo_SmoothSuccess_NaN", - "Tracking FOM", trackingFOM, "Tracking FOM", 200, 0.0, - 1.0); - Fill2DHistogram("TrackingPulls", "TrackInfo_SmoothSuccess_NaN", - "P Vs. Theta", theta, pmag, - "P Vs. #theta; #theta [deg.]; |P| [GeV/c]", 70, 0.0, - 140.0, 50, 0.0, 10.0); - Fill2DHistogram("TrackingPulls", "TrackInfo_SmoothSuccess_NaN", - "Phi Vs. Theta", theta, phi, - "#phi Vs. #theta; #theta [deg.]; #phi [deg.]", 70, 0.0, - 140.0, 180, -180.0, 180.0); - Fill2DHistogram("TrackingPulls", "TrackInfo_SmoothSuccess_NaN", - "P Vs. Phi", phi, pmag, - "P Vs. #phi; #phi [deg.]; |P| [GeV/c]", 180, -180, 180.0, - 50, 0.0, 10.0); - continue; + hTrackingFOM_SmoothSuccess_NaN->Fill(trackingFOM); + hTrack_PVsTheta_SmoothSuccess_NaN->Fill(theta, pmag); + hTrack_PhiVsTheta_SmoothSuccess_NaN->Fill(theta, phi); + hTrack_PVsPhi_SmoothSuccess_NaN->Fill(phi, pmag); + continue; } for (size_t iPull = 0; iPull < pulls.size(); iPull++) { @@ -279,33 +434,18 @@ jerror_t JEventProcessor_TrackingPulls::evnt(JEventLoop *loop, double resic = pulls[iPull].resic; double errc = pulls[iPull].errc; - Fill1DHistogram("TrackingPulls", "TrackPulls", "All Pulls", resi / err, - "Residual/Error", 100, -5.0, 5.0); - Fill2DHistogram("TrackingPulls", "TrackPulls", "All Pulls Vs. P", pmag, - resi / err, ";|P| ;Residual/Error", 100, 0.0, 10.0, 100, - -5.0, 5.0); - Fill2DHistogram("TrackingPulls", "TrackPulls", "All Pulls Vs. Phi", phi, - resi / err, ";#phi ;Residual/Error", 180, -180.0, 180.0, - 100, -5.0, 5.0); - Fill2DHistogram("TrackingPulls", "TrackPulls", "All Pulls Vs. Theta", - theta, resi / err, ";#theta ;Residual/Error", 140, 0.0, - 140.0, 100, -5.0, 5.0); - Fill2DHistogram("TrackingPulls", "TrackPulls", "All Pulls Vs. NDF", - locTrackTimeBased->Ndof, resi / err, - ";Track NDF ;Residual/Error", 140, 0.0, 140.0, 100, -5.0, - 5.0); - Fill2DHistogram("TrackingPulls", "TrackPulls", - "All Pulls Vs. Tracking FOM", trackingFOM, resi / err, - ";Track FOM ;Residual/Error", 140, 0.0, 140.0, 100, -5.0, - 5.0); + hAllPulls->Fill(resi / err); + hAllPulls_Vs_P->Fill(pmag, resi / err); + hAllPulls_Vs_Phi->Fill(phi, resi / err); + hAllPulls_Vs_Theta->Fill(theta, resi / err); + hAllPulls_Vs_NDF->Fill(locTrackTimeBased->Ndof, resi / err); + hAllPulls_Vs_TrackingFOM->Fill(trackingFOM, resi / err); + if (fdc_hit != nullptr) { - Fill1DHistogram("TrackingPulls", "TrackPulls", "FDC Wire Error", err, - "Wire Residual Error", 100, 0.0, 0.1); - Fill1DHistogram("TrackingPulls", "TrackPulls", "FDC Cathode Error", - errc, "Cathode Residual Error", 100, 0.0, 0.1); + hFDCWireError->Fill(err); + hFDCCathodeError->Fill(errc); } else { - Fill1DHistogram("TrackingPulls", "TrackPulls", "CDCError", err, - "Residual Error", 100, 0.0, 0.1); + hCDCError->Fill(err); } // Fill some detector specific info @@ -315,203 +455,80 @@ jerror_t JEventProcessor_TrackingPulls::evnt(JEventLoop *loop, if (fdc_hit != nullptr && fdc_hit->wire->layer <= nextPlane) { if (fdc_hit->wire->layer == nextPlane) nextPlane++; - Fill1DHistogram("TrackingPulls", "FDCPulls", "All Wire Pulls", - resi / err, "Residual/Error", 100, -5.0, 5.0); - Fill1DHistogram("TrackingPulls", "FDCPulls", "All Cathode Pulls", - resic / errc, "Residual/Error", 100, -5.0, 5.0); - Fill1DHistogram("TrackingPulls", "FDCPulls", "All Wire Residuals", resi, - "Residual", 100, -0.1, 0.1); - Fill1DHistogram("TrackingPulls", "FDCPulls", "All Cathode Residuals", - resic, "Residual", 100, -0.1, 0.1); - Fill2DHistogram("TrackingPulls", "FDCPulls", - "All Wire Residuals Vs. Plane", fdc_hit->wire->layer, - resi, ";plane ;Residual", 24, 0.5, 24.5, 100, -0.1, - 0.1); - Fill2DHistogram("TrackingPulls", "FDCPulls", - "All Cathode Residuals Vs. Plane", fdc_hit->wire->layer, - resic, ";plane ;Residual", 24, 0.5, 24.5, 100, -0.1, - 0.1); - Fill2DHistogram("TrackingPulls", "FDCPulls", "All Wire Pulls Vs. Plane", - fdc_hit->wire->layer, resi / err, - ";plane ;Residual/Error", 24, 0.5, 24.5, 100, -5.0, - 5.0); - Fill2DHistogram("TrackingPulls", "FDCPulls", - "All Cathode Pulls Vs. Plane", fdc_hit->wire->layer, - resic / errc, ";plane ;Residual/Error", 24, 0.5, 24.5, - 100, -5.0, 5.0); - Fill2DHistogram("TrackingPulls", "FDCPulls", - "All Wire Residuals Vs Drift Time", tdrift, resi, - ";Drift Time;Residual", 170, -20.0, 150.0, 100, -0.1, - 0.1); - Fill2DHistogram("TrackingPulls", "FDCPulls", - "All Wire Pulls Vs Drift Time", tdrift, resi / err, - ";Drift Time;Residual/Error", 170, -20.0, 150.0, 100, - -5.0, 5.0); - Fill2DHistogram("TrackingPulls", "FDCPulls", "All Wire Pulls Vs. P", - pmag, resi / err, ";|P| ;Residual/Error", 100, 0.0, - 10.0, 100, -5.0, 5.0); - Fill2DHistogram("TrackingPulls", "FDCPulls", "All Wire Pulls Vs. Phi", - phi, resi / err, ";#phi ;Residual/Error", 180, -180.0, - 180.0, 100, -5.0, 5.0); - Fill2DHistogram("TrackingPulls", "FDCPulls", "All Wire Pulls Vs. Theta", - theta, resi / err, ";#theta ;Residual/Error", 50, 0.0, - 25.0, 100, -5.0, 5.0); - Fill2DHistogram("TrackingPulls", "FDCPulls", "All Cathode Pulls Vs. P", - pmag, resic / errc, ";|P| ;Residual/Error", 100, 0.0, - 10.0, 100, -5.0, 5.0); - Fill2DHistogram("TrackingPulls", "FDCPulls", - "All Cathode Pulls Vs. Phi", phi, resic / errc, - ";#phi ;Residual/Error", 180, -180.0, 180.0, 100, -5.0, - 5.0); - Fill2DHistogram("TrackingPulls", "FDCPulls", - "All Cathode Pulls Vs. Theta", theta, resic / errc, - ";#theta ;Residual/Error", 50, 0.0, 25.0, 100, -5.0, - 5.0); - Fill2DHistogram("TrackingPulls", "FDCPulls", "All Wire Residuals Vs. P", - pmag, resi, ";|P| ;Residual/Error", 100, 0.0, 10.0, 100, - -0.1, 0.1); - Fill2DHistogram( - "TrackingPulls", "FDCPulls", "All Wire Residuals Vs. Phi", phi, - resi, ";#phi ;Residual/Error", 180, -180.0, 180.0, 100, -0.1, 0.1); - Fill2DHistogram( - "TrackingPulls", "FDCPulls", "All Wire Residuals Vs. Theta", theta, - resi, ";#theta ;Residual/Error", 50, 0.0, 25.0, 100, -0.1, 0.1); - Fill2DHistogram("TrackingPulls", "FDCPulls", - "All Cathode Residuals Vs. P", pmag, resic, - ";|P| ;Residual/Error", 100, 0.0, 10.0, 100, -0.1, 0.1); - Fill2DHistogram( - "TrackingPulls", "FDCPulls", "All Cathode Residuals Vs. Phi", phi, - resic, ";#phi ;Residual/Error", 180, -180.0, 180.0, 100, -0.1, 0.1); - Fill2DHistogram("TrackingPulls", "FDCPulls", - "All Cathode Residuals Vs. Theta", theta, resic, - ";#theta ;Residual/Error", 50, 0.0, 25.0, 100, -0.1, - 0.1); - Fill2DHistogram("TrackingPulls", "FDCPulls", "All Wire Pulls Vs. NDF", - locTrackTimeBased->Ndof, resi / err, - ";Track NDF ;Residual/Error", 50, 0.5, 50.5, 100, -5.0, - 5.0); - Fill2DHistogram("TrackingPulls", "FDCPulls", - "All Wire Pulls Vs. Tracking FOM", trackingFOM, - resi / err, ";Track FOM ;Residual/Error", 100, 0.0, 1.0, - 100, -5.0, 5.0); - Fill2DHistogram("TrackingPulls", "FDCPulls", - "All Cathode Pulls Vs. NDF", locTrackTimeBased->Ndof, - resic / errc, ";Track NDF ;Residual/Error", 50, 0.5, - 50.5, 100, -5.0, 5.0); - Fill2DHistogram("TrackingPulls", "FDCPulls", - "All Cathode Pulls Vs. Tracking FOM", trackingFOM, - resic / errc, ";Track FOM ;Residual/Error", 100, 0.0, - 1.0, 100, -5.0, 5.0); - - // Make the Per-Plane Histograms - char planeName[256]; - sprintf(planeName, "FDCPulls_Plane%.2i", fdc_hit->wire->layer); - - Fill1DHistogram("TrackingPulls", planeName, "All Wire Pulls", - resi / err, "Residual/Error", 100, -5.0, 5.0); - Fill1DHistogram("TrackingPulls", planeName, "All Cathode Pulls", - resic / errc, "Residual/Error", 100, -5.0, 5.0); - Fill1DHistogram("TrackingPulls", planeName, "All Wire Residuals", resi, - "Residual", 100, -0.1, 0.1); + + hFDCAllWirePulls->Fill(resi / err); + hFDCAllCathodeulls->Fill(resic / errc); + hFDCAllWireResiduals->Fill(resi); + hFDCAllCathodeResiduals->Fill(resic); + hFDCAllWireResidualsVsPlane->Fill(fdc_hit->wire->layer, resi); + hFDCAllCathodeResidualsVsPlane->Fill(fdc_hit->wire->layer, resic); + hFDCAllWirePullsVsPlane->Fill(fdc_hit->wire->layer, resi / err); + hFDCAllCathodePullsVsPlane->Fill(fdc_hit->wire->layer, resic / errc); + hFDCAllWireResidualsVsDriftTime->Fill(tdrift, resi); + hFDCAllWirePullsVsDriftTime->Fill(tdrift, resi / err); + hFDCAllWirePullsVsP->Fill(pmag, resi / err); + hFDCAllWirePullsVsTheta->Fill(theta, resi / err); + hFDCAllWirePullsVsPhi->Fill(phi, resi / err); + hFDCAllCathodePullsVsP->Fill(pmag, resic / errc); + hFDCAllCathodePullsVsPhi->Fill(phi, resic / errc); + hFDCAllCathodePullsVsTheta->Fill(theta, resic / errc); + hFDCAllWireResidualsVsP->Fill(pmag, resi); + hFDCAllWireResidualsVsPhi->Fill(phi, resi); + hFDCAllWireResidualsVsTheta->Fill(theta, resi); + hFDCAllCathodeResidualsVsP->Fill(pmag, resic); + hFDCAllCathodeResidualsVsPhi->Fill(phi, resic); + hFDCAllCathodeResidualsVsTheta->Fill(theta, resic); + hFDCAllWirePullsVsNDF->Fill(locTrackTimeBased->Ndof, resi / err); + hFDCAllWirePullsVsTrackingFOM->Fill(trackingFOM, resi / err); + hFDCAllCathodePullsVsNDF->Fill(locTrackTimeBased->Ndof, resic / err); + hFDCAllCathodePullsVsTrackingFOM->Fill(trackingFOM, resic / err); + + hFDCAllWirePulls_ByLayer[fdc_hit->wire->layer - 1]->Fill(resi / err); + hFDCAllCathodeulls_ByLayer[fdc_hit->wire->layer - 1]->Fill(resic / errc); + hFDCAllWireResiduals_ByLayer[fdc_hit->wire->layer - 1]->Fill(resi); if (trackingFOM > 0.02) { - Fill1DHistogram("TrackingPulls", planeName, "wire_residual", resi, "Residual", 200, -0.1, 0.1); - if (pulls[iPull].left_right == 1) { - Fill1DHistogram("TrackingPulls", planeName, "wire_residual_right", resi, "Residual", 200, -0.1, 0.1); - } else if (pulls[iPull].left_right == -1) { - Fill1DHistogram("TrackingPulls", planeName, "wire_residual_left", resi, "Residual", 200, -0.1, 0.1); - } + hFDCWireResidualsGoodTracks_ByLayer[fdc_hit->wire->layer - 1]->Fill(resi); + if (pulls[iPull].left_right == 1) { + hFDCWireResidualsGoodTracksRight_ByLayer[fdc_hit->wire->layer - 1]->Fill(resi); + } else if (pulls[iPull].left_right == -1) { + hFDCWireResidualsGoodTracksLeft_ByLayer[fdc_hit->wire->layer - 1]->Fill(resi); + } } - Fill1DHistogram("TrackingPulls", planeName, "All Cathode Residuals", - resic, "Residual", 100, -0.1, 0.1); - Fill2DHistogram("TrackingPulls", planeName, - "All Wire Residuals Vs Drift Time", tdrift, resi, - ";Drift Time;Residual", 170, -20.0, 150.0, 100, -0.1, - 0.1); - Fill2DHistogram("TrackingPulls", planeName, - "All Wire Pulls Vs Drift Time", tdrift, resi / err, - ";Drift Time;Residual/Error", 170, -20.0, 150.0, 100, - -5.0, 5.0); - Fill2DHistogram("TrackingPulls", planeName, "All Wire Pulls Vs. P", - pmag, resi / err, ";|P| ;Residual/Error", 100, 0.0, - 10.0, 100, -5.0, 5.0); - Fill2DHistogram("TrackingPulls", planeName, "All Wire Pulls Vs. Phi", - phi, resi / err, ";#phi ;Residual/Error", 180, -180.0, - 180.0, 100, -5.0, 5.0); - Fill2DHistogram("TrackingPulls", planeName, "All Wire Pulls Vs. Theta", - theta, resi / err, ";#theta ;Residual/Error", 50, 0.0, - 25.0, 100, -5.0, 5.0); - Fill2DHistogram("TrackingPulls", planeName, "All Wire Residuals Vs. P", - pmag, resi, ";|P| ;Residual", 100, 0.0, 10.0, 100, -0.1, - 0.1); - Fill2DHistogram("TrackingPulls", planeName, - "All Wire Residuals Vs. Phi", phi, resi, - ";#phi ;Residual", 180, -180.0, 180.0, 100, -0.1, 0.1); - Fill2DHistogram("TrackingPulls", planeName, - "All Wire Residuals Vs. Theta", theta, resi, - ";#theta ;Residual", 50, 0.0, 25.0, 100, -0.1, 0.1); - Fill2DHistogram("TrackingPulls", planeName, "All Cathode Pulls Vs. P", - pmag, resic / errc, ";|P| ;Residual/Error", 100, 0.0, - 10.0, 100, -5.0, 5.0); - Fill2DHistogram("TrackingPulls", planeName, "All Cathode Pulls Vs. Phi", - phi, resic / errc, ";#phi ;Residual/Error", 180, -180.0, - 180.0, 100, -5.0, 5.0); - Fill2DHistogram("TrackingPulls", planeName, - "All Cathode Pulls Vs. Theta", theta, resic / errc, - ";#theta ;Residual/Error", 50, 0.0, 25.0, 100, -5.0, - 5.0); - Fill2DHistogram("TrackingPulls", planeName, - "All Cathode Residuals Vs. P", pmag, resic, - ";|P| ;Residual", 100, 0.0, 10.0, 100, -0.1, 0.1); - Fill2DHistogram("TrackingPulls", planeName, - "All Cathode Residuals Vs. Phi", phi, resic, - ";#phi ;Residual", 180, -180.0, 180.0, 100, -0.1, 0.1); - Fill2DHistogram("TrackingPulls", planeName, - "All Cathode Residuals Vs. Theta", theta, resic, - ";#theta ;Residual", 50, 0.0, 25.0, 100, -0.1, 0.1); - Fill2DHistogram("TrackingPulls", planeName, "Wire Pulls", - fdc_hit->wire->wire, resi / err, - ";Wire Number ;Residual/Error", 96, 0.5, 96.5, 100, - -5.0, 5.0); - Fill2DHistogram("TrackingPulls", planeName, "Wire Residuals", - fdc_hit->wire->wire, resi, ";Wire Number ;Residual", 96, - 0.5, 96.5, 100, -0.1, 0.1); + + hFDCAllCathodeResiduals_ByLayer[fdc_hit->wire->layer - 1]->Fill(resic); + hFDCAllWireResidualsVsDriftTime_ByLayer[fdc_hit->wire->layer - 1]->Fill(tdrift, resi); + hFDCAllWirePullsVsDriftTime_ByLayer[fdc_hit->wire->layer - 1]->Fill(tdrift, resi / err); + hFDCAllWirePullsVsP_ByLayer[fdc_hit->wire->layer - 1]->Fill(pmag, resi / err); + hFDCAllWirePullsVsTheta_ByLayer[fdc_hit->wire->layer - 1]->Fill(theta, resi / err); + hFDCAllWirePullsVsPhi_ByLayer[fdc_hit->wire->layer - 1]->Fill(phi, resi / err); + hFDCAllCathodePullsVsP_ByLayer[fdc_hit->wire->layer - 1]->Fill(pmag, resic / errc); + hFDCAllCathodePullsVsPhi_ByLayer[fdc_hit->wire->layer - 1]->Fill(phi, resic / errc); + hFDCAllCathodePullsVsTheta_ByLayer[fdc_hit->wire->layer - 1]->Fill(theta, resic / errc); + hFDCAllWireResidualsVsP_ByLayer[fdc_hit->wire->layer - 1]->Fill(pmag, resi); + hFDCAllWireResidualsVsPhi_ByLayer[fdc_hit->wire->layer - 1]->Fill(phi, resi); + hFDCAllWireResidualsVsTheta_ByLayer[fdc_hit->wire->layer - 1]->Fill(theta, resi); + hFDCAllCathodeResidualsVsP_ByLayer[fdc_hit->wire->layer - 1]->Fill(pmag, resic); + hFDCAllCathodeResidualsVsPhi_ByLayer[fdc_hit->wire->layer - 1]->Fill(phi, resic); + hFDCAllCathodeResidualsVsTheta_ByLayer[fdc_hit->wire->layer - 1]->Fill(theta, resic); + hFDCWirePulls_ByLayer[fdc_hit->wire->layer - 1]->Fill(fdc_hit->wire->wire, resi / err); + hFDCWireResiduals_ByLayer[fdc_hit->wire->layer - 1]->Fill(fdc_hit->wire->wire, resi); + if (fabs(resi / err) < 5.0) { - Fill2DProfile("TrackingPulls", planeName, "2D Wire Hit Pulls", - fdc_hit->xy.X(), fdc_hit->xy.Y(), resi / err, - "Mean of Wire Pulls vs. PseudoHit XY", 100, -50., 50., - 100, -50., 50.); + hFDC2DWirePulls_ByLayer[fdc_hit->wire->layer - 1]->Fill(fdc_hit->xy.X(), fdc_hit->xy.Y(), resi / err); } if (fabs(resi) < 0.1) { - Fill2DProfile("TrackingPulls", planeName, "2D Wire Hit Residuals", - fdc_hit->xy.X(), fdc_hit->xy.Y(), resi, - "Mean of Wire Residuals vs. PseudoHit XY", 100, -50., - 50., 100, -50., 50.); - Fill2DProfile("TrackingPulls", planeName, - "2D Wire Hit Residuals Local", fdc_hit->w, fdc_hit->s, - resi, - "Mean of Wire Residuals vs. PseudoHit WS;Perpendicular " - "Distance to Wire; Distance Along the Wire", - 100, -50., 50., 100, -50., 50.); + hFDC2DWireResiduals_ByLayer[fdc_hit->wire->layer - 1]->Fill(fdc_hit->xy.X(), fdc_hit->xy.Y(), resi); + hFDC2DWireResidualsLocal_ByLayer[fdc_hit->wire->layer - 1]->Fill(fdc_hit->w, fdc_hit->s, resi); } if (fabs(resic / errc) < 5.0) { - Fill2DProfile("TrackingPulls", planeName, "2D Cathode Hit Pulls", - fdc_hit->xy.X(), fdc_hit->xy.Y(), resic / errc, - "Mean of Cathode Pulls vs. PseudoHit XY", 100, -50., - 50., 100, -50., 50.); + hFDC2DCathodePulls_ByLayer[fdc_hit->wire->layer - 1]->Fill(fdc_hit->xy.X(), fdc_hit->xy.Y(), resic / err); } if (fabs(resic) < 0.1) { - Fill2DProfile("TrackingPulls", planeName, "2D Cathode Hit Residuals", - fdc_hit->xy.X(), fdc_hit->xy.Y(), resic, - "Mean of Cathode Residuals vs. PseudoHit XY", 100, -50., - 50., 100, -50., 50.); - Fill2DProfile( - "TrackingPulls", planeName, "2D Cathode Hit Residuals Local", - fdc_hit->w, fdc_hit->s, resic, - "Mean of Cathode Residuals vs. PseudoHit WS;Perpendicular " - "Distance to Wire; Distance Along the Wire", - 100, -50., 50., 100, -50., 50.); + hFDC2DCathodeResiduals_ByLayer[fdc_hit->wire->layer - 1]->Fill(fdc_hit->xy.X(), fdc_hit->xy.Y(), resic); + hFDC2DCathodeResidualsLocal_ByLayer[fdc_hit->wire->layer - 1]->Fill(fdc_hit->w, fdc_hit->s, resic); } + if (MAKE_TREE){ dTreeFillData.Fill_Array("fdc_resi", resi, fdc_hit->wire->layer - 1); dTreeFillData.Fill_Array("fdc_resic", resic, fdc_hit->wire->layer - 1); @@ -534,112 +551,46 @@ jerror_t JEventProcessor_TrackingPulls::evnt(JEventLoop *loop, (nextPlane == 25 || evntCount > 1000)) { if (cdc_hit->wire->ring == nextRing) nextRing++; - Fill1DHistogram("TrackingPulls", "CDCPulls", "All Residuals", resi, - "Residual", 100, -0.1, 0.1); - Fill1DHistogram("TrackingPulls", "CDCPulls", "All Pulls", resi / err, - "Residual/Error", 100, -5.0, 5.0); - Fill2DHistogram("TrackingPulls", "CDCPulls", "All Pulls Vs. Ring", - cdc_hit->wire->ring, resi / err, - ";ring ;Residual/Error", 28, 0.5, 28.5, 100, -5.0, 5.0); - Fill2DHistogram("TrackingPulls", "CDCPulls", "All Residuals Vs. Ring", - cdc_hit->wire->ring, resi, ";ring ;Residual", 28, 0.5, - 28.5, 100, -0.1, 0.1); - Fill2DHistogram("TrackingPulls", "CDCPulls", "All Pulls Vs. tdrift", - tdrift, resi / err, ";tdrift [ns] ;Residual/Error", 200, - 0.0, 1000.0, 100, -5.0, 5.0); - Fill2DHistogram("TrackingPulls", "CDCPulls", "All Residuals Vs. tdrift", - tdrift, resi, ";tdrift [ns] ;Residual", 200, 0.0, - 1000.0, 100, -0.1, 0.1); - Fill2DHistogram("TrackingPulls", "CDCPulls", "All Pulls Vs. P", pmag, - resi / err, ";|P| ;Residual/Error", 50, 0.0, 10.0, 100, - -5.0, 5.0); - Fill2DHistogram("TrackingPulls", "CDCPulls", "All Pulls Vs. Phi", phi, - resi / err, ";#phi ;Residual/Error", 180, -180.0, 180.0, - 100, -5.0, 5.0); - Fill2DHistogram("TrackingPulls", "CDCPulls", "All Pulls Vs. Theta", - theta, resi / err, ";#theta ;Residual/Error", 140, 0.0, - 140.0, 100, -5.0, 5.0); - Fill2DHistogram("TrackingPulls", "CDCPulls", "All Residuals Vs. P", - pmag, resi, ";|P| ;Residual", 50, 0.0, 10.0, 100, -0.1, - 0.1); - Fill2DHistogram("TrackingPulls", "CDCPulls", "All Residuals Vs. Phi", - phi, resi, ";#phi ;Residual", 180, -180.0, 180.0, 100, - -0.1, 0.1); - Fill2DHistogram("TrackingPulls", "CDCPulls", "All Residuals Vs. Theta", - theta, resi, ";#theta ;Residual", 140, 0.0, 140.0, 100, - -0.1, 0.1); - Fill2DHistogram("TrackingPulls", "CDCPulls", "All Pulls Vs. NDF", - locTrackTimeBased->Ndof, resi / err, - ";Track NDF ;Residual/Error", 50, 0.5, 50.5, 100, -5.0, - 5.0); - Fill2DHistogram("TrackingPulls", "CDCPulls", - "All Pulls Vs. Tracking FOM", trackingFOM, resi / err, - ";Track FOM ;Residual/Error", 100, 0.0, 1.0, 100, -5.0, - 5.0); - - // Make the Per-Ring Histograms - char ringName[256]; - sprintf(ringName, "CDCPulls_Ring%.2i", cdc_hit->wire->ring); - - Fill1DHistogram("TrackingPulls", ringName, "All Residuals", resi, - "Residual", 100, -0.1, 0.1); - Fill1DHistogram("TrackingPulls", ringName, "All Pulls", resi / err, - "Residual/Error", 100, -5.0, 5.0); - Fill2DHistogram("TrackingPulls", ringName, "All Pulls Vs. tdrift", - tdrift, resi / err, ";tdrift [ns] ;Residual/Error", 200, - 0.0, 1000.0, 100, -5.0, 5.0); - Fill2DHistogram("TrackingPulls", ringName, "All Pulls Vs. z", z, - resi / err, ";z [cm] ;Residual/Error", 200, -30., 200., - 100, -5.0, 5.0); - Fill2DHistogram("TrackingPulls", ringName, "All Residuals Vs. tdrift", - tdrift, resi, ";tdrift [ns] ;Residual", 200, 0.0, - 1000.0, 100, -0.1, 0.1); - Fill2DHistogram("TrackingPulls", ringName, "All Residuals Vs. z", z, - resi, ";z [cm] ;Residual", 200, -30., 200.0, 100, -0.1, - 0.1); - Fill2DHistogram("TrackingPulls", ringName, "All Pulls Vs. P", pmag, - resi / err, ";|P| ;Residual/Error", 50, 0.0, 10.0, 100, - -5.0, 5.0); - Fill2DHistogram("TrackingPulls", ringName, "All Pulls Vs. Phi", phi, - resi / err, ";#phi ;Residual/Error", 180, -180.0, 180.0, - 100, -5.0, 5.0); - Fill2DHistogram("TrackingPulls", ringName, "All Pulls Vs. Theta", theta, - resi / err, ";#theta ;Residual/Error", 140, 0.0, 140.0, - 100, -5.0, 5.0); - Fill2DHistogram("TrackingPulls", ringName, "All Residuals Vs. P", pmag, - resi, ";|P| ;Residual", 50, 0.0, 10.0, 100, -0.1, 0.1); - Fill2DHistogram("TrackingPulls", ringName, "All Residuals Vs. Phi", phi, - resi, ";#phi ;Residual", 180, -180.0, 180.0, 100, -0.1, - 0.1); - Fill2DHistogram("TrackingPulls", ringName, "All Residuals Vs. Theta", - theta, resi, ";#theta ;Residual", 140, 0.0, 140.0, 100, - -0.1, 0.1); - - double nStraw = numstraws[cdc_hit->wire->ring - 1]; + hCDCAllPulls->Fill(resi / err); + hCDCAllResiduals->Fill(resi); + hCDCAllResidualsVsRing->Fill(cdc_hit->wire->ring, resi); + hCDCAllPullsVsRing->Fill(cdc_hit->wire->ring, resi / err); + hCDCAllResidualsVsDriftTime->Fill(tdrift, resi); + hCDCAllPullsVsDriftTime->Fill(tdrift, resi / err); + hCDCAllPullsVsP->Fill(pmag, resi / err); + hCDCAllPullsVsTheta->Fill(theta, resi / err); + hCDCAllPullsVsPhi->Fill(phi, resi / err); + hCDCAllResidualsVsP->Fill(pmag, resi); + hCDCAllResidualsVsPhi->Fill(phi, resi); + hCDCAllResidualsVsTheta->Fill(theta, resi); + hCDCAllPullsVsNDF->Fill(locTrackTimeBased->Ndof, resi / err); + hCDCAllPullsVsTrackingFOM->Fill(trackingFOM, resi / err); + + hCDCAllPulls_ByRing[cdc_hit->wire->ring - 1]->Fill(resi / err); + hCDCAllResiduals_ByRing[cdc_hit->wire->ring - 1]->Fill(resi); + hCDCAllResidualsVsDriftTime_ByRing[cdc_hit->wire->ring - 1]->Fill(tdrift, resi); + hCDCAllPullsVsDriftTime_ByRing[cdc_hit->wire->ring - 1]->Fill(tdrift, resi / err); + hCDCAllResidualsVsZ_ByRing[cdc_hit->wire->ring - 1]->Fill(z, resi); + hCDCAllPullsVsZ_ByRing[cdc_hit->wire->ring - 1]->Fill(z, resi / err); + hCDCAllPullsVsP_ByRing[cdc_hit->wire->ring - 1]->Fill(pmag, resi / err); + hCDCAllPullsVsTheta_ByRing[cdc_hit->wire->ring - 1]->Fill(theta, resi / err); + hCDCAllPullsVsPhi_ByRing[cdc_hit->wire->ring - 1]->Fill(phi, resi / err); + hCDCAllResidualsVsP_ByRing[cdc_hit->wire->ring - 1]->Fill(pmag, resi); + hCDCAllResidualsVsPhi_ByRing[cdc_hit->wire->ring - 1]->Fill(phi, resi); + hCDCAllResidualsVsTheta_ByRing[cdc_hit->wire->ring - 1]->Fill(theta, resi); + double phiIntersect = (cdc_hit->wire->origin + (z - 92.0) * cdc_hit->wire->udir).Phi() * TMath::RadToDeg(); - Fill2DHistogram("TrackingPulls", ringName, "Per Straw Pulls", - cdc_hit->wire->straw, resi / err, - ";Straw Number ;Residual/Error", nStraw, 0.5, - nStraw + 0.5, 100, -5.0, 5.0); - Fill2DHistogram("TrackingPulls", ringName, "Per Straw Residuals", - cdc_hit->wire->straw, resi, ";Straw Number ;Residual", - nStraw, 0.5, nStraw + 0.5, 100, -0.1, 0.1); + hCDCStrawPulls_ByRing[cdc_hit->wire->ring - 1]->Fill(cdc_hit->wire->straw, resi / err); + hCDCStrawResiduals_ByRing[cdc_hit->wire->ring -1]->Fill(cdc_hit->wire->straw, resi); if (fabs(resi) < 0.1) { - Fill2DProfile("TrackingPulls", ringName, "Residual Vs Phi-Theta", - theta, phi, resi, ";#theta;#phi", 70, 0.0, 140.0, 180, - -180.0, 180.0); - Fill2DProfile("TrackingPulls", ringName, "Residual Vs Phi-z", z, phi, - resi, ";z;#phi", 200, 0.0, 200.0, 180, -180.0, 180.0); - Fill2DProfile("TrackingPulls", ringName, "Residual Vs PhiIntersect-z", - z, phiIntersect, resi, ";z;#phi Intersect", 200, 0.0, - 200.0, nStraw, -180.0, 180.0); - Fill2DProfile("TrackingPulls", ringName, "Residual Vs P-Theta", theta, - pmag, resi, ";#theta;|P|", 70, 0.0, 140.0, 50, 0.0, - 10.0); + hCDCStrawResidualsVsPhiTheta_ByRing[cdc_hit->wire->ring - 1]->Fill(theta, phi, resi); + hCDCStrawResidualsVsPhiZ_ByRing[cdc_hit->wire->ring - 1]->Fill(z, phi, resi); + hCDCStrawResidualsVsPhiIntersectZ_ByRing[cdc_hit->wire->ring - 1]->Fill(z, phiIntersect, resi); + hCDCStrawResidualsVsPTheta_ByRing[cdc_hit->wire->ring - 1]->Fill(theta, pmag, resi); } if (MAKE_TREE){ @@ -657,6 +608,9 @@ jerror_t JEventProcessor_TrackingPulls::evnt(JEventLoop *loop, dTreeInterface->Fill(dTreeFillData); } + japp->RootUnLock(); //RELEASE ROOT LOCK!! + + return NOERROR; } diff --git a/src/plugins/monitoring/TrackingPulls/JEventProcessor_TrackingPulls.h b/src/plugins/monitoring/TrackingPulls/JEventProcessor_TrackingPulls.h index 1f24c6cc76..259e75ef4f 100644 --- a/src/plugins/monitoring/TrackingPulls/JEventProcessor_TrackingPulls.h +++ b/src/plugins/monitoring/TrackingPulls/JEventProcessor_TrackingPulls.h @@ -12,6 +12,12 @@ #include "ANALYSIS/DTreeInterface.h" #include +#include +#include +#include +#include +#include + class JEventProcessor_TrackingPulls : public jana::JEventProcessor { public: JEventProcessor_TrackingPulls(); @@ -37,6 +43,131 @@ class JEventProcessor_TrackingPulls : public jana::JEventProcessor { bool MAKE_TREE; DTreeInterface* dTreeInterface; static thread_local DTreeFillData dTreeFillData; + + + TH1I *hTrackingFOM; + TH2I *hTrack_PVsTheta; + TH2I *hTrack_PhiVsTheta; + TH2I *hTrack_PVsPhi; + + TH1I *hTrackingFOM_SmoothFailure; + TH2I *hTrack_PVsTheta_SmoothFailure; + TH2I *hTrack_PhiVsTheta_SmoothFailure; + TH2I *hTrack_PVsPhi_SmoothFailure; + + TH1I *hTrackingFOM_SmoothSuccess; + TH2I *hTrack_PVsTheta_SmoothSuccess; + TH2I *hTrack_PhiVsTheta_SmoothSuccess; + TH2I *hTrack_PVsPhi_SmoothSuccess; + + TH1I *hTrackingFOM_SmoothSuccess_NaN; + TH2I *hTrack_PVsTheta_SmoothSuccess_NaN; + TH2I *hTrack_PhiVsTheta_SmoothSuccess_NaN; + TH2I *hTrack_PVsPhi_SmoothSuccess_NaN; + + TH1I *hAllPulls; + TH2I *hAllPulls_Vs_P; + TH2I *hAllPulls_Vs_Phi; + TH2I *hAllPulls_Vs_Theta; + TH2I *hAllPulls_Vs_NDF; + TH2I *hAllPulls_Vs_TrackingFOM; + TH1I *hFDCWireError; + TH1I *hFDCCathodeError; + TH1I *hCDCError; + + TH1I *hFDCAllWirePulls; + TH1I *hFDCAllCathodeulls; + TH1I *hFDCAllWireResiduals; + TH1I *hFDCAllCathodeResiduals; + TH2I *hFDCAllWireResidualsVsPlane; + TH2I *hFDCAllCathodeResidualsVsPlane; + TH2I *hFDCAllWirePullsVsPlane; + TH2I *hFDCAllCathodePullsVsPlane; + TH2I *hFDCAllWireResidualsVsDriftTime; + TH2I *hFDCAllWirePullsVsDriftTime; + TH2I *hFDCAllWirePullsVsP; + TH2I *hFDCAllWirePullsVsPhi; + TH2I *hFDCAllWirePullsVsTheta; + TH2I *hFDCAllCathodePullsVsP; + TH2I *hFDCAllCathodePullsVsPhi; + TH2I *hFDCAllCathodePullsVsTheta; + TH2I *hFDCAllWireResidualsVsP; + TH2I *hFDCAllWireResidualsVsPhi; + TH2I *hFDCAllWireResidualsVsTheta; + TH2I *hFDCAllCathodeResidualsVsP; + TH2I *hFDCAllCathodeResidualsVsPhi; + TH2I *hFDCAllCathodeResidualsVsTheta; + TH2I *hFDCAllWirePullsVsNDF; + TH2I *hFDCAllWirePullsVsTrackingFOM; + TH2I *hFDCAllCathodePullsVsNDF; + TH2I *hFDCAllCathodePullsVsTrackingFOM; + + vector hFDCAllWirePulls_ByLayer; + vector hFDCAllCathodeulls_ByLayer; + vector hFDCAllWireResiduals_ByLayer; + vector hFDCAllCathodeResiduals_ByLayer; + vector hFDCWireResidualsGoodTracks_ByLayer; + vector hFDCWireResidualsGoodTracksRight_ByLayer; + vector hFDCWireResidualsGoodTracksLeft_ByLayer; + vector hFDCAllWireResidualsVsDriftTime_ByLayer; + vector hFDCAllWirePullsVsDriftTime_ByLayer; + vector hFDCAllWirePullsVsP_ByLayer; + vector hFDCAllWirePullsVsPhi_ByLayer; + vector hFDCAllWirePullsVsTheta_ByLayer; + vector hFDCAllCathodePullsVsP_ByLayer; + vector hFDCAllCathodePullsVsPhi_ByLayer; + vector hFDCAllCathodePullsVsTheta_ByLayer; + vector hFDCAllWireResidualsVsP_ByLayer; + vector hFDCAllWireResidualsVsPhi_ByLayer; + vector hFDCAllWireResidualsVsTheta_ByLayer; + vector hFDCAllCathodeResidualsVsP_ByLayer; + vector hFDCAllCathodeResidualsVsPhi_ByLayer; + vector hFDCAllCathodeResidualsVsTheta_ByLayer; + + vector hFDCWirePulls_ByLayer; + vector hFDCWireResiduals_ByLayer; + vector hFDC2DWirePulls_ByLayer; + vector hFDC2DWireResiduals_ByLayer; + vector hFDC2DWireResidualsLocal_ByLayer; + vector hFDC2DCathodePulls_ByLayer; + vector hFDC2DCathodeResiduals_ByLayer; + vector hFDC2DCathodeResidualsLocal_ByLayer; + + TH1I *hCDCAllPulls; + TH1I *hCDCAllResiduals; + TH2I *hCDCAllResidualsVsRing; + TH2I *hCDCAllPullsVsRing; + TH2I *hCDCAllResidualsVsDriftTime; + TH2I *hCDCAllPullsVsDriftTime; + TH2I *hCDCAllPullsVsP; + TH2I *hCDCAllPullsVsPhi; + TH2I *hCDCAllPullsVsTheta; + TH2I *hCDCAllResidualsVsP; + TH2I *hCDCAllResidualsVsPhi; + TH2I *hCDCAllResidualsVsTheta; + TH2I *hCDCAllPullsVsNDF; + TH2I *hCDCAllPullsVsTrackingFOM; + + vector hCDCAllPulls_ByRing; + vector hCDCAllResiduals_ByRing; + vector hCDCAllResidualsVsDriftTime_ByRing; + vector hCDCAllPullsVsDriftTime_ByRing; + vector hCDCAllResidualsVsZ_ByRing; + vector hCDCAllPullsVsZ_ByRing; + vector hCDCAllPullsVsP_ByRing; + vector hCDCAllPullsVsPhi_ByRing; + vector hCDCAllPullsVsTheta_ByRing; + vector hCDCAllResidualsVsP_ByRing; + vector hCDCAllResidualsVsPhi_ByRing; + vector hCDCAllResidualsVsTheta_ByRing; + vector hCDCStrawPulls_ByRing; + vector hCDCStrawResiduals_ByRing; + + vector hCDCStrawResidualsVsPhiTheta_ByRing; + vector hCDCStrawResidualsVsPhiZ_ByRing; + vector hCDCStrawResidualsVsPhiIntersectZ_ByRing; + vector hCDCStrawResidualsVsPTheta_ByRing; + }; #endif // _JEventProcessor_TrackingPulls_ diff --git a/src/plugins/monitoring/TrackingPulls_straight/JEventProcessor_TrackingPulls_straight.cc b/src/plugins/monitoring/TrackingPulls_straight/JEventProcessor_TrackingPulls_straight.cc index 2daa2000df..c19f116304 100644 --- a/src/plugins/monitoring/TrackingPulls_straight/JEventProcessor_TrackingPulls_straight.cc +++ b/src/plugins/monitoring/TrackingPulls_straight/JEventProcessor_TrackingPulls_straight.cc @@ -36,6 +36,8 @@ jerror_t JEventProcessor_TrackingPulls_straight::init(void) { tree_->Branch("track_index", &track_index_, "track_index/I"); tree_->Branch("chi2", &chi2_, "chi2/D"); tree_->Branch("ndf", &ndf_, "ndf/I"); + tree_->Branch("ncdchits", &ncdchits_, "ncdchits/I"); + tree_->Branch("nfdchits", &nfdchits_, "nfdchits/I"); tree_->Branch("mom", &mom_, "mom/D"); tree_->Branch("phi", &phi_, "phi/D"); tree_->Branch("theta", &theta_, "theta/D"); @@ -123,6 +125,8 @@ jerror_t JEventProcessor_TrackingPulls_straight::evnt(JEventLoop *loop, track_index_ = (int)i; chi2_ = track->chisq; ndf_ = track->Ndof; + ncdchits_ = track->measured_cdc_hits_on_track; + nfdchits_ = track->measured_fdc_hits_on_track; mom_ = track->momentum().Mag(); phi_ = track->momentum().Phi() * TMath::RadToDeg(); theta_ = track->momentum().Theta() * TMath::RadToDeg(); diff --git a/src/plugins/monitoring/TrackingPulls_straight/JEventProcessor_TrackingPulls_straight.h b/src/plugins/monitoring/TrackingPulls_straight/JEventProcessor_TrackingPulls_straight.h index 3bd8fa609e..43431e6592 100644 --- a/src/plugins/monitoring/TrackingPulls_straight/JEventProcessor_TrackingPulls_straight.h +++ b/src/plugins/monitoring/TrackingPulls_straight/JEventProcessor_TrackingPulls_straight.h @@ -39,6 +39,8 @@ class JEventProcessor_TrackingPulls_straight : public jana::JEventProcessor { int track_index_; double chi2_; int ndf_; + int ncdchits_; + int nfdchits_; double mom_; double phi_; double theta_; diff --git a/src/programs/Utilities/SConscript b/src/programs/Utilities/SConscript index fb894ccdf2..9120982ce9 100644 --- a/src/programs/Utilities/SConscript +++ b/src/programs/Utilities/SConscript @@ -5,7 +5,8 @@ Import('*') # Default targets (always built) subdirs = ['analysis', 'root_merge', 'root2email'] -subdirs.extend( ['hddm', 'hddm_cull_events', 'hddm_merge_files']) +#subdirs.extend( ['hddm'] ) +subdirs.extend( ['hddm_cull_events', 'hddm_merge_files']) subdirs.extend( ['mkplugin', 'mkfactory_plugin'] ) subdirs.extend( ['hdevio_scan', 'hdbeam_current', 'hdevio_sample', 'hdskims'] ) subdirs.extend( ['mergeTrees'] ) diff --git a/src/programs/Utilities/analysis/MakeReactionPlugin.pl b/src/programs/Utilities/analysis/MakeReactionPlugin.pl index b991776f41..27b20bb93e 100755 --- a/src/programs/Utilities/analysis/MakeReactionPlugin.pl +++ b/src/programs/Utilities/analysis/MakeReactionPlugin.pl @@ -620,6 +620,17 @@ () { # Contents of default SConstruct file for plugins $content = " +from __future__ import division +from __future__ import absolute_import +from __future__ import print_function +from __future__ import unicode_literals + +from builtins import map +from builtins import str +from builtins import open +from builtins import int +from future import standard_library +standard_library.install_aliases() import os import sys @@ -629,7 +640,7 @@ () # Get HALLD_RECON_HOME environment variable, verifying it is set halld_home = os.getenv('HALLD_RECON_HOME') if(halld_home == None): - print 'HALLD_RECON_HOME environment variable not set!' + print('HALLD_RECON_HOME environment variable not set!') exit(-1) # Get HALLD_MY if it exists. Otherwise use HALLD_RECON_HOME @@ -651,7 +662,8 @@ () osname = os.getenv('BMS_OSNAME', 'build') # Get architecture name -arch = subprocess.Popen([\"uname\"], stdout=subprocess.PIPE).communicate()[0].strip() +arch_out = ROOT_CFLAGS = subprocess.Popen([\"uname\"], stdout=subprocess.PIPE).communicate()[0].strip() +arch = str(arch_out, 'utf-8') # Setup initial environment plugininstalldir = halld_my diff --git a/src/programs/Utilities/hddm/Makefile b/src/programs/Utilities/hddm/Makefile deleted file mode 100644 index 40b46b868d..0000000000 --- a/src/programs/Utilities/hddm/Makefile +++ /dev/null @@ -1,111 +0,0 @@ -OStype = $(shell uname) -ARCHtype = $(shell uname -m) - -ifndef OS -OS = $(shell uname) -endif -ifndef ARCH -ARCH = $(shell uname -p) -endif -ifndef OSNAME -OSNAME = $(OS)-$(ARCH) -endif - -# HALLD_MY is used for installation below but if it is -# not defined, then we should try installing into HALLD_HOME -ifndef HALLD_MY -HALLD_MY = $(HALLD_HOME) -endif - -CPP = c++ -LIBXDR = - -ifeq ($(OStype),Linux) - ifeq ($(ARCHtype),alpha) - CPP := c++ -g - else - CPP := c++ -g -D_REENTRANT - endif -endif -ifeq ($(OStype),OSF1) - CPP := c++ -g -DBASENAME_USE_BUILTIN -endif -ifeq ($(OStype),Darwin) - CPP := c++ -g -DBASENAME_IN_LIBGEN -DXDR_LONGLONG_MISSING -endif -ifeq ($(OStype),SunOS) - CPP := CC -g -DBASENAME_IN_LIBGEN - LIBXDR := -lnsl -endif - -OBJDIR = .obj/$(BMS_OSNAME) -BINDIR = .bin/$(BMS_OSNAME) -BINARIES = $(BINDIR)/xml-hddm $(BINDIR)/hddm-xml $(BINDIR)/hddm-c $(BINDIR)/hddm-cpp $(BINDIR)/hddmcat - -all: mkdirs $(BINARIES) - -mkdirs: - mkdir -p $(OBJDIR) $(BINDIR) - -install: xml-xml hddm-schema schema-hddm mkdirs $(BINARIES) - mkdir -p $(HALLD_MY)/$(BMS_OSNAME)/bin - cp -v hddm-schema schema-hddm xml-xml $(HALLD_MY)/$(BMS_OSNAME)/bin - mkdir -p $(HALLD_MY)/$(BMS_OSNAME)/bin - cp -v $(BINARIES) $(HALLD_MY)/$(BMS_OSNAME)/bin - -$(BINDIR)/xml-hddm: xml-hddm.cpp $(OBJDIR)/XString.o $(OBJDIR)/XParsers.o $(OBJDIR)/md5.o - $(CPP) $(LD_FLAGS) -I$(HALLD_MY)/include -I$(HALLD_HOME)/src/include -I$(XERCESCROOT)/include \ - -I$(HALLD_HOME)/$(BMS_OSNAME)/include -o $@ $^ \ - -L$(HALLD_MY)/$(BMS_OSNAME)/lib \ - -L$(HALLD_HOME)/$(BMS_OSNAME)/lib -lxstream \ - -L$(XERCESCROOT)/lib -lxerces-c $(LIBXDR) - -$(BINDIR)/hddm-xml: hddm-xml.cpp $(OBJDIR)/XString.o $(OBJDIR)/XParsers.o $(OBJDIR)/md5.o - $(CPP) $(LD_FLAGS) -I$(HALLD_MY)/include -I$(HALLD_HOME)/src/include -I$(XERCESCROOT)/include \ - -I$(HALLD_HOME)/$(BMS_OSNAME)/include -o $@ $^ \ - -L$(HALLD_MY)/$(BMS_OSNAME)/lib \ - -L$(HALLD_HOME)/$(BMS_OSNAME)/lib -lxstream -lbz2 -lz \ - -L$(XERCESCROOT)/lib -lxerces-c $(LIBXDR) - -$(BINDIR)/hddm-c: hddm-c.cpp $(OBJDIR)/XString.o $(OBJDIR)/XParsers.o $(OBJDIR)/md5.o - $(CPP) $(LD_FLAGS) -I$(HALLD_MY)/include -I$(HALLD_HOME)/src/include -I$(XERCESCROOT)/include \ - -I$(HALLD_HOME)/$(BMS_OSNAME)/include -o $@ $^ \ - -L$(XERCESCROOT)/lib -lxerces-c $(LIBXDR) - -$(BINDIR)/hddm-cpp: hddm-cpp.cpp $(OBJDIR)/XString.o $(OBJDIR)/XParsers.o $(OBJDIR)/md5.o - $(CPP) $(LD_FLAGS) -I$(HALLD_MY)/include -I$(HALLD_HOME)/src/include -I$(XERCESCROOT)/include \ - -I$(HALLD_HOME)/$(BMS_OSNAME)/include -o $@ $^ \ - -L$(XERCESCROOT)/lib -lxerces-c $(LIBXDR) - -$(BINDIR)/hddmcat: hddmcat.cpp - $(CPP) $(LD_FLAGS) -o $@ $^ - -test: $(BINDIR)/hddm-c $(BINDIR)/hddm-cpp $(BINDIR)/hddm-xml test.xml - hddm-c test.xml - hddm-cpp test.xml - $(CPP) $(LD_FLAGS) -I$(HALLD_MY)/include -I$(HALLD_HOME)/src/include -I$(XERCESCROOT)/include \ - -I$(HALLD_HOME)/$(BMS_OSNAME)/include -o testhddm -L$(HALLD_HOME)/lib/$(BMS_OSNAME) \ - testhddm.cpp hddm_v.c hddm_v.cpp -lxstream $(LIBXDR) -lz -lbz2 - ./testhddm - hddm-xml test.hddm - -%.xsd: %.xml hddm-schema.xsl - ./hddm-schema $< >$@ - -$(OBJDIR)/%.o: %.cpp - $(CPP) $(CXXFLAGS) -I$(HALLD_MY)/include -I$(HALLD_HOME)/src/include -I$(XERCESCROOT)/include \ - -I$(HALLD_HOME)/$(BMS_OSNAME)/include -c -o $@ $^ - -$(OBJDIR)/%.o: %.c - $(CPP) $(CXXFLAGS) -I$(HALLD_MY)/include -I$(HALLD_HOME)/src/include -I$(XERCESCROOT)/include \ - -I$(HALLD_HOME)/$(BMS_OSNAME)/include -c -o $@ $^ - -clean: - /bin/rm -f $(OBJDIR)/*.o core *.depend - -depclean: - @echo "Nothing to do for make depclean in hddm" - -pristine: clean - -# end of makefile diff --git a/src/programs/Utilities/hddm/Makefile.OSX b/src/programs/Utilities/hddm/Makefile.OSX deleted file mode 100644 index 8e16de83ce..0000000000 --- a/src/programs/Utilities/hddm/Makefile.OSX +++ /dev/null @@ -1,16 +0,0 @@ - -PACKAGES := XERCES -MISC_LIBS = -L/sw/lib -lXm -L/usr/X11R6/lib -lXt -lf2c -lg2c -lcompat -lgelhad - -include $(HALLD_DIR)/src/BMS/Makefile.bin - -c: hddm-c hddm-cpp - hddm-c event.xml - hddm-cpp event.xml - -install: c - mv hddm_s.h hddm_s.hpp $(HALLD_HOME)/src/libraries/include - mv hddm_s.c hddm_containers_s.cc $(HALLD_HOME)/src/libraries/HDDM - -klean: - rm -f hddm_s.h hddm_s.hpp hddm_s.c hddm_containers_s.cc diff --git a/src/programs/Utilities/hddm/README.txt b/src/programs/Utilities/hddm/README.txt deleted file mode 100644 index 956f030227..0000000000 --- a/src/programs/Utilities/hddm/README.txt +++ /dev/null @@ -1,82 +0,0 @@ - - Build Notes for HDDM Tools - Richard Jones - September 10, 2003 - -This document is intended as a quick-start guide for building and using -the hdds tools. For more information and for discussion of features and -bugs, please go to http://portal.gluex.org and look for "forums". - -1) Since you are reading this, you have already done the first step. - From your cvs source directory you typed: - - halld> cvs checkout hddm - -2) Download the xerces-c xml library from xml.apache.org and unpack - it somewhere on your system or GlueX working area. Getting the sources - and doing the build yourself (next step) makes sure that you have a - working installation for your configuration. - -3) Build the xerces xml library for your system. - - This is pretty simple. The instructions are found on the xml.apache.org - web site. There are just three steps: define XERCESCROOT to point to the - base directory where you unpacked xerces-c, then runConfigure and gmake. - The result is a shared library in the directory xerces-c/lib. - -4) Download and build the Xalan xml tool from xml.apache.org and unpack - it somewhere on your system or GlueX working area. If you have java - installed on your system, downloading Xalan-j is simple and does not - require a build step. Otherwise download Xalan-c and build it in a - similar way to the one described under step 3. - -5) Somewhere, perferrably at the top of your cvs source directory you - should make a script called setup that sets up some environment - variables that are needed to locate the XML libraries on your system. - What that looks like depends on your shell, but for tcsh it looks like: - - halld> cat setup - setenv CVS_RSH ssh - setenv CVSROOT @login1.jlab.org:/halld/cvsroot - setenv CERN - setenv CERN_VERSION - setenv CERN_ROOT ${CERN}/${CERN_VERSION} - setenv HALLD_ROOT - setenv PATH ${PATH}:${HALLD_ROOT}/bin.Linux:${CERN_ROOT}/bin - setenv XERCESCROOT - setenv LD_LIBRARY_PATH ${LD_LIBRARY_PATH}:/${XERCESCROOT/lib - setenv JAVAROOT - setenv XALANJROOT - setenv CLASSPATH=${XALANJROOT}/bin/xalan.jar - - For the bash or ksh shells you should use the export command instead of - setenv. You will need to source this file before every session, (or - invoke it with the . operator for ksh or bash). Note that the JAVAROOT - definition is not necessary if you do not intend to use java tools. - If you do use java, you should also make sure that the java command is - in your path, so that the command java is found. - -6) Check out the xstream package from the halld cvs repository and build - and install it in your build area in the usual way. - - halld> cd - halld> cvs checkout xstream - halld> make install -C xstream - -7) Now if everything was installed correctly, you can build the hddm tools - by going to the hddm directory you created in step 1 and doing make. - - halld> cd hddm - halld> make hddm-c hddm-xml xml-hddm - -8) The tools hddm-schema, schema-hddm and xml-xml are written in perl and - require Xerces-Perl from xml.apache.org to be installed if you want to - use them. Installation instructions are found at xml.apache.org. By - default these tools use the Xalan-j package. If you installed the c++ - version of Xalan instead, go into hddm-schema and schema-hddm and - comment out the line where xalan is started under java and remove the - comment from the line where xalan-c is invoked. - -9) For information about the design and use of the hddm tools, see the - documentation in index.html. For more information about the xstream - binary streams interface, see http://xstream.sourceforge.net . diff --git a/src/programs/Utilities/hddm/SConscript b/src/programs/Utilities/hddm/SConscript deleted file mode 100644 index d3a646d8b2..0000000000 --- a/src/programs/Utilities/hddm/SConscript +++ /dev/null @@ -1,68 +0,0 @@ - - -import sbms - -# get env object and clone it -Import('*') -top_env = env -env = env.Clone() - -# On Ubuntu 13.10, it was confirmed that turning on optimization -# when building hddm-cpp led to some things being omitted from the -# generated hddm_r.hpp file resulting in compile time errors. Turn -# off optimization here to prevent this. -opts = ['-O', '-O1', '-O2', '-O3', '-O4'] -cflags = env['CFLAGS'] -cxxflags = env['CXXFLAGS'] -for opt in opts: - if opt in cflags : cflags.remove(opt) - if opt in cxxflags: cxxflags.remove(opt) -env.Replace(CFLAGS=cflags, CXXFLAGS=cxxflags) - -sbms.AddXERCES(env) -sbms.Add_xstream(env) -sbms.AddROOT(env) - -# The llvm_clan_3.7.0 compiler on Linux_CentOS6-x86_64 needs -# -pthread on the link command to work. -if env['COMPILER']=='clang': - env.AppendUnique(LINKFLAGS=['-pthread']) - -progs = [] - -commonsrc = ['XString.cpp', 'XParsers.cpp', 'md5.c'] - -# The hddm-c and hddm-cpp utilities are needed to generate code -# for the HDDM library. See src/libraries/HDDM/SConscript for details. -hddmc = env.Program(target='hddm-c', source=['hddm-c.cpp' , commonsrc]) -hddmcpp = env.Program(target='hddm-cpp', source=['hddm-cpp.cpp', commonsrc]) -hddmpy = env.Program(target='hddm-py', source=['hddm-py.cpp', commonsrc]) -progs.append( hddmc ) -progs.append( hddmcpp ) -progs.append( hddmpy ) -progs.append( env.Program(target='xml-hddm', source=['xml-hddm.cpp', commonsrc]) ) -progs.append( env.Program(target='hddm-xml', source=['hddm-xml.cpp', commonsrc]) ) -progs.append( env.Program(target='hddm-root', source=['hddm-root.cpp', commonsrc]) ) -progs.append( env.Program(target='hddmcat', source=['hddmcat.cpp']) ) - -# (See src/libraries/HDDM/SConscript) -top_env.Requires(env['HDDMC_SRC'] , hddmc ) -top_env.Requires(env['HDDMCPP_SRC'], hddmcpp) -top_env.Requires(env['HDDMPY_SRC'] , hddmpy ) - -# Cleaning and installation are restricted to the directory -# scons was launched from or its descendents -CurrentDir = env.Dir('.').srcnode().abspath -if not CurrentDir.startswith(env.GetLaunchDir()): - # Not in launch directory. Tell scons no to clean these targets - env.NoClean(progs) -else: - # We're in launch directory (or descendent) schedule installation - - # Installation directories for executable and headers - includedir = env.subst('$INCDIR') - bindir = env.subst('$BINDIR') - - # Install targets - env.Install(bindir, ['hddm-schema', 'schema-hddm', 'xml-xml']) - env.Install(bindir, progs) diff --git a/src/programs/Utilities/hddm/VersionConfig.hpp b/src/programs/Utilities/hddm/VersionConfig.hpp deleted file mode 100644 index bbf3fbe959..0000000000 --- a/src/programs/Utilities/hddm/VersionConfig.hpp +++ /dev/null @@ -1,4 +0,0 @@ -#define HDDM_VERSION_MAJOR 1 -#define HDDM_VERSION_MINOR 0 - -#define HDF5_SUPPORT diff --git a/src/programs/Utilities/hddm/XParsers.cpp b/src/programs/Utilities/hddm/XParsers.cpp deleted file mode 100644 index 0ec3716990..0000000000 --- a/src/programs/Utilities/hddm/XParsers.cpp +++ /dev/null @@ -1,414 +0,0 @@ -/* - * XParsers: service classes to support parsing of xml domuments - * using standard DOM parsing tools - * - * Class implementation - * September 21, 2003 - * Richard Jones - * - * Bundled with the error handler classes are two utility functions: - * - * 1. parseInputDocument - parser implemented using the old-style - * XercesDOMParser interface based on the example code in - * $XERCESCROOT/samples/DOMPrint - * - * 2. buildDOMDocument - parser implemented using the w3c standard - * DOMBuilder interface based on the example code in - * $XERCESCROOT/samples/DOMCount - * - * Implementation Notes: - * --------------------- - * To prevent memory leaks, each of these parsers only retains a single - * document in memory at a time. The next call will destroy the DOM - * tree created on the previous call and return the resources to the - * pool. To prevent this behavior, call the parser with the argument - * perm=true, in which case the resulting DOMDocument will persist for - * the rest of the lifetime of the program. - * - * - * Modification Notes: - * -------------------- - * 11/7/2012 DL - * Added EntityResolver class to keep track of all of the XML files - * pulled in by the parser so an md5 checksum could be performed. - * results are written to a FORTRAN function called "md5geom" so the - * checksum can be accessed programatically. - * - * 6/12/2012 DL - * Xerces 3 has done away with the DOMBuilder API, yet retains - * the DOMParser. It seems the code using the routines in this file - * looked to the pre-processor variable OLD_STYLE_XERCES_PARSER to - * decide whether to call parseInputDocument() or buildDOMDocument(). - * The former being called if the variable was defined implying - * the former was likely to be deprecated. The simplest change that - * could be made to get this working with XERCES 3 was to turn the - * buildDOMDocument() routine into a wrapper for the parseInputDocument() - * routine. This is done below. - * - */ - -#include -using namespace std; - -#include -#include -#include - -#include "XParsers.hpp" -#include "XString.hpp" -#include "md5.h" - -std::string last_md5_checksum = ""; - -/* - * FIX_XERCES_getElementById_BUG does a store/load cycle at parsing time - * to fully instantiate entity references on the document tree. - * See xerces-c++ bug 12800 at http://nagoya.apache.org - */ -#define FIX_XERCES_getElementById_BUG true - -#define X(str) XString(str).unicode_str() -#define S(str) str.c_str() - -xercesc::DOMDocument* parseInputDocument(const XString& xmlFile, bool keep) -{ - static xercesc::XercesDOMParser* scratchParser=0; - xercesc::XercesDOMParser* parser; - if (keep) - { - parser = new xercesc::XercesDOMParser; - } - else if (scratchParser == 0) - { - parser = scratchParser = new xercesc::XercesDOMParser; - } - else - { - parser = scratchParser; - } - - MyEntityResolver myEntityResolver(xmlFile); - - parser->setValidationScheme(xercesc::XercesDOMParser::Val_Auto); - parser->setCreateEntityReferenceNodes(false); - parser->setValidationSchemaFullChecking(true); - parser->setDoNamespaces(true); - parser->setDoSchema(true); - parser->setEntityResolver(&myEntityResolver); - - MyOwnErrorHandler errorHandler; - parser->setErrorHandler(&errorHandler); - - try - { - parser->parse(xmlFile.c_str()); - myEntityResolver.GetMD5_checksum(); - } - catch (const xercesc::XMLException& toCatch) - { - std::cerr - << "\nparseInputDocument: Error during parsing: '" << xmlFile - << "'\n" << "Exception message is: \n" - << toCatch.getMessage() << "\n" << std::endl; - return 0; - } - catch (const xercesc::DOMException& toCatch) - { - std::cerr - << "\nXParsers: Error during parsing: '" << xmlFile << "'\n" - << "Exception message is: \n" - << toCatch.msg << "\n" << std::endl; - xercesc::XMLPlatformUtils::Terminate(); - return 0; - } - catch (...) - { - std::cerr - << "\nparseInputDocument: Unexpected exception during parsing: '" - << xmlFile << "'\n"; - xercesc::XMLPlatformUtils::Terminate(); - return 0; - } - - if (errorHandler.getSawErrors()) - { - std::cerr << "\nErrors occured, no output available\n" << std::endl; - return 0; - } - - return parser->getDocument(); -} - -xercesc::DOMDocument* buildDOMDocument(const XString& xmlFile, bool keep) -{ -return parseInputDocument(xmlFile, keep); -#if 0 // below no longer works in XERCES 3 - - xercesc::DOMImplementation *impl = - xercesc:: DOMImplementationRegistry::getDOMImplementation(X("LS")); - static xercesc::DOMBuilder* scratchBuilder=0; - xercesc::DOMBuilder* builder; - if (keep) - { - builder = ((xercesc::DOMImplementationLS*)impl)->createDOMBuilder( - xercesc::DOMImplementationLS::MODE_SYNCHRONOUS, 0); - } - else if (scratchBuilder == 0) - { - builder = scratchBuilder = ((xercesc::DOMImplementationLS*)impl)-> - createDOMBuilder(xercesc::DOMImplementationLS::MODE_SYNCHRONOUS, - 0); - } - else - { - builder = scratchBuilder; - } - XString tmpFileS = ".tmp-"+xmlFile.basename(); - - builder->setFeature(xercesc::XMLUni::fgDOMValidation, true); - builder->setFeature(xercesc::XMLUni::fgDOMNamespaces, true); - builder->setFeature(xercesc::XMLUni::fgDOMDatatypeNormalization, true); - builder->setFeature(xercesc::XMLUni::fgDOMEntities, false); - builder->setFeature(xercesc::XMLUni::fgXercesSchemaFullChecking, true); - builder->setFeature(xercesc::XMLUni::fgXercesSchema, true); - - MyDOMErrorHandler errHandler; - builder->setErrorHandler(&errHandler); - - xercesc::DOMDocument* doc = 0; - - try { - builder->resetDocumentPool(); - doc = builder->parseURI(xmlFile.c_str()); -#if defined FIX_XERCES_getElementById_BUG - xercesc::DOMWriter* writer = ((xercesc::DOMImplementationLS*)impl)-> - createDOMWriter(); - xercesc::LocalFileFormatTarget* lfft = - new xercesc::LocalFileFormatTarget(X(tmpFileS)); - writer->writeNode(lfft,*(doc->getDocumentElement())); - delete lfft; - delete writer; - builder->resetDocumentPool(); - doc = builder->parseURI(X(tmpFileS)); -#endif - } - catch (const xercesc::XMLException& toCatch) { - std::cout << "Exception message is: \n" << toCatch.getMessage() << "\n"; - return 0; - } - catch (const xercesc::DOMException& toCatch) { - std::cout << "Exception message is: \n" << toCatch.msg << "\n"; - return 0; - } - catch (...) { - std::cout << "Unexpected Exception \n" ; - return 0; - } - - if (errHandler.getSawErrors()) - { - std::cerr << "\nErrors occured, no output available\n" << std::endl; - return 0; - } - - return doc; -#endif // 0 -} - -MyOwnErrorHandler::MyOwnErrorHandler() : - fSawErrors(false) -{ -} - -MyOwnErrorHandler::~MyOwnErrorHandler() -{ -} - -// Overrides of the SAX ErrorHandler interface - -void MyOwnErrorHandler::error(const xercesc::SAXParseException& e) -{ - fSawErrors = true; - XString systemId(e.getSystemId()); - XString message(e.getMessage()); - std::cerr - << "\nparseInputDocument: Error at file " << S(systemId) - << ", line " << e.getLineNumber() - << ", char " << e.getColumnNumber() - << "\n Message: " << S(message) << std::endl; -} - -void MyOwnErrorHandler::fatalError(const xercesc::SAXParseException& e) -{ - fSawErrors = true; - XString systemId(e.getSystemId()); - XString message(e.getMessage()); - std::cerr - << "\nparseInputDocument: Fatal Error at file " << S(systemId) - << ", line " << e.getLineNumber() - << ", char " << e.getColumnNumber() - << "\n Message: " << S(message) << std::endl; -} - -void MyOwnErrorHandler::warning(const xercesc::SAXParseException& e) -{ - XString systemId(e.getSystemId()); - XString message(e.getMessage()); - std::cerr - << "\nparseInputDocument: Warning at file " << S(systemId) - << ", line " << e.getLineNumber() - << ", char " << e.getColumnNumber() - << "\n Message: " << S(message) << std::endl; -} - -void MyOwnErrorHandler::resetErrors() -{ -} - -MyDOMErrorHandler::MyDOMErrorHandler() : - - fSawErrors(false) -{ -} - -MyDOMErrorHandler::~MyDOMErrorHandler() -{ -} - -// MyDOMHandlers: Overrides of the DOM ErrorHandler interface - -bool MyDOMErrorHandler::handleError(const xercesc::DOMError& domError) -{ - fSawErrors = true; - if (domError.getSeverity() == xercesc::DOMError::DOM_SEVERITY_WARNING) - std::cerr << "\nWarning at file "; - else if (domError.getSeverity() == xercesc::DOMError::DOM_SEVERITY_ERROR) - std::cerr << "\nError at file "; - else - std::cerr << "\nFatal Error at file "; - - std::cerr - << XString(domError.getLocation()->getURI()).c_str() - << ", line " << domError.getLocation()->getLineNumber() - << ", char " << domError.getLocation()->getColumnNumber() - << "\n Message: " << XString(domError.getMessage()).c_str() - << std::endl; - - return true; -} - -void MyDOMErrorHandler::resetErrors() -{ - fSawErrors = false; -} - -//<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><> - -//---------------------------------- -// MyEntityResolver (constructor) -//---------------------------------- -MyEntityResolver::MyEntityResolver(const XString& xmlFile) -{ - xml_filenames.push_back(xmlFile); - - string fname = xmlFile; - size_t pos = fname.find_last_of('/'); - if(pos != string::npos){ - path = fname.substr(0,pos) + "/"; - } -} - -//---------------------------------- -// MyEntityResolver (destructor) -//---------------------------------- -MyEntityResolver::~MyEntityResolver() -{ - -} - -//---------------------------------- -// resolveEntity -//---------------------------------- -xercesc::InputSource* MyEntityResolver::resolveEntity(const XMLCh* const publicId, const XMLCh* const systemId) -{ - /// This method gets called from the xerces parser each time it - /// opens a file (except for the top-level file). For each of these, - /// record the name of the file being opened, then just return NULL - /// to have xerces handle opening the file in the normal way. - - // Do some backflips to get strings into std::string format - std::string my_publicId = ""; - std::string my_systemId = ""; - if(publicId){ - char *my_publicId_ptr = xercesc::XMLString::transcode(publicId); - my_publicId = my_publicId_ptr; - xercesc::XMLString::release(&my_publicId_ptr); - } - if(systemId){ - char *my_systemId_ptr = xercesc::XMLString::transcode(systemId); - my_systemId = my_systemId_ptr; - xercesc::XMLString::release(&my_systemId_ptr); - } - //std::cerr<<"publicId="< -#include -#include -#include - -#include -#include -#include - -#include "XString.hpp" - - -// Filled by parseInputDocument using MyEntityResolver class -extern std::string last_md5_checksum; - - -/* a simple error handler to install on XercesDOMParser */ - -class MyOwnErrorHandler : public xercesc::ErrorHandler -{ -public: - MyOwnErrorHandler(); - ~MyOwnErrorHandler(); - - bool getSawErrors() const; - -/* Implementation of the SAX ErrorHandler interface */ - void warning(const xercesc::SAXParseException& e); - void error(const xercesc::SAXParseException& e); - void fatalError(const xercesc::SAXParseException& e); - void resetErrors(); - -private : - MyOwnErrorHandler(const MyOwnErrorHandler&); - void operator=(const MyOwnErrorHandler&); - - bool fSawErrors; // flag to record that an error occurred -}; - -inline bool MyOwnErrorHandler::getSawErrors() const -{ - return fSawErrors; -} - -/* a simple error handler to install on DOMBuilder parser */ - -class MyDOMErrorHandler : public xercesc::DOMErrorHandler -{ -public: - MyDOMErrorHandler(); - ~MyDOMErrorHandler(); - - bool getSawErrors() const; - bool handleError(const xercesc::DOMError& domError); - void resetErrors(); - -private : - MyDOMErrorHandler(const MyDOMErrorHandler&); - void operator=(const MyDOMErrorHandler&); - bool fSawErrors; -}; - -inline bool MyDOMErrorHandler::getSawErrors() const -{ - return fSawErrors; -} - -// A simple entity resolver to keep track of files being -// included from the top-level XML file so a full MD5 sum -// can be made -class MyEntityResolver : public xercesc::EntityResolver -{ -public: - MyEntityResolver(const XString& xmlFile); - ~MyEntityResolver(); - - xercesc::InputSource* resolveEntity(const XMLCh* const publicId, const XMLCh* const systemId); - - std::vector GetXMLFilenames(void); - std::string GetMD5_checksum(void); - -private: - std::vector xml_filenames; - std::string path; -}; - -xercesc::DOMDocument* parseInputDocument(const XString& file, bool keep); -xercesc::DOMDocument* buildDOMDocument(const XString& file, bool keep); - -#endif diff --git a/src/programs/Utilities/hddm/XString.cpp b/src/programs/Utilities/hddm/XString.cpp deleted file mode 100644 index b190604171..0000000000 --- a/src/programs/Utilities/hddm/XString.cpp +++ /dev/null @@ -1,112 +0,0 @@ -/* - * XString: a simple class for translation between - * XMLCh strings and local coding - * - * Class implementation - * September 21, 2003 - * Richard Jones - */ - -#include "XString.hpp" -#include - -int dumper = 0; - -XString::XString(void) - : fStringCollection() -{} - -XString::XString(const XMLCh* const x) - : fStringCollection() -{ - if (x) - { - char* str = xercesc::XMLString::transcode(x); - fStringCollection.push_back(str); - (std::string&)*this = str; - } -} - -XString::XString(const char* const s) - : fStringCollection() -{ - if (s) - { - (std::string&)*this = s; - } -} - -XString::XString(const std::string& s) - : fStringCollection() -{ - if (s.size()) - { - (std::string&)*this = s; - } -} - -XString::XString(const XString& X) - : fStringCollection() -{ - (std::string&)*this = (std::string&)X; -} - -XString::~XString() -{ - std::list::iterator iter; - for (iter = fStringCollection.begin(); - iter != fStringCollection.end(); - ++iter) - { - delete [] *iter; - } -} - -XString& XString::operator=(const XString& X) -{ - (std::string&)*this = (std::string&)X; - return *this; -} - -const XMLCh* XString::unicode_str() -{ - XMLCh* ustr = xercesc::XMLString::transcode(this->c_str()); - fStringCollection.push_back((char*)ustr); - return ustr; -} - -const XString XString::basename() const -{ - XString s(*this); - size_type p = s.find_last_of("/"); - if (p != npos) - { - s = s.substr(p+1,s.size()); - } - return s; -} - -void XString::dump() -{ - std::cerr << ">>> XString dump:" << std::endl - << " >first the addresses: "; - std::list::iterator iter; - for (iter = fStringCollection.begin(); - iter != fStringCollection.end(); - ++iter) - { - void* x = *iter; - std::cerr << x << ","; - } - std::cerr << std::endl - << " >and now the strings: "; - for (iter = fStringCollection.begin(); - iter != fStringCollection.end(); - ++iter) - { - XMLCh* x = (XMLCh*)(*iter); - char* str = xercesc::XMLString::transcode(x); - std::cerr << str << ","; - } - std::cerr << std::endl; -} diff --git a/src/programs/Utilities/hddm/XString.hpp b/src/programs/Utilities/hddm/XString.hpp deleted file mode 100644 index f4567ef37a..0000000000 --- a/src/programs/Utilities/hddm/XString.hpp +++ /dev/null @@ -1,47 +0,0 @@ -/* - * XString: a simple class for translation between - * XMLCh strings and local coding - * - * Class definition - * September 21, 2003 - * Richard Jones - */ - -#ifndef SAW_XSTRING_DEF -#define SAW_XSTRING_DEF true - -#include -#include - -#include -#include - - -class XString: public std::string -{ - -/* The XString class extends the STL string class by adding - * unicode functionality required by the implementation of - * the Xerces xml library. - */ - public : - XString(void); - XString(const XMLCh* const x); - XString(const char* const s); - XString(const std::string& str); - XString(const XString& X); - ~XString(); - - const XString basename() const; // implements basename() from strings.h - const XMLCh* unicode_str(); // must modify the object because it - // has to keep track of memory usage. - - XString& operator=(const XString& src); - - private: - std::list fStringCollection; - - void dump(); -}; - -#endif diff --git a/src/programs/Utilities/hddm/event.xsd.test b/src/programs/Utilities/hddm/event.xsd.test deleted file mode 100644 index a58e4b9e54..0000000000 --- a/src/programs/Utilities/hddm/event.xsd.test +++ /dev/null @@ -1,620 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/programs/Utilities/hddm/exam1.xml b/src/programs/Utilities/hddm/exam1.xml deleted file mode 100644 index f6bd665b45..0000000000 --- a/src/programs/Utilities/hddm/exam1.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/src/programs/Utilities/hddm/exam2.c b/src/programs/Utilities/hddm/exam2.c deleted file mode 100644 index 582da72443..0000000000 --- a/src/programs/Utilities/hddm/exam2.c +++ /dev/null @@ -1,98 +0,0 @@ -#include - -int report(x_HDDM_t *tscript); - -int main() -{ - x_iostream_t* fp; - x_HDDM_t* tscript; - x_Student_t* student; - x_Enrolleds_t* enrolleds; - x_Courses_t* courses; - x_Result_t* result; - string_t name; - string_t grade; - string_t course; - int i; - - fp = init_x_HDDM("exam2.hddm"); - for (i=0;i<1000000;i++) { - - // first build the complete nodal structure for this record - tscript = make_x_HDDM(); - tscript->student = student = make_x_Student(); - student->enrolleds = enrolleds = make_x_Enrolleds(99); - enrolleds->mult = 1; - enrolleds->in[0].courses = courses = make_x_Courses(99); - courses->mult = 3; - courses->in[0].result = make_x_Result(); - courses->in[1].result = make_x_Result(); - courses->in[2].result = make_x_Result(); - - // now fill in the attribute data for this record - name = (char*)malloc(30); - strcpy(name,"Humphrey Gaston"); - student->name = name; - enrolleds->in[0].year = 2005; - enrolleds->in[0].semester = 2; - courses->in[0].credits = 3; - course = (char*)malloc(30); - courses->in[0].title = strcpy(course,"Beginning Russian"); - grade = (char*)malloc(5); - courses->in[0].result->grade = strcpy(grade,"A-"); - courses->in[0].result->Pass = 1; - courses->in[1].credits = 1; - course = (char*)malloc(30); - courses->in[1].title = strcpy(course,"Bohemian Poetry"); - grade = (char*)malloc(5); - courses->in[1].result->grade = strcpy(grade,"C"); - courses->in[1].result->Pass = 1; - courses->in[2].credits = 4; - course = (char*)malloc(30); - courses->in[2].title = strcpy(course,"Developmental Psychology"); - grade = (char*)malloc(5); - courses->in[2].result->grade = strcpy(grade,"B+"); - courses->in[2].result->Pass = 1; - - // now open a file and write this one record into it - flush_x_HDDM(tscript,fp); - } - close_x_HDDM(fp); - - // try reading it back in from the output file just written - fp = open_x_HDDM("exam2.hddm"); - int count=0; - while ((tscript = read_x_HDDM(fp)) != 0) { - if (count/100000*100000 == count) { - printf("event %d\n", count); - report(tscript); - } - ++count; - } - printf("finished after %d events read.\n", count); - return 0; -} - -int report(x_HDDM_t *tscript) -{ - x_Student_t* student = tscript->student; - x_Enrolleds_t* enrolleds = student->enrolleds; - x_Courses_t* courses = enrolleds->in[0].courses; - int total_courses = courses->mult; - int total_enrolled = 0; - int total_credits = 0; - int total_passed = 0; - int i; - for (i=0;iin[i].result->Pass) { - if (enrolleds->in[0].year > 1992) { - total_credits += courses->in[i].credits; - } - ++total_passed; - } - } - printf("%s enrolled in %d courses and passed %d of them,\n", - student->name, total_courses, total_passed); - printf("earning a total of %d credits.\n", total_credits); - return 0; -} diff --git a/src/programs/Utilities/hddm/exam2.cpp b/src/programs/Utilities/hddm/exam2.cpp deleted file mode 100644 index f0487752e8..0000000000 --- a/src/programs/Utilities/hddm/exam2.cpp +++ /dev/null @@ -1,80 +0,0 @@ -#include -#include "hddm_x.hpp" - -int report(hddm_x::HDDM &xrec); - -int main() -{ - hddm_x::HDDM xrec; - std::ofstream ofs("exam2.hddm"); - hddm_x::ostream *ostr = new hddm_x::ostream(ofs); - - //ostr->setCompression(hddm_x::k_z_compression); - - for (int n=0; n<1000000; ++n) { - hddm_x::StudentList student = xrec.addStudents(); - student().setName("Humphrey Gaston"); - hddm_x::EnrolledList enrolled = student().addEnrolleds(); - enrolled().setYear(2005); - enrolled().setSemester(2); - hddm_x::CourseList course = enrolled().addCourses(3); - course(0).setCredits(3); - course(0).setTitle("Beginning Russian"); - course(0).addResults(); - course(0).getResult().setGrade("A-"); - course(0).getResult().setPass(true); - course(1).setCredits(1); - course(1).setTitle("Bohemian Poetry"); - course(1).addResults(); - course(1).getResult().setGrade("C"); - course(1).getResult().setPass(1); - course(2).setCredits(4); - course(2).setTitle("Developmental Psychology"); - course(2).addResults(); - course(2).getResult().setGrade("B+"); - course(2).getResult().setPass(true); - *ostr << xrec; - xrec.clear(); - } - delete ostr; - ofs.close(); - - // try reading it back in from the output file just written - std::ifstream ifs("exam2.hddm"); - hddm_x::istream istr(ifs); - int count=0; - while (ifs.good()) { - istr >> xrec; - if (count/100000*100000 == count) { - std::cout << "event " << count << std::endl; - report(xrec); - } - ++count; - } - std::cout << "finished after " << count << " events read." << std::endl; - return 0; -} - -int report(hddm_x::HDDM &xrec) -{ - hddm_x::CourseList courses = xrec.getCourses(); - int total_courses = courses.size(); - int total_enrolled = 0; - int total_credits = 0; - int total_passed = 0; - hddm_x::CourseList::iterator iter; - for (iter = courses.begin(); iter != courses.end(); ++iter) { - if (iter->getResult().getPass()) { - if (iter->getYear() > 1992) { - total_credits += iter->getCredits(); - } - ++total_passed; - } - } - std::cout << courses().getName() << " enrolled in " - << total_courses << " courses " - << "and passed " << total_passed << " of them, " << std::endl - << "earning a total of " << total_credits - << " credits." << std::endl; - return 0; -} diff --git a/src/programs/Utilities/hddm/exam2.py b/src/programs/Utilities/hddm/exam2.py deleted file mode 100644 index 0bf965b777..0000000000 --- a/src/programs/Utilities/hddm/exam2.py +++ /dev/null @@ -1,57 +0,0 @@ -import hddm_x -import sys - -def report(xrec): - courses = xrec.getCourses() - total_courses = len(courses) - total_enrolled = 0 - total_credits = 0 - total_passed = 0 - for course in courses: - if course.getResult().Pass: - if course.year > 1992: - total_credits += course.credits - total_passed += 1 - print courses[0].name, "enrolled in", total_courses, "courses", \ - "and passed", total_passed, "of them," - print "earning a total of", total_credits, "credits." - -ostr = hddm_x.ostream("exam2.hddm") -#ostr.compression = hddm_x.k_z_compression - -for n in range(0, 1000000): - xrec = hddm_x.HDDM() - student = xrec.addStudents() - student[0].name = "Humphrey Gaston" - enrolled = student[0].addEnrolleds() - enrolled[0].year = 2005 - enrolled[0].semester = 2 - course = enrolled[0].addCourses(3) - course[0].credits = 3 - course[0].title = "Beginning Russian" - course[0].addResults() - course[0].getResult().grade = "A-" - course[0].getResult().Pass = True - course[1].credits = 1 - course[1].title = "Bohemian Poetry" - course[1].addResults() - course[1].getResult().grade = "C" - course[1].getResult().Pass = 1 - course[2].credits = 4 - course[2].title = "Developmental Psychology" - course[2].addResults() - course[2].getResult().grade = "B+" - course[2].getResult().Pass = True - ostr.write(xrec) -del ostr - -# try reading it back in from the output file just written - -istr = hddm_x.istream("exam2.hddm") -count=0 -for rec in istr: - if count % 100000 == 0: - print "event", count - report(rec) - count += 1 -print "finished after", count, "events read." diff --git a/src/programs/Utilities/hddm/exam2.xml b/src/programs/Utilities/hddm/exam2.xml deleted file mode 100644 index 48fd0c8510..0000000000 --- a/src/programs/Utilities/hddm/exam2.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/src/programs/Utilities/hddm/hddm-c.cpp b/src/programs/Utilities/hddm/hddm-c.cpp deleted file mode 100644 index fa8fc611b7..0000000000 --- a/src/programs/Utilities/hddm/hddm-c.cpp +++ /dev/null @@ -1,2162 +0,0 @@ -/* - * hddm-c : tool that reads in a HDDM document (Hall D Data Model) - * and writes a c header file that embodies the model in - * c structures. It also generates an input/output pair - * of functions to translate the model between the memory - * representation and a default binary representation that - * is suitable for passing over a pipe or storing on disk. - * - * Version 1.3 - Richard Jones, February 10, 2021. - * - Modified to be able to accept a hddm file as a valid hddm template. - * This simplifies the documentation by eliminating the false distinction - * between a hddm template and the text header that appears at the top of - * every hddm file. It also gets rid of the unnecessary step of having - * to delete the binary data following the header in a hddm file before - * it can be used as a template. - * - * Version 1.2 - Richard Jones, December 2005. - * - Updated code to use STL strings and vectors instead of old c-style - * pre-allocated arrays and strXXX functions. - * - Moved functions into classes grouped by function for better clarity. - * - * Version 1.1 - Richard Jones, September 2003. - * - Updated code to work with the new DOM-2 implementation Xerces-c - * from apache.org. Significant changes have taken place in the API - * since DOM-1. - * - Added support for new types "long" (int64), "string" (char arrays of - * arbitrary length), and "anyURI" (special case of string). - * - Switched from native encoding to the use of the XDR library to make - * hddm files machine-independent. - * - * Original version - Richard Jones, May 25 2001. - * - * - * Programmer's Notes: - * ------------------- - * 1. The HDDM specification describes data files using xml. For - * information about the contents and structure of HDDM documents - * see the web page that describes the data model. - * - * 2. Access by hddm-c to the xml source is through the industry- - * standard Document Object Model (DOM) interface. - * - * 3. The code has been tested with the xerces-c DOM implementation from - * Apache, and is intended to be used with the xerces-c library. - * - * 4. Output is sent to .h and .c where is - * by default "hddm" and can be changed with the -o option. - * - * 5. As a by-product of using the DOM parser to access the xml source, - * hddm-c verifies the source for well-formedness. Therefore it may - * also be used to check the xml data model document. - * - * - * Implementation Notes: - * --------------------- - * 1. The binary stream consists of the hddm data model in the form - * of a well-formed xml header, followed by binary data. - * - * 2. The binary data consist of a sequence of event records, which are - * repetitions of the basic data model in a serial representation. - * - * 3. Each element is output to the stream in the order it appears in - * the data model, prefixed by an exclusive byte count. - * - * 4. Any c application compiled with the hddm header file that is - * generated by hddm-c is able to read any hddm binary file that - * was written using the same hddm class, ie. the - * document tags must be a non-colliding set (see matching rules). - * - * 5. The input/output features of the c library produced by hddm-c - * are implemented using the xdr binary i/o library written originally - * by Sun Microsystems. This library provides basic serialization/ - * deserialization of binary data using network byte-ordering - * (RFC-1832) and is a part of many unix installations. - */ - -#define MAX_POPLIST_LENGTH 99 - -#include "XString.hpp" -#include "XParsers.hpp" - -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -#define X(str) XString(str).unicode_str() -#define S(str) str.c_str() - -using namespace xercesc; - -XString classPrefix; - -void usage() -{ - std::cerr - << "\nUsage:\n" - << " hddm-c [-v | -o ] {HDDM file}\n\n" - << "Options:\n" - << " -v validate only\n" - << " -o write to .h, .c" - << std::endl; -} - -class XtString : public XString -{ -/* XString class with a few extra methods for creating type - * strings that are useful in creating c structures - */ - public: - XtString() {}; - XtString(const char* s): XString(s) {}; - XtString(const XMLCh* p): XString(p) {}; - XtString(const std::string& s): XString(s) {}; - XtString(const XString& x): XString(x) {}; - XtString(const XtString& t): XString((XString&)t) {}; - - XtString plural(); - XtString simpleType(); - XtString listType(); -}; - -class CodeBuilder -{ -/* The methods in this class are used to write the c code that - * implements the hddm structures i/o library. - */ - public: - std::ofstream hFile; - std::ofstream cFile; - - CodeBuilder() {}; - ~CodeBuilder() {}; - - void checkConsistency(DOMElement* el, DOMElement* elref); - void writeHeader(DOMElement* el); - void constructGroup(DOMElement* el); - void constructConstructors(); - void constructUnpackers(); - void constructReadFunc(DOMElement* topEl); - void constructSkipFunc(); - void constructPackers(); - void constructFlushFunc(DOMElement* el); - void writeMatcher(); - void constructOpenFunc(DOMElement* el); - void constructInitFunc(DOMElement* el); - void constructCloseFunc(DOMElement* el); - void constructDocument(DOMElement* el); - - private: - std::vector tagList; -}; - - -int main(int argC, char* argV[]) -{ - try - { - XMLPlatformUtils::Initialize(); - } - catch (const XMLException* toCatch) - { - XtString msg(toCatch->getMessage()); - std::cerr - << "hddm-c: Error during initialization! :\n" - << msg << std::endl; - return 1; - } - - if (argC < 2) - { - usage(); - return 1; - } - else if ((argC == 2) && (strcmp(argV[1], "-?") == 0)) - { - usage(); - return 2; - } - - XtString xmlFile; - XtString hFilename; - bool verifyOnly = false; - int argInd; - for (argInd = 1; argInd < argC; argInd++) - { - if (argV[argInd][0] != '-') - { - break; - } - if (strcmp(argV[argInd],"-v") == 0) - { - verifyOnly = true; - } - else if (strcmp(argV[argInd],"-o") == 0) - { - hFilename = XtString(argV[++argInd]); - } - else - { - std::cerr - << "Unknown option \'" << argV[argInd] - << "\', ignoring it\n" << std::endl; - } - } - - if (argInd != argC - 1) - { - usage(); - return 1; - } - xmlFile = XtString(argV[argInd]); - std::ifstream ifs(xmlFile.c_str()); - if (!ifs.good()) - { - std::cerr - << "hddm-c: Error opening hddm template " << xmlFile << std::endl; - exit(1); - } - std::ostringstream tmpFileStr; - tmpFileStr << "tmp" << getpid(); - std::ofstream ofs(tmpFileStr.str().c_str()); - if (! ofs.is_open()) - { - std::cerr - << "hddm-c: Error opening temp file " << tmpFileStr.str() << std::endl; - exit(2); - } - - XString xmlPreamble("\n"); - XString xmlHeader; - XString line; - while (getline(ifs,line)) - { - if (line.find("") != line.npos) - { - xmlPreamble += line + "\n"; - } - else if (line.size() == 0) - { - xmlPreamble += "\n"; - } - else if (line.find("") - { - break; - } - } - ofs.close(); - ifs.close(); - -#if defined OLD_STYLE_XERCES_PARSER - DOMDocument* document = parseInputDocument(tmpFileStr.str().c_str(),false); -#else - DOMDocument* document = buildDOMDocument(tmpFileStr.str().c_str(),false); -#endif - if (document == 0) - { - std::cerr - << "hddm-c : Error parsing HDDM document, " - << "cannot continue" << std::endl; - return 1; - } - unlink(tmpFileStr.str().c_str()); - - DOMElement* rootEl = document->getDocumentElement(); - XtString rootS(rootEl->getTagName()); - if (rootS != "HDDM") - { - std::cerr - << "hddm-c error: root element of input document is " - << "\"" << rootS << "\", expected \"HDDM\"" - << std::endl; - return 1; - } - - XtString classS(rootEl->getAttribute(X("class"))); - classPrefix = classS; - - XtString hname; - if (verifyOnly) - { - hname = "/dev/null"; - } - else if (hFilename.size()) - { - hname = hFilename + ".h"; - } - else - { - hname = "hddm_" + classPrefix + ".h"; - } - - CodeBuilder builder; - builder.hFile.open(hname.c_str()); - if (! builder.hFile.is_open()) - { - std::cerr - << "hddm-c error: unable to open output file " - << hname << std::endl; - return 1; - } - - XtString cname; - if (verifyOnly) - { - cname = "/dev/null"; - } - else if (hFilename.size()) - { - cname = hFilename + ".c"; - } - else - { - cname = "hddm_" + classPrefix + ".c"; - } - - builder.cFile.open(cname.c_str()); - if (! builder.cFile.is_open()) - { - std::cerr - << "hddm-c error: unable to open output file " - << cname << std::endl; - return 1; - } - - builder.hFile - << "/*" << std::endl - << " * " << hname << " - DO NOT EDIT THIS FILE" << std::endl - << " *" << std::endl - << " * This file was generated automatically by hddm-c" - << " from the file" << std::endl - << " * " << xmlFile << std::endl - << std::endl - << " * This header file defines the c structures that" - << " hold the data" << std::endl - << " * described in the data model" - << " (from " << xmlFile << "). " << std::endl - << " *" << std::endl - << " * The hddm data model tool set was written by" << std::endl - << " * Richard Jones, University of Connecticut." << std::endl - << " *" << std::endl - << " * For more information see the documentation at" << std::endl - << " * http://github.com/rjones30/HDDM" << std::endl - << " *" << std::endl - << " */" << std::endl - << std::endl; - - builder.cFile - << "/*" << std::endl - << " * " << cname << " - DO NOT EDIT THIS FILE" << std::endl - << " *" << std::endl - << " * This file was generated automatically by hddm-c" - << " from the file" << std::endl - << " * " << xmlFile << std::endl - << std::endl - << " * This c file contains the i/o interface to" - << " the c structures" << std::endl - << " * described in the data model" - << " (from " << xmlFile << "). " << std::endl - << " *" << std::endl - << " * The hddm data model tool set was written by" << std::endl - << " * Richard Jones, University of Connecticut." << std::endl - << " *" << std::endl - << " * For more information see the documentation at" << std::endl - << " * http://github.com/rjones30/HDDM" << std::endl - << " */" << std::endl - << std::endl; - - builder.hFile - << "#include " << std::endl - << "#include " << std::endl - << "#include " << std::endl - << "#include " << std::endl - << "#include " << std::endl - << "#include " << std::endl - << "#include " << std::endl - << std::endl - << "typedef char* string_t; " - << "// use this alias for string-valued attributes" << std::endl - << std::endl - << "/* Note to users: The option MALLOC_FREE_WITH_MEMCHECK" << std::endl - << " * was created for debugging this hddm library, but it" << std::endl - << " * is also useful for finding memory leaks in user" << std::endl - << " * code. To use it, replace malloc(n) everywhere in" << std::endl - << " * your code with MALLOC(n,\"some descriptive string\")" << std::endl - << " * and free(p) with FREE(p) and include this header" << std::endl - << " * and compile with -DMALLOC_FREE_WITH_MEMCHECK set." << std::endl - << " * Any attempt to malloc memory already malloc'ed or" << std::endl - << " * to free memory that has not yet been malloc'ed is" << std::endl - << " * immediately flagged with an error message. A call" << std::endl - << " * to checkpoint() anywhere in the user code reports" << std::endl - << " * any memory that has been malloc'ed not freed." << std::endl - << " */" << std::endl - << "#if defined MALLOC_FREE_WITH_MEMCHECK" << std::endl - << "# include " << std::endl - << "# define MALLOC(N,S) (checkin(malloc(N),S))" << std::endl - << "# define CHECK(P,S) (checkin(P,S))" << std::endl - << "# define FREE(P) (checkout(P),free(P))" << std::endl - << "#else" << std::endl - << "# define MALLOC(N,S) malloc(N)" << std::endl - << "# define CHECK(P,S) assert(1 == 1)" << std::endl - << "# define FREE(P) free(P)" << std::endl - << "#endif" << std::endl; - - builder.cFile - << "int hddm_" + classPrefix + "_nullTarget=0;" << std::endl - << "#define HDDM_NULL (void*)&hddm_" + classPrefix + "_nullTarget" - << std::endl - << std::endl - << "#include \"" << hname << "\"" << std::endl - << "#include " << std::endl - << std::endl - << "int hddm_" + classPrefix + "_buffersize = 1000000;" - << std::endl - << "int hddm_" + classPrefix + "_stringsize = 1000000;" - << std::endl - << "int hddm_" + classPrefix + "_headersize = 1000000;" - << std::endl - << std::endl - << "void set_" + classPrefix + "_HDDM_buffersize(int size)" - << std::endl - << "{" << std::endl - << " hddm_" + classPrefix + "_buffersize = size;" << std::endl - << "}" << std::endl - << std::endl - << "int get_" + classPrefix + "_HDDM_buffersize()" << std::endl - << "{" << std::endl - << " return hddm_" + classPrefix + "_buffersize;" << std::endl - << "}" << std::endl - << std::endl - << "void set_" + classPrefix + "_HDDM_stringsize(int size)" - << std::endl - << "{" << std::endl - << " hddm_" + classPrefix + "_stringsize = size;" << std::endl - << "}" << std::endl - << std::endl - << "int get_" + classPrefix + "_HDDM_stringsize()" << std::endl - << "{" << std::endl - << " return hddm_" + classPrefix + "_stringsize;" << std::endl - << "}" << std::endl - << std::endl - << "void set_" + classPrefix + "_HDDM_headersize(int size)" - << std::endl - << "{" << std::endl - << " hddm_" + classPrefix + "_headersize = size;" << std::endl - << "}" << std::endl - << std::endl - << "int get_" + classPrefix + "_HDDM_headersize()" << std::endl - << "{" << std::endl - << " return hddm_" + classPrefix + "_headersize;" << std::endl - << "}" << std::endl - << std::endl - << "static int XDRerror()" << std::endl - << "{" << std::endl - << " fprintf(stderr,\"hddm xdr library error - \"" << std::endl - << " \"data buffering has failed for some reason,\"" << std::endl - << " \" probably buffer overflow.\\n\"" << std::endl - << " \"Try increasing the size of the hddm i/o\"" << std::endl - << " \" buffers or maximum string size.\\n\");" << std::endl - << " exit(9);" << std::endl - << " return 0;" << std::endl - << "}" << std::endl; - - builder.constructGroup(rootEl); - - builder.hFile << std::endl - << "#ifdef __cplusplus" << std::endl - << "extern \"C\" {" << std::endl - << "#endif" << std::endl; - builder.constructConstructors(); - builder.hFile << std::endl - << "#ifdef __cplusplus" << std::endl - << "}" << std::endl - << "#endif" << std::endl; - - builder.hFile << std::endl - << "#ifndef " << classPrefix << "_DocumentString" << std::endl - << "#define " << classPrefix << "_DocumentString" << std::endl - << std::endl - << "extern " - << "char HDDM_" << classPrefix << "_DocumentString[];" << std::endl - << std::endl - << "#ifdef INLINE_PREPEND_UNDERSCORES" << std::endl - << "#define inline __inline" << std::endl - << "#endif" << std::endl - << std::endl - << "#endif /* " << classPrefix << "_DocumentString */" << std::endl; - - builder.cFile << std::endl - << "char HDDM_" << classPrefix << "_DocumentString[]" - << " = " << std::endl; - builder.constructDocument(rootEl); - builder.cFile << ";" << std::endl; - - builder.hFile << std::endl - << "#ifndef HDDM_STREAM_INPUT" << std::endl - << "#define HDDM_STREAM_INPUT -91" << std::endl - << "#define HDDM_STREAM_OUTPUT -92" << std::endl - << std::endl - << "struct popNode_s {" << std::endl - << " void* (*unpacker)(XDR*, struct popNode_s*);" << std::endl - << " int inParent;" << std::endl - << " int popListLength;" << std::endl - << " struct popNode_s* popList[" - << MAX_POPLIST_LENGTH << "];" << std::endl - << "};" << std::endl - << "typedef struct popNode_s popNode;" << std::endl - << std::endl - << "typedef struct {" << std::endl - << " FILE* fd;" << std::endl - << " int iomode;" << std::endl - << " int lerrno;" << std::endl - << " char* filename;" << std::endl - << " XDR* xdrs;" << std::endl - << " popNode* popTop;" << std::endl - << " char* iobuffer;" << std::endl - << " int iobuffer_size;" << std::endl - << "} " << classPrefix << "_iostream_t;" << std::endl - << std::endl - << "#endif /* HDDM_STREAM_INPUT */" << std::endl; - - builder.cFile << std::endl - << "#ifndef _FILE_OFFSET_BITS" << std::endl - << "# define _FILE_OFFSET_BITS 64" << std::endl - << "#endif" << std::endl - << std::endl - << "static off_t xdr_getpos64(XDR *xdrs)" << std::endl - << "{" << std::endl - << " if (xdrs->x_base == 0) {" << std::endl - << " return ftello((FILE *)xdrs->x_private);" << std::endl - << " }" << std::endl - << " off_t pos = xdr_getpos(xdrs);" << std::endl - << " return pos;" << std::endl - << "}" << std::endl - << std::endl - << "static bool_t xdr_setpos64(XDR *xdrs, off_t pos) " << std::endl - << "{ " << std::endl - << " if (xdrs->x_base == 0) {" << std::endl - << " return ((fseeko((FILE *)xdrs->x_private, pos, 0) < 0)? FALSE : TRUE);" - << std::endl - << " }" << std::endl - << " return xdr_setpos(xdrs,pos);" << std::endl - << "}" << std::endl; - - builder.constructUnpackers(); - - builder.hFile << std::endl - << "#ifdef __cplusplus" << std::endl - << "extern \"C\" {" << std::endl - << "#endif" << std::endl - << std::endl - << "void set_" + classPrefix + "_HDDM_buffersize(int size);" - << std::endl - << "int get_" + classPrefix + "_HDDM_buffersize();" << std::endl - << "void set_" + classPrefix + "_HDDM_stringsize(int size);" - << std::endl - << "int get_" + classPrefix + "_HDDM_stringsize();" << std::endl - << "void set_" + classPrefix + "_HDDM_headersize(int size);" - << std::endl - << "int get_" + classPrefix + "_HDDM_headersize();" << std::endl; - builder.constructReadFunc(rootEl); - builder.constructSkipFunc(); - builder.constructFlushFunc(rootEl); - builder.constructOpenFunc(rootEl); - builder.constructInitFunc(rootEl); - builder.constructCloseFunc(rootEl); - builder.hFile << std::endl - << "#ifdef __cplusplus" << std::endl - << "}" << std::endl - << "#endif" << std::endl - << std::endl - << "#if !defined HDDM_NULL" << std::endl - << "extern int hddm_" + classPrefix + "_nullTarget;" << std::endl - << "# define HDDM_NULL (void*)&hddm_" + classPrefix + "_nullTarget" - << std::endl - << "#endif" << std::endl; - - XMLPlatformUtils::Terminate(); - return 0; -} - -XtString XtString::plural() -{ - XtString p(*this); - XtString::size_type len = p.size(); - if (len > 3 && p.substr(len-3,3) == "tum") - { - p.replace(len-3,3,"ta"); - } - else if (len > 1 && p.substr(len-3,3) == "ies") - { - p.replace(len-3,3,"iesList"); - } - else if (len > 2 && p.substr(len-2,2) == "ex") - { - p.replace(len-2,2,"ices"); - } - else if (len > 2 && p.substr(len-2,2) == "sh") - { - p.replace(len-2,2,"shes"); - } - else if (len > 1 && p.substr(len-1,1) == "s") - { - p.replace(len-1,1,"ses"); - } - else if (len > 1) - { - p += "s"; - } - return p; -} - -/* Map from tag name to name of the corresponding c-structure - * for the case of simple tags (those that do not repeat) - */ -XtString XtString::simpleType() -{ - XtString p(*this); - p[0] = toupper(p[0]); - p = classPrefix + "_" + p + "_t"; - return p; -} - -/* Map from tag name to name of the corresponding c-structure - * for the case of list tags (those that may repeat) - */ -XtString XtString::listType() -{ - XtString r = plural(); - r[0] = toupper(r[0]); - r = classPrefix + "_" + r + "_t"; - return r; -} - -/* Verify that the tag group under this element does not collide - * with existing tag group elref, otherwise exit with fatal error - */ -void CodeBuilder::checkConsistency(DOMElement* el, DOMElement* elref) -{ - XtString tagS(el->getTagName()); - if (el->getParentNode() == elref->getParentNode()) - { - std::cerr - << "hddm-c error: tag " << "\"" << tagS - << "\" is duplicated within one context in xml document." - << std::endl; - exit(1); - } - - DOMNamedNodeMap* oldAttr = elref->getAttributes(); - DOMNamedNodeMap* newAttr = el->getAttributes(); - unsigned int listLength = oldAttr->getLength(); - for (unsigned int n = 0; n < listLength; n++) - { - XtString nameS(oldAttr->item(n)->getNodeName()); - XtString oldS(elref->getAttribute(X(nameS))); - XtString newS(el->getAttribute(X(nameS))); - if (nameS == "minOccurs") - { - continue; - } - else if (nameS == "maxOccurs") - { - int maxold = (oldS == "unbounded")? INT_MAX : atoi(S(oldS)); - int maxnew = (newS == "unbounded")? INT_MAX : atoi(S(newS)); - if ((maxold < 2 && maxnew > 1) || (maxold > 1 && maxnew < 2)) - { - std::cerr - << "hddm-c error: inconsistent maxOccurs usage by tag " - << "\"" << tagS << "\" in xml document." << std::endl; - exit(1); - } - } - else if (newS != oldS) - { - std::cerr - << "hddm-c error: inconsistent usage of attribute " - << "\"" << nameS << "\" in tag " - << "\"" << tagS << "\" in xml document." << std::endl; - exit(1); - } - } - listLength = newAttr->getLength(); - for (unsigned int n = 0; n < listLength; n++) - { - XtString nameS(newAttr->item(n)->getNodeName()); - XtString oldS(elref->getAttribute(X(nameS))); - XtString newS(el->getAttribute(X(nameS))); - if (nameS == "minOccurs") - { - continue; - } - else if (nameS == "maxOccurs") - { - int maxold = (oldS == "unbounded")? INT_MAX : atoi(S(oldS)); - int maxnew = (newS == "unbounded")? INT_MAX : atoi(S(newS)); - if ((maxold < 2 && maxnew > 1) || (maxold > 1 && maxnew < 2)) - { - std::cerr - << "hddm-c error: inconsistent maxOccurs usage by tag " - << "\"" << tagS << "\" in xml document." << std::endl; - exit(1); - } - } - else if (newS != oldS) - { - std::cerr - << "hddm-c error: inconsistent usage of attribute " - << "\"" << nameS << "\" in tag " - << "\"" << tagS << "\" in xml document." << std::endl; - exit(1); - } - } - DOMNodeList* oldList = elref->getChildNodes(); - DOMNodeList* newList = el->getChildNodes(); - listLength = oldList->getLength(); - if (newList->getLength() != listLength) - { - std::cerr - << "hddm-c error: inconsistent usage of tag " - << "\"" << tagS << "\" in xml document." << std::endl; - exit(1); - } - for (unsigned int n = 0; n < listLength; n++) - { - DOMNode* cont = oldList->item(n); - XtString nameS(cont->getNodeName()); - short type = cont->getNodeType(); - if (type == DOMNode::ELEMENT_NODE) - { - DOMNodeList* contList = el->getElementsByTagName(X(nameS)); - if (contList->getLength() != 1) - { - std::cerr - << "hddm-c error: inconsistent usage of tag " - << "\"" << tagS << "\" in xml document." << std::endl; - exit(1); - } - } - } -} - -/* Write declaration of c-structure for this tag to c-header file */ - -void CodeBuilder::writeHeader(DOMElement* el) -{ - XtString tagS(el->getTagName()); - XtString ctypeDef = tagS.simpleType(); - hFile << std::endl - << "#ifndef SAW_" << ctypeDef << std::endl - << "#define SAW_" << ctypeDef << std::endl - << std::endl - << "typedef struct {" << std::endl; - - DOMNamedNodeMap* varList = el->getAttributes(); - int varCount = varList->getLength(); - for (int v = 0; v < varCount; v++) - { - DOMNode* var = varList->item(v); - XtString typeS(var->getNodeValue()); - XtString nameS(var->getNodeName()); - if (typeS == "int") - { - hFile << " int32_t " << nameS << ";" << std::endl; - } - else if (typeS == "long") - { - hFile << " int64_t " << nameS << ";" << std::endl; - } - else if (typeS == "float") - { - hFile << " float " << nameS << ";" << std::endl; - } - else if (typeS == "double") - { - hFile << " double " << nameS << ";" << std::endl; - } - else if (typeS == "boolean") - { - hFile << " bool_t " << nameS << ";" << std::endl; - } - else if (typeS == "string") - { - hFile << " string_t " << nameS << ";" << std::endl; - } - else if (typeS == "anyURI") - { - hFile << " string_t " << nameS << ";" << std::endl; - } - else if (typeS == "Particle_t") - { - hFile << " Particle_t " << nameS << ";" << std::endl; - } - else - { - /* ignore attributes with unrecognized values */ - } - } - - DOMNodeList* contList = el->getChildNodes(); - int contLength = contList->getLength(); - for (int c = 0; c < contLength; c++) - { - DOMNode* cont = contList->item(c); - XtString nameS(cont->getNodeName()); - short type = cont->getNodeType(); - if (type == DOMNode::ELEMENT_NODE) - { - DOMElement* contEl = (DOMElement*) cont; - XtString repS(contEl->getAttribute(X("maxOccurs"))); - int rep = (repS == "unbounded")? INT_MAX : atoi(S(repS)); - XtString ctypeRef = (rep > 1) ? nameS.listType() - : nameS.simpleType(); - XtString::size_type clen = ctypeRef.size(); - - hFile << " " << ctypeRef << "* "; - for (int i = 0; i < 19-(int)clen; i++) - { - hFile << " "; - } - hFile << ((rep > 1) ? nameS.plural() : nameS) << ";" << std::endl; - } - } - - hFile << "} " << ctypeDef << ";" << std::endl; - - XtString repS(el->getAttribute(X("maxOccurs"))); - int rep = (repS == "unbounded")? INT_MAX : atoi(S(repS)); - if (rep > 1) - { - XtString ctypeRef = tagS.listType(); - hFile << std::endl << "typedef struct {" << std::endl - << " unsigned int mult;" << std::endl - << " " << ctypeDef << " in[1];" << std::endl - << "} " << ctypeRef << ";" << std::endl; - } - - hFile << "#endif /* " << ctypeDef << " */" << std::endl; -} - -/* Generate c-structure declarations for this tag and its descendants; - * this function calls itself recursively - */ -void CodeBuilder::constructGroup(DOMElement* el) -{ - XtString tagS(el->getTagName()); - std::vector::iterator iter; - for (iter = tagList.begin(); iter != tagList.end(); iter++) - { - XtString targS((*iter)->getTagName()); - if (tagS == targS) - { - checkConsistency(el,*iter); - return; - } - } - - tagList.push_back(el); - - DOMNodeList* contList = el->getChildNodes(); - int contLength = contList->getLength(); - for (int c = 0; c < contLength; c++) - { - DOMNode* cont = contList->item(c); - short type = cont->getNodeType(); - if (type == DOMNode::ELEMENT_NODE) - { - DOMElement* contEl = (DOMElement*) cont; - constructGroup(contEl); - } - } - - writeHeader(el); -} - -/* Generate c code for make__ functions */ - -void CodeBuilder::constructConstructors() -{ - std::vector::iterator iter; - for (iter = tagList.begin(); iter != tagList.end(); iter++) - { - DOMElement* tagEl = *iter; - XtString tagS(tagEl->getTagName()); - XtString listType = tagS.listType(); - XtString simpleType = tagS.simpleType(); - - hFile << std::endl; - cFile << std::endl; - - XtString repS = tagEl->getAttribute(X("maxOccurs")); - int rep = (repS == "unbounded")? INT_MAX : atoi(S(repS)); - if (rep > 1) - { - hFile << listType << "* "; - cFile << listType << "* "; - XtString listT(listType); - listT.erase(listT.rfind('_')); - hFile << "make_" << listT; - cFile << "make_" << listT; - hFile << "(int n);" << std::endl; - cFile << "(int n)" << std::endl - << "{" << std::endl - << " int i;" << std::endl - << " int rep = (n > 1) ? n-1 : 0;" << std::endl - << " int size = sizeof(" << listType - << ") + rep * sizeof(" << simpleType << ");" << std::endl - << " " << listType - << "* p = (" << listType << "*)MALLOC(size,\"" - << listType << "\");" << std::endl - << " p->mult = 0;" << std::endl - << " for (i=0; iin[i];" << std::endl; - DOMNamedNodeMap* varList = tagEl->getAttributes(); - int varCount = varList->getLength(); - for (int v = 0; v < varCount; v++) - { - DOMNode* var = varList->item(v); - XtString typeS(var->getNodeValue()); - XtString nameS(var->getNodeName()); - if (typeS == "string" || - typeS == "anyURI") - { - cFile << " pp->" << nameS - << " = (string_t)&hddm_" + classPrefix + "_nullTarget;" - << std::endl; - } - else if (typeS == "int" || - typeS == "long" || - typeS == "float" || - typeS == "double" || - typeS == "boolean") - { - cFile << " pp->" << nameS << " = 0;" << std::endl; - } - else if (typeS == "Particle_t") - { - cFile << " pp->" << nameS - << " = (Particle_t)0;" << std::endl; - } - } - DOMNodeList* contList = tagEl->getChildNodes(); - for (unsigned int c = 0; c < contList->getLength(); c++) - { - DOMNode* cont = contList->item(c); - short ctype = cont->getNodeType(); - if (ctype == DOMNode::ELEMENT_NODE) - { - DOMElement* contEl = (DOMElement*) cont; - XtString cnameS(contEl->getTagName()); - XtString crepS(contEl->getAttribute(X("maxOccurs"))); - int crep = (crepS == "unbounded")? INT_MAX : atoi(S(crepS)); - if (crep > 1) - { - cFile << " pp->" << cnameS.plural() - << " = (" << cnameS.listType() - << "*)&hddm_" + classPrefix + "_nullTarget;" - << std::endl; - } - else - { - cFile << " pp->" << cnameS - << " = (" << cnameS.simpleType() - << "*)&hddm_" + classPrefix + "_nullTarget;" - << std::endl; - } - } - } - cFile << " }" << std::endl; - } - else - { - hFile << simpleType << "* "; - cFile << simpleType << "* "; - XtString simpleT(simpleType); - simpleT.erase(simpleT.rfind('_')); - hFile << "make_" << simpleT; - cFile << "make_" << simpleT; - hFile << "();" << std::endl; - cFile << "()" << std::endl - << "{" << std::endl - << " int size = sizeof(" << simpleType << ");" << std::endl - << " " << simpleType << "* p = " - << "(" << simpleType << "*)MALLOC(size,\"" - << simpleType << "\");" << std::endl; - DOMNamedNodeMap* varList = tagEl->getAttributes(); - int varCount = varList->getLength(); - for (int v = 0; v < varCount; v++) - { - DOMNode* var = varList->item(v); - XtString typeS(var->getNodeValue()); - XtString nameS(var->getNodeName()); - if (typeS == "string" || - typeS == "anyURI") - { - cFile << " p->" << nameS - << " = (string_t)&hddm_" + classPrefix + "_nullTarget;" - << std::endl; - } - else if (typeS == "int" || - typeS == "long" || - typeS == "float" || - typeS == "double" || - typeS == "boolean") - { - cFile << " p->" << nameS << " = 0;" << std::endl; - } - else if (typeS == "Particle_t") - { - cFile << " p->" << nameS - << " = (Particle_t)0;" << std::endl; - } - } - DOMNodeList* contList = tagEl->getChildNodes(); - for (unsigned int c = 0; c < contList->getLength(); c++) - { - DOMNode* cont = contList->item(c); - short ctype = cont->getNodeType(); - if (ctype == DOMNode::ELEMENT_NODE) - { - DOMElement* contEl = (DOMElement*) cont; - XtString cnameS(contEl->getTagName()); - XtString crepS(contEl->getAttribute(X("maxOccurs"))); - int crep = (crepS == "unbounded")? INT_MAX : atoi(S(crepS)); - if (crep > 1) - { - cFile << " p->" << cnameS.plural() - << " = (" << cnameS.listType() - << "*)&hddm_" + classPrefix + "_nullTarget;" - << std::endl; - } - else - { - cFile << " p->" << cnameS - << " = (" << cnameS.simpleType() - << "*)&hddm_" + classPrefix + "_nullTarget;" - << std::endl; - } - } - } - } - cFile << " return p;" << std::endl - << "}" << std::endl; - } -} - -/* Generate c functions for unpacking binary stream into c-structures */ - -void CodeBuilder::constructUnpackers() -{ - cFile << std::endl; - std::vector::iterator iter; - for (iter = tagList.begin(); iter != tagList.end(); iter++) - { - DOMElement* tagEl = *iter; - XtString tagS(tagEl->getTagName()); - XtString listType = tagS.listType(); - XtString simpleType = tagS.simpleType(); - - cFile << std::endl << "static "; - - XtString tagType; - XtString repS = tagEl->getAttribute(X("maxOccurs")); - int rep = (repS == "unbounded")? INT_MAX : atoi(S(repS)); - if (rep > 1) - { - tagType = tagS.listType(); - } - else - { - tagType = tagS.simpleType(); - } - XtString tagT(tagType); - tagT.erase(tagT.rfind('_')); - cFile << tagType << "* unpack_" << tagT - << "(XDR* xdrs, popNode* pop)" - << std::endl - << "{" << std::endl - << " " << tagType << "* this1 = (" << tagType - << "*)HDDM_NULL;" << std::endl - << " unsigned int size;" << std::endl - << " if (! xdr_u_int(xdrs,&size))" << std::endl - << " {" << std::endl - << " return this1;" << std::endl - << " }" << std::endl - << " else if (size > 0)" << std::endl - << " {" << std::endl - << " off_t start = xdr_getpos64(xdrs);" << std::endl; - - if (rep > 1) - { - cFile << " int m;" << std::endl - << " unsigned int mult;" << std::endl - << " if (! xdr_u_int(xdrs,&mult))" << std::endl - << " XDRerror();" << std::endl; - cFile << " this1 = make_" << tagT << "(mult);" << std::endl; - - cFile << " this1->mult = mult;" << std::endl - << " for (m = 0; m < mult; m++ )" << std::endl - << " {" << std::endl; - } - else - { - cFile << " this1 = make_" << tagT << "();" << std::endl - << " {" << std::endl; - } - - int hasContents = 0; - DOMNodeList* contList = tagEl->getChildNodes(); - for (unsigned int c = 0; c < contList->getLength(); c++) - { - DOMNode* cont = contList->item(c); - short type = cont->getNodeType(); - if (type == DOMNode::ELEMENT_NODE) - { - hasContents = 1; - DOMElement* contEl = (DOMElement*) cont; - XtString nameS(contEl->getTagName()); - XtString reS(contEl->getAttribute(X("maxOccurs"))); - int re = (reS == "unbounded")? INT_MAX : atoi(S(reS)); - cFile << " int p;" << std::endl - << " void* (*ptr) = (void**) &this1->" - << ((rep > 1) ? "in[m]." : "" ) - << ((re > 1) ? nameS.plural() : nameS) << ";" << std::endl; - break; - } - } - - DOMNamedNodeMap* attList = tagEl->getAttributes(); - for (unsigned int a = 0; a < attList->getLength(); a++) - { - DOMNode* att = attList->item(a); - XtString typeS(att->getNodeValue()); - XtString nameS(att->getNodeName()); - XtString nameStr(nameS); - if (rep > 1) - { - nameStr = "in[m]." + nameS; - } - if (typeS == "int") - { - cFile << " if (! xdr_int(xdrs,&this1->" - << nameStr << "))" << std::endl - << " XDRerror();" << std::endl; - } - else if (typeS == "long") - { - cFile << "#ifndef XDR_LONGLONG_MISSING" << std::endl - << " if (! xdr_longlong_t(xdrs,&this1->" - << nameStr << "))" << std::endl - << " XDRerror();" << std::endl - << "#else" << std::endl - << " {" << std::endl - << " int* " << nameStr << "_ = " - << "(int*)&this1->" << nameStr << ";" << std::endl - << "# if __BIG_ENDIAN__" << std::endl - << " if (! xdr_int(xdrs,&" - << nameStr << "_[0]))" << std::endl - << " XDRerror();" << std::endl - << " if (! xdr_int(xdrs,&" - << nameStr << "_[1]))" << std::endl - << " XDRerror();" << std::endl - << "# else" << std::endl - << " if (! xdr_int(xdrs,&" - << nameStr << "_[1]))" << std::endl - << " XDRerror();" << std::endl - << " if (! xdr_int(xdrs,&" - << nameStr << "_[0]))" << std::endl - << " XDRerror();" << std::endl - << "# endif" << std::endl - << " }" << std::endl - << "#endif" << std::endl; - } - else if (typeS == "float") - { - cFile << " if (! xdr_float(xdrs,&this1->" - << nameStr << "))" << std::endl - << " XDRerror();" << std::endl; - } - else if (typeS == "double") - { - cFile << " if (! xdr_double(xdrs,&this1->" - << nameStr << "))" << std::endl - << " XDRerror();" << std::endl; - } - else if (typeS == "boolean") - { - cFile << " if (! xdr_bool(xdrs,&this1->" - << nameStr << "))" << std::endl - << " XDRerror();" << std::endl; - } - else if (typeS == "Particle_t") - { - cFile << " if (! xdr_int(xdrs,(int*)&this1->" - << nameStr << "))" << std::endl - << " XDRerror();" << std::endl; - } - else if (typeS == "string") - { - cFile << " this1->" << nameStr << " = 0;" << std::endl - << " if (! xdr_string(xdrs, &this1->" - << nameStr << ", hddm_" + classPrefix - << "_stringsize))" << std::endl - << " XDRerror();" << std::endl; - cFile << " CHECK(this1->" << nameStr << "," - << "\"string_t\");" << std::endl; - } - else if (typeS == "anyURI") - { - cFile << " this1->" << nameStr << " = 0;" << std::endl - << " if (! xdr_string(xdrs, &this1->" - << nameStr << ", hddm_" + classPrefix - << "_stringsize))" << std::endl - << " XDRerror();" << std::endl; - cFile << " CHECK(this1->" << nameStr << "," - << "\"string_t\");" << std::endl; - } - else - { - /* ignore attributes with unrecognized values */ - } - } - - if (hasContents) - { - cFile << " for (p = 0; p < pop->popListLength; p++)" << std::endl - << " {" << std::endl - << " popNode* pnode = pop->popList[p];" << std::endl - << " if (pnode)" << std::endl - << " {" << std::endl - << " int kid = pnode->inParent;" << std::endl - << " ptr[kid] = pnode->unpacker(xdrs,pnode);" - << std::endl - << " }" << std::endl - << " else" << std::endl - << " {" << std::endl - << " unsigned int skip;" << std::endl - << " if (! xdr_u_int(xdrs,&skip))" << std::endl - << " XDRerror();" << std::endl - << " xdr_setpos64(xdrs,xdr_getpos64(xdrs)+skip);" - << std::endl - << " }" << std::endl - << " }" << std::endl; - } - cFile << " }" << std::endl - << " xdr_setpos64(xdrs,start+size);" << std::endl - << " }" << std::endl - << " return this1;" << std::endl - << "}" << std::endl; - } -} - -/* Generate c function to read from binary stream into c-structures */ - -void CodeBuilder::constructReadFunc(DOMElement* topEl) -{ - XtString topS(topEl->getTagName()); - XtString topType = topS.simpleType(); - XtString topT(topType); - topT.erase(topT.rfind('_')); - hFile << std::endl - << topType << "* read_" << topT - << "(" << classPrefix << "_iostream_t* fp" << ");" << std::endl; - - cFile << std::endl - << topType << "* read_" << topT - << "(" << classPrefix << "_iostream_t* fp" << ")" << std::endl - << "{" << std::endl - << " off_t base;" << std::endl - << " unsigned int size;" << std::endl - << " xdrmem_create(fp->xdrs,fp->iobuffer,fp->iobuffer_size,XDR_DECODE);" - << std::endl - << " base = xdr_getpos64(fp->xdrs);" << std::endl - << " if (fread(fp->iobuffer,1,4,fp->fd) != 4 || ! xdr_u_int(fp->xdrs,&size))" - << std::endl - << " {" << std::endl - << " xdr_destroy(fp->xdrs);" << std::endl - << " return 0;" << std::endl - << " }" << std::endl - << " else if (size == 1)" << std::endl - << " {" << std::endl - << " fprintf(stderr,\"hddm error - \"" << std::endl - << " \"stream compression and/or integrity checks" - " found in input stream.\\n\"" << std::endl - << " \"These features are not supported by the" - " hddm c i/o interface.\\n\");" << std::endl - << " fprintf(stderr,\"You must use the c++ interface" - " to read this file.\\n\");" << std::endl - << " exit(9);" << std::endl - << " }" << std::endl - << " else if (size + 4 > fp->iobuffer_size)" << std::endl - << " {" << std::endl - << " xdr_destroy(fp->xdrs);" << std::endl - << " char *newbuf = (char*)malloc(fp->iobuffer_size *= 2);" - << std::endl - << " memcpy(newbuf,fp->iobuffer,4);" << std::endl - << " free(fp->iobuffer);" << std::endl - << " fp->iobuffer = newbuf;" << std::endl - << " xdrmem_create(fp->xdrs,fp->iobuffer,fp->iobuffer_size,XDR_DECODE);" - << std::endl - << " base = xdr_getpos64(fp->xdrs);" << std::endl - << " }" << std::endl - << " if (fread(fp->iobuffer+4,1,size,fp->fd) != size)" << std::endl - << " {" << std::endl - << " fprintf(stderr,\"hddm error - \"" << std::endl - << " \"read failed on input hddm stream, \"" << std::endl - << " \"cannot continue.\\n\");" << std::endl - << " exit(9);" << std::endl - << " }" << std::endl - << " xdr_setpos64(fp->xdrs,base);" << std::endl - << " " << topType << "* nextEvent = " - << "unpack_" << topT << "(fp->xdrs,fp->popTop);" << std::endl - << " xdr_destroy(fp->xdrs);" << std::endl - << " return (nextEvent == HDDM_NULL)? 0 : nextEvent;" << std::endl - << "}" << std::endl; -} - -/* Generate c function to skip over events in the binary stream */ - -void CodeBuilder::constructSkipFunc() -{ - hFile << std::endl - << "int skip_" << classPrefix << "_HDDM" - << "(" << classPrefix << "_iostream_t* fp, int nskip);" << std::endl; - - cFile << std::endl - << "int skip_" << classPrefix << "_HDDM" - << "(" << classPrefix << "_iostream_t* fp, int nskip)" << std::endl - << "{" << std::endl - << " int skipped;" << std::endl - << " for (skipped=0; skipped < nskip; ++skipped)" << std::endl - << " {" << std::endl - << " unsigned int size;" << std::endl - << " xdrmem_create(fp->xdrs,fp->iobuffer,fp->iobuffer_size,XDR_DECODE);" - << std::endl - << " if (fread(fp->iobuffer,1,4,fp->fd) != 4 || ! xdr_u_int(fp->xdrs,&size))" - << std::endl - << " {" << std::endl - << " break;" << std::endl - << " }" << std::endl - << " else if (size == 1)" << std::endl - << " {" << std::endl - << " fprintf(stderr,\"hddm error - \"" << std::endl - << " \"stream compression and/or integrity " - "checks found in input stream.\\n\"" << std::endl - << " \"These features are not supported " - "by the hddm c i/o interface.\\n\");" << std::endl - << " fprintf(stderr,\"You must use the c++ " - << "interface to read this file.\\n\");" << std::endl - << " exit(9);" << std::endl - << " }" << std::endl - << " else if (size + 4 > fp->iobuffer_size)" << std::endl - << " {" << std::endl - << " xdr_destroy(fp->xdrs);" << std::endl - << " char *newbuf = (char*)malloc(fp->iobuffer_size *= 2);" - << std::endl - << " memcpy(newbuf,fp->iobuffer,4);" << std::endl - << " free(fp->iobuffer);" << std::endl - << " fp->iobuffer = newbuf;" << std::endl - << " xdrmem_create(fp->xdrs,fp->iobuffer,fp->iobuffer_size,XDR_DECODE);" - << std::endl - << " }" << std::endl - << " if (fread(fp->iobuffer+4,1,size,fp->fd) != size)" << std::endl - << " {" << std::endl - << " fprintf(stderr,\"hddm error - \"" << std::endl - << " \"read failed on input hddm stream, \"" << std::endl - << " \"cannot continue.\\n\");" << std::endl - << " exit(9);" << std::endl - << " }" << std::endl - << " }" << std::endl - << " xdr_destroy(fp->xdrs);" << std::endl - << " return skipped;" << std::endl - << "}" << std::endl; -} - -/* Generate streamers for packing c-structures onto a binary stream - * and deleting them from memory when output is complete - */ - -void CodeBuilder::constructPackers() -{ - cFile << std::endl; - std::vector::iterator iter; - for (iter = tagList.begin(); iter != tagList.end(); iter++) - { - DOMElement* tagEl = *iter; - XtString tagS(tagEl->getTagName()); - XtString listType = tagS.listType(); - XtString simpleType = tagS.simpleType(); - - cFile << "static "; - - XtString tagType; - XtString repS(tagEl->getAttribute(X("maxOccurs"))); - int rep = (repS == "unbounded")? INT_MAX : atoi(S(repS)); - if (rep > 1) - { - tagType = listType; - } - else - { - tagType = simpleType; - } - XtString tagT(tagType); - tagT.erase(tagT.rfind('_')); - cFile << "int pack_" << tagT << "(XDR* xdrs, " - << tagType << "* this1);" << std::endl; - } - - for (iter = tagList.begin(); iter != tagList.end(); iter++) - { - DOMElement* tagEl = *iter; - XtString tagS(tagEl->getTagName()); - XtString listType = tagS.listType(); - XtString simpleType = tagS.simpleType(); - - cFile << std::endl << "static "; - - XtString tagType; - XtString repS(tagEl->getAttribute(X("maxOccurs"))); - int rep = (repS == "unbounded")? INT_MAX : atoi(S(repS)); - if (rep > 1) - { - tagType = listType; - } - else - { - tagType = simpleType; - } - XtString tagT(tagType); - tagT.erase(tagT.rfind('_')); - cFile << "int pack_" << tagT << "(XDR* xdrs, " - << tagType << "* this1)" << std::endl - << "{" << std::endl; - if (rep > 1) - { - cFile << " int m=0;" << std::endl; - } - cFile << " unsigned int size=0;" << std::endl - << " off_t base,start,end;" << std::endl - << " base = xdr_getpos64(xdrs);" << std::endl; - if (tagT.find("_HDDM") != tagT.npos) - { - cFile - << " if (base == -1)" << std::endl - << " {" << std::endl - << " fprintf(stderr,\"hddm error - \"" << std::endl - << " \"stream offset request failed " - "on output hddm stream, \"" << std::endl - << " \"cannot continue.\\n\");" << std::endl - << " return -1;" << std::endl - << " }" << std::endl; - } - cFile << " if (! xdr_u_int(xdrs,&size))" << std::endl - << " XDRerror();" << std::endl - << " start = xdr_getpos64(xdrs);" << std::endl - << std::endl; - if (rep > 1) - { - cFile << " if (! xdr_u_int(xdrs,&this1->mult))" << std::endl - << " XDRerror();" << std::endl - << " for (m = 0; m < this1->mult; m++)" << std::endl - << " {" << std::endl; - } - else - { - cFile << " {" << std::endl; - } - - DOMNamedNodeMap* attList = tagEl->getAttributes(); - for (unsigned int a = 0; a < attList->getLength(); a++) - { - DOMNode* att = attList->item(a); - XtString typeS(att->getNodeValue()); - XtString nameS(att->getNodeName()); - XtString nameStr(nameS); - if (rep > 1) - { - nameStr = "in[m]." + nameS; - } - if (typeS == "int") - { - cFile << " if (! xdr_int(xdrs,&this1->" - << nameStr << "))" << std::endl - << " XDRerror();" << std::endl; - } - if (typeS == "long") - { - cFile << "#ifndef XDR_LONGLONG_MISSING" << std::endl - << " if (! xdr_longlong_t(xdrs,&this1->" - << nameStr << "))" << std::endl - << " XDRerror();" << std::endl - << "#else" << std::endl - << " {" << std::endl - << " int* " << nameStr << "_ = " - << "(int*)&this1->" << nameStr << ";" << std::endl - << "# if __BIG_ENDIAN__" << std::endl - << " if (! xdr_int(xdrs,&" - << nameStr << "_[0]))" << std::endl - << " XDRerror();" << std::endl - << " if (! xdr_int(xdrs,&" - << nameStr << "_[1]))" << std::endl - << " XDRerror();" << std::endl - << "# else" << std::endl - << " if (! xdr_int(xdrs,&" - << nameStr << "_[1]))" << std::endl - << " XDRerror();" << std::endl - << " if (! xdr_int(xdrs,&" - << nameStr << "_[0]))" << std::endl - << " XDRerror();" << std::endl - << "# endif" << std::endl - << " }" << std::endl - << "#endif" << std::endl; - } - else if (typeS == "float") - { - cFile << " if (! xdr_float(xdrs,&this1->" - << nameStr << "))" << std::endl - << " XDRerror();" << std::endl; - } - else if (typeS == "double") - { - cFile << " if (! xdr_double(xdrs,&this1->" - << nameStr << "))" << std::endl - << " XDRerror();" << std::endl; - } - else if (typeS == "boolean") - { - cFile << " if (! xdr_bool(xdrs,&this1->" - << nameStr << "))" << std::endl - << " XDRerror();" << std::endl; - } - else if (typeS == "Particle_t") - { - cFile << " if (! xdr_int(xdrs,(int*)&this1->" - << nameStr << "))" << std::endl - << " XDRerror();" << std::endl; - } - else if (typeS == "string") - { - cFile << " if (! xdr_string(xdrs,&this1->" - << nameStr << ", hddm_" + classPrefix - << "_stringsize))" << std::endl - << " XDRerror();" << std::endl; - cFile << " FREE(this1->" << nameStr << ");" << std::endl; - } - else if (typeS == "anyURI") - { - cFile << " if (! xdr_string(xdrs,&this1->" - << nameStr << ", hddm_" + classPrefix - << "_stringsize))" << std::endl - << " XDRerror();" << std::endl; - cFile << " FREE(this1->" << nameStr << ");" << std::endl; - } - else - { - /* ignore attributes with unrecognized values */ - } - } - - DOMNodeList* contList = tagEl->getChildNodes(); - for (unsigned int c = 0; c < contList->getLength(); c++) - { - DOMNode* cont = contList->item(c); - short type = cont->getNodeType(); - if (type == DOMNode::ELEMENT_NODE) - { - DOMElement* contEl = (DOMElement*) cont; - XtString nameS(contEl->getTagName()); - XtString reS(contEl->getAttribute(X("maxOccurs"))); - int re = (reS == "unbounded")? INT_MAX : atoi(S(reS)); - XtString contType; - if (re > 1) - { - contType = nameS.listType(); - } - else - { - contType = nameS.simpleType(); - } - XtString contT(contType); - contT.erase(contT.rfind('_')); - cFile << " if (this1->" - << ((rep > 1)? "in[m]." : "") - << ((re > 1)? nameS.plural(): nameS) << " != (" - << contType << "*)&hddm_" + classPrefix + "_nullTarget)" - << std::endl - << " {" << std::endl - - << " if (pack_" << contT << "(xdrs,this1->" - << ((rep > 1)? "in[m]." : "") - << ((re > 1)? nameS.plural() : nameS) << ") < 0) {" - << std::endl - << " return -1;" << std::endl - << " }" << std::endl - << " }" << std::endl - << " else" << std::endl - << " {" << std::endl - << " int zero=0;" << std::endl - << " if (! xdr_int(xdrs,&zero))" << std::endl - << " XDRerror();" << std::endl - << " }" << std::endl; - } - } - - cFile << " }" << std::endl - << " end = xdr_getpos64(xdrs);" << std::endl - << " xdr_setpos64(xdrs,base);" << std::endl - << " size = end-start;" << std::endl; - if (tagT.find("_HDDM") != tagT.npos) - { - cFile - << " if (size + 4 > hddm_" + classPrefix + "_buffersize) {" - << std::endl - << " fprintf(stderr,\"hddm error - \"" << std::endl - << " \"output buffer overflow on hddm stream," - " cannot continue.\\n\");" << std::endl - << " fprintf(stderr,\"Please increase buffer" - " size using \"" << std::endl - << " \"set_" + classPrefix + "_HDDM_buffersize(s) with" - " s > %d.\", hddm_" + classPrefix + "_buffersize);" - << std::endl - << " exit(9);" << std::endl - << " }" << std::endl; - } - cFile << " if (! xdr_u_int(xdrs,&size))" << std::endl - << " XDRerror();" << std::endl - << " xdr_setpos64(xdrs,end);" << std::endl - << " FREE(this1);" << std::endl - << " return size;" << std::endl - << "}" << std::endl; - } -} - -/* Generate c functions for exporting c-structures onto a binary stream */ - -void CodeBuilder::constructFlushFunc(DOMElement* el) -{ - DOMElement* topEl = tagList[0]; - XtString topS(topEl->getTagName()); - XtString topType = topS.simpleType(); - XtString topT(topType); - topT.erase(topT.rfind('_')); - - constructPackers(); - - hFile << std::endl - << "int flush_" << topT << "(" << topType << "* this1," - << classPrefix << "_iostream_t* fp" << ");" << std::endl; - - cFile << std::endl - << "int flush_" << topT << "(" << topType << "* this1," - << classPrefix << "_iostream_t* fp" << ")" << std::endl - << "{" << std::endl - << " if (this1 == 0)" << std::endl - << " {" << std::endl - << " return 0;" << std::endl - << " }" << std::endl - << " else if (fp == 0)" << std::endl - << " {" << std::endl - << " XDR* xdrs = (XDR*)malloc(sizeof(XDR));" << std::endl - << " char* dump = (char*)malloc(hddm_" - + classPrefix + "_buffersize);" << std::endl - << " xdrmem_create(xdrs,dump,hddm_" - + classPrefix + "_buffersize,XDR_ENCODE);" << std::endl - << " pack_" << topT << "(xdrs,this1);" << std::endl - << " xdr_destroy(xdrs);" << std::endl - << " free(xdrs);" << std::endl - << " free(dump);" << std::endl - << " }" << std::endl - << " else if (fp->iomode == HDDM_STREAM_OUTPUT)" << std::endl - << " {" << std::endl - << " int size;" << std::endl - << " xdrmem_create(fp->xdrs,fp->iobuffer," - "fp->iobuffer_size,XDR_ENCODE);" << std::endl - << " size = pack_" + classPrefix + "_HDDM(fp->xdrs,this1);" - << std::endl - << " if (size < 0)" << std::endl - << " {" << std::endl - << " fp->lerrno = errno;" << std::endl - << " xdr_destroy(fp->xdrs);" << std::endl - << " return -1;" << std::endl - << " }" << std::endl - << " else if (size > 0)" << std::endl - << " {" << std::endl - << " int wsize = fwrite(fp->iobuffer,1,size+4,fp->fd);" - << std::endl - << " if (wsize != size + 4)" << std::endl - << " {" << std::endl - << " fprintf(stderr,\"HDDM Error: error writing to \"" - << std::endl - << " \"output hddm file.\\n\");" << std::endl - << " fprintf(stderr,\"%d bytes of %d " - "actually written.\\n\"," << std::endl - << " wsize, size+4);" << std::endl - << " exit(9);" << std::endl - << " }" << std::endl - << " }" << std::endl - << " xdr_destroy(fp->xdrs);" << std::endl - << " }" << std::endl - << " return 0;" << std::endl - << "}" << std::endl; -} - -/* Generate c functions that match up corresponding elements between - * the c structures and the data model that appears on the input - * binary stream. If successful, these routines build a hierarchical - * structure (the "pop tree") that gives directions to the unpackers. - * - * The matching rules are as follows: - * - * 1) The attribute list for any given tag must be identical in content - * and order wherever it appears, otherwise there is a collision. - * - * 2) The content list for any given tag must be internally consistent - * within each model, but there are no requirements for agreement - * between the c-structures and the binary stream models. Only the - * contents which appear in both models will be unpacked, however. - */ - -void CodeBuilder::writeMatcher() -{ - cFile << std::endl - << "static int getTag(char* d, char* tag)" << std::endl - << "{" << std::endl - << " int level;" << std::endl - << " char* token;" << std::endl - << " char line[500];" << std::endl - << " strncpy(line,d,500);" << std::endl - << " line[499] = 0;" << std::endl - << " level = index(line,'<')-line;" << std::endl - << " if (level < 500 &&" << std::endl - << " (token = strtok(line+level+1,\" >\")))" << std::endl - << " {" << std::endl - << " strncpy(tag,token,500);" << std::endl - << " return level/2;" << std::endl - << " }" << std::endl - << " return -1;" << std::endl - << "}" << std::endl - << std::endl - << "static char* getEndTag(char* d, char* tag)" << std::endl - << "{" << std::endl - << " char line[500];" << std::endl - << " char endTag[510];" << std::endl - << " strncpy(line,d,500);" << std::endl - << " line[499] = 0;" << std::endl - << " if (strstr(strtok(line,\"\\n\"),\"/>\") == 0)" << std::endl - << " {" << std::endl - << " sprintf(endTag,\"\",tag);" << std::endl - << " }" << std::endl - << " else" << std::endl - << " {" << std::endl - << " strcpy(endTag,\"/>\");" << std::endl - << " }" << std::endl - << " return strstr(d,endTag);" << std::endl - << "}" << std::endl - << std::endl - << "static void collide(char* b, char* c)" << std::endl - << "{" << std::endl - << " char btag[500];" << std::endl - << " getTag(b,btag);" << std::endl - << " b = index(b,'<');" << std::endl - << " c = index(c,'<');" << std::endl - << " *(index(b,'\\n')) = 0;" << std::endl - << " *(index(c,'\\n')) = 0;" << std::endl - << " fprintf(stderr,\"HDDM warning: \");" << std::endl - << " fprintf(stderr,\"tag %s in input file \", btag);" << std::endl - << " fprintf(stderr,\"does not match c header hddm_" - << classPrefix << ".h\\n\");" << std::endl - << " fprintf(stderr,\" input file: %s\\n\", b);" << std::endl - << " fprintf(stderr,\" c header: %s\\n\", c);" << std::endl - << " fprintf(stderr,\" === Tag %s will be ignored,\", btag);" - << std::endl - << " fprintf(stderr,\" rebuild to cure the problem ===\\n\");" - << std::endl - << " *(index(b,0)) = '\\n';" << std::endl - << " *(index(c,0)) = '\\n';" << std::endl - << "}" << std::endl - << std::endl - << "static int tag_strncmp(char* a, char* b, int len)" << std::endl - << "{" << std::endl - << " if (strncmp(a,b,len) == 0) {" << std::endl - << " return 0;" << std::endl - << " }" << std::endl - << " else if (strncmp(a,\"::iterator iter; - for (iter = tagList.begin(); iter != tagList.end(); iter++) - { - XtString tagS((*iter)->getTagName()); - XtString repS((*iter)->getAttribute(X("maxOccurs"))); - int rep = (repS == "unbounded")? INT_MAX : atoi(S(repS)); - XtString tagType; - if (rep > 1) - { - tagType = tagS.listType(); - } - else - { - tagType = tagS.simpleType(); - } - XtString tagT(tagType); - tagT.erase(tagT.rfind('_')); - - cFile << " else if " - << "(strcmp(btag,\"" << tagS << "\") == 0)" << std::endl - << " {" << std::endl - << " this1->unpacker = " - << "(void*(*)(XDR*,popNode*))" - << "unpack_" << tagT << ";" << std::endl - << " }" << std::endl; - } - - cFile << " this1->inParent = ptrSeqNo;" << std::endl - << " this1->popListLength = 0;" << std::endl - << " c = index(c+1,'\\n');" << std::endl - << " b = index(b+1,'\\n');" << std::endl - << " while (getTag(b,btag) > blevel)" << std::endl - << " {" << std::endl - << " this1->popList[this1->popListLength++] = matches(b,c);" - << std::endl - << " if (this1->popListLength > " - << MAX_POPLIST_LENGTH << ")" << std::endl - << " {" << std::endl - << " fprintf(stderr," - << "\"hddm error - popList overflow.\\n\");" << std::endl - << " fprintf(stderr," - << "\"Increase MAX_POPLIST_LENGTH and recompile.\\n\");" << std::endl - << " exit(9);" << std::endl - << " }" << std::endl - << " b = getEndTag(b,btag);" << std::endl - << " b = index(b+1,'\\n');" << std::endl - << " }" << std::endl - << " return this1;" << std::endl - << " }" << std::endl - << " else" << std::endl - << " {" << std::endl - << " c = getEndTag(c,ctag);" << std::endl - << " c = index(c+1,'\\n');" << std::endl - << " ++ptrSeqNo;" << std::endl - << " }" << std::endl - << " }" << std::endl - << " return 0;" << std::endl - << "}" << std::endl; -} - -/* Generate c code to open a hddm file for reading */ - -void CodeBuilder::constructOpenFunc(DOMElement* el) -{ - XtString tagS(el->getTagName()); - XtString tagType = tagS.simpleType(); - XtString tagT(tagType); - tagT.erase(tagT.rfind('_')); - hFile << std::endl - << classPrefix << "_iostream_t* " - << "open_" << tagT << "(char* filename);" << std::endl; - - writeMatcher(); - - cFile << std::endl - << classPrefix << "_iostream_t* " - << "open_" << tagT << "(char* filename)" << std::endl - << "{" << std::endl - << " " << classPrefix << "_iostream_t* fp = " - << "(" << classPrefix << "_iostream_t*)" - << "malloc(sizeof(" << classPrefix << "_iostream_t));" << std::endl - << " char* p;" << std::endl - << " char* head;" << std::endl - << " char* nullfilename=(char*)\"\";" << std::endl - << " if (filename)" << std::endl - << " {" << std::endl - << " fp->fd = fopen(filename,\"r\");" << std::endl - << " }" << std::endl - << " else" << std::endl - << " {" << std::endl - << " fp->fd = fdopen(0,\"r\");" << std::endl - << " filename = nullfilename;" << std::endl - << " }" << std::endl - << " if (fp->fd == 0)" << std::endl - << " {" << std::endl - << " free(fp);" << std::endl - << " return 0;" << std::endl - << " }" << std::endl - << " fp->iomode = HDDM_STREAM_INPUT;" << std::endl - << " head = (char*)malloc(hddm_" + classPrefix + "_headersize);" - << std::endl - << " while ((fgets(head,7,fp->fd) != 0) &&" << std::endl - << " (strstr(head,\"\") == 0;" << std::endl - << " p += strlen(p))" << std::endl - << " {" << std::endl - << " if (p-head + 10 > hddm_" + classPrefix + "_headersize)" - << std::endl - << " {" << std::endl - << " fprintf(stderr,\"HDDM Error: \");" << std::endl - << " fprintf(stderr,\"input template model overflows \"" - << std::endl - << " \"the hddm header input buffer, cannot continue.\\n\");" - << std::endl - << " fprintf(stderr,\"Please increase header" - " buffer size using \"" << std::endl - << " \"set_" + classPrefix + "_HDDM_headersize(s) with " - "s > %d.\\n\", hddm_" + classPrefix + "_headersize);" - << std::endl - << " exit(9);" << std::endl - << " }" << std::endl - << " if (fgets(p,1000,fp->fd) == 0)" << std::endl - << " {" << std::endl - << " break;" << std::endl - << " }" << std::endl - << " }" << std::endl - << " fp->popTop = matches(head,HDDM_" << classPrefix - << "_DocumentString);" << std::endl - << " free(head);" << std::endl - << " if (fp->popTop == 0" - << " || fp->popTop->popListLength == 0)" << std::endl - << " {" << std::endl - << " fprintf(stderr,\"HDDM Error: \");" << std::endl - << " fprintf(stderr,\"input template model \");" << std::endl - << " fprintf(stderr,\"does not match c header.\");" << std::endl - << " fprintf(stderr,\" Please recompile.\\n\");" << std::endl - << " exit(9);" << std::endl - << " }" << std::endl - << " fp->filename = " - << "(char*)malloc(strlen(filename) + 1);" << std::endl - << " strcpy(fp->filename,filename);" << std::endl - << " fp->xdrs = (XDR*)malloc(sizeof(XDR));" << std::endl - << " fp->iobuffer = (char*)malloc(fp->iobuffer_size" - " = hddm_" + classPrefix + "_buffersize);" << std::endl - << " return fp;" << std::endl - << "}" << std::endl; -} - -/* Generate the c code to open a hddm file for writing */ - -void CodeBuilder::constructInitFunc(DOMElement* el) -{ - XtString tagS(el->getTagName()); - XtString tagType = tagS.simpleType(); - XtString tagT(tagType); - tagT.erase(tagT.rfind('_')); - hFile << std::endl - << classPrefix << "_iostream_t* " - << "init_" << tagT << "(char* filename);" << std::endl; - cFile << std::endl - << classPrefix << "_iostream_t* " - << "init_" << tagT << "(char* filename)" << std::endl - << "{" << std::endl - << " int len;" << std::endl - << " char* head;" << std::endl - << " char* nullfilename=(char*)\"\";" << std::endl - << " " << classPrefix << "_iostream_t* fp = " - << "(" << classPrefix << "_iostream_t*)" - << "malloc(sizeof(" << classPrefix << "_iostream_t));" << std::endl - << " if (filename)" << std::endl - << " {" << std::endl - << " fp->fd = fopen(filename,\"w\");" << std::endl - << " }" << std::endl - << " else" << std::endl - << " {" << std::endl - << " fp->fd = fdopen(1,\"w\");" << std::endl - << " filename = nullfilename;" << std::endl - << " }" << std::endl - << " if (fp->fd == 0)" << std::endl - << " {" << std::endl - << " free(fp);" << std::endl - << " return 0;" << std::endl - << " }" << std::endl - << " fp->iomode = HDDM_STREAM_OUTPUT;" << std::endl - << " len = strlen(HDDM_" - << classPrefix << "_DocumentString);" << std::endl - << " head = (char*)malloc(len+1);" << std::endl - << " strcpy(head,HDDM_" - << classPrefix << "_DocumentString);" << std::endl - << " if (fwrite(head,1,len,fp->fd) != len)" << std::endl - << " {" << std::endl - << " fprintf(stderr,\"HDDM Error: \");" << std::endl - << " fprintf(stderr,\"error writing to \");" << std::endl - << " fprintf(stderr,\"output file %s\\n\",filename);" << std::endl - << " exit(9);" << std::endl - << " }" << std::endl - << " fp->filename = " - << "(char*)malloc(strlen(filename) + 1);" << std::endl - << " strcpy(fp->filename,filename);" << std::endl - << " fp->popTop = 0;" << std::endl - << " fp->xdrs = (XDR*)malloc(sizeof(XDR));" << std::endl - << " fp->iobuffer = (char*)malloc(fp->iobuffer_size" - " = hddm_" + classPrefix + "_buffersize);" << std::endl - << " free(head);" << std::endl - << " return fp;" << std::endl - << "}" << std::endl; -} - -/* Generate the c code to close an open hddm file */ - -void CodeBuilder::constructCloseFunc(DOMElement* el) -{ - XtString tagS(el->getTagName()); - XtString tagType = tagS.simpleType(); - XtString tagT(tagType); - tagT.erase(tagT.rfind('_')); - hFile << std::endl - << "void close_" << tagT << "(" - << classPrefix << "_iostream_t* fp);" << std::endl; - - cFile << std::endl - << "static void popaway(popNode* p)" << std::endl - << "{" << std::endl - << " if (p)" << std::endl - << " {" << std::endl - << " int n;" << std::endl - << " for (n = 0; n < p->popListLength; n++)" << std::endl - << " {" << std::endl - << " popaway(p->popList[n]);" << std::endl - << " }" << std::endl - << " free(p);" << std::endl - << " }" << std::endl - << "}" << std::endl - << std::endl - << "void close_" << tagT - << "(" << classPrefix << "_iostream_t* fp)" << std::endl - << "{" << std::endl - << " free(fp->xdrs);" << std::endl - << " free(fp->iobuffer);" << std::endl - << " fclose(fp->fd);" << std::endl - << " free(fp->filename);" << std::endl - << " popaway(fp->popTop);" << std::endl - << " free(fp);" << std::endl - << "}" << std::endl; -} - -/* Generate the xml template in normal form and store in a string */ - -void CodeBuilder::constructDocument(DOMElement* el) -{ - static int indent = 0; - cFile << "\""; - for (int n = 0; n < indent; n++) - { - cFile << " "; - } - - XtString tagS(el->getTagName()); - cFile << "<" << tagS; - DOMNamedNodeMap* attrList = el->getAttributes(); - int attrListLength = attrList->getLength(); - for (int a = 0; a < attrListLength; a++) - { - DOMNode* node = attrList->item(a); - XtString nameS(node->getNodeName()); - XtString valueS(node->getNodeValue()); - cFile << " " << nameS << "=\\\"" << valueS << "\\\""; - } - - DOMNodeList* contList = el->getChildNodes(); - int contListLength = contList->getLength(); - if (contListLength > 0) - { - cFile << ">\\n\"" << std::endl; - indent++; - for (int c = 0; c < contListLength; c++) - { - DOMNode* node = contList->item(c); - if (node->getNodeType() == DOMNode::ELEMENT_NODE) - { - DOMElement* contEl = (DOMElement*) node; - constructDocument(contEl); - } - } - indent--; - cFile << "\""; - for (int n = 0; n < indent; n++) - { - cFile << " "; - } - cFile << "\\n\"" << std::endl; - } - else - { - cFile << " />\\n\"" << std::endl; - } -} diff --git a/src/programs/Utilities/hddm/hddm-cpp.cpp b/src/programs/Utilities/hddm/hddm-cpp.cpp deleted file mode 100644 index 5f866fb574..0000000000 --- a/src/programs/Utilities/hddm/hddm-cpp.cpp +++ /dev/null @@ -1,4583 +0,0 @@ -/* - * hddm-cpp : tool that reads in a HDDM document (Hall D Data Model) - * and writes a c++ class library that expresses the model - * in c++ classes. It also generates input/output methods - * for serializing/deserializing these classes in a form - * suitable for passing over a network or storing on disk. - * - * author: richard.t.jones at uconn.edu - * version: January 25, 2006 - original release. - * January 13, 2012 - added support for compression through - * the xstream zip and bzip2 facilities. - * June 4, 2016 - added reposition support for random - * access to hddm streams, including - * compressed streams. - * October 10, 2020 - introduced support for reading and - * writing of hddm streams to HDF5 files. - * - * Version 1.4 - Richard Jones, February 10, 2021. - * - Modified to be able to accept a hddm file as a valid hddm template. - * This simplifies the documentation by eliminating the false distinction - * between a hddm template and the text header that appears at the top of - * every hddm file. It also gets rid of the unnecessary step of having - * to delete the binary data following the header in a hddm file before - * it can be used as a template. - * - * Programmer's Notes: - * ------------------- - * 1. The HDDM specification describes data files using xml. For - * information about the contents and structure of HDDM documents - * see the web page that describes the data model. - * - * 2. Access by hddm-cpp to the xml source is through the industry- - * standard Document Object Model (DOM) interface. - * - * 3. The code has been tested with the xerces-c DOM implementation from - * Apache, and is intended to be used with the xerces-c library. - * - * 4. Output is sent to .hpp and ++.cpp where - * is by default "hddm_X" and can be changed with the -o option, where - * X is the user-defined HDDM class string defined in the HDDM tag. - * - * 5. As a by-product of using the DOM parser to access the xml source, - * hddm-cpp verifies the source for well-formedness. Therefore it may - * also be used to check the xml data model document. - * - * - * Implementation Notes: - * --------------------- - * 1. The binary stream consists of the hddm data model in the form - * of a well-formed xml header, followed by binary data. - * - * 2. The binary data consist of a sequence of event records, which are - * repetitions of the basic data model in a serial representation. - * - * 3. Each element is output to the stream in the order it appears in - * the data model, prefixed by an exclusive byte count. - * - * 4. Any c++ application compiled with the hddm header file that is - * generated by hddm-cpp is able to read any hddm binary file that - * was written using the same hddm class, ie. the - * document tags must be a non-colliding set (see matching rules). - * - * 5. The input/output features of the class library produced by hddm-cpp - * are implemented on top of the "xstream" binary i/o class by Claudio - * Valente which provides serialization/deserialization of binary data - * using network byte-ordering (RFC-1832), compression/decompression, - * and error checking capability used to make the hddm i/o facility - * flexible and robust. - * - * 6. The matching rules between the built-in data model and the data - * found in an arbitrary input file are as follows: - * a) The attribute list for any given tag must be identical in content - * and order wherever it appears, otherwise there is a collision. - * b) The content list for any given tag must be internally consistent - * within each model, but there are no requirements for agreement - * between the classes and the binary stream models. Only the - * contents which appear in both models will be unpacked, however. - */ - -#include "VersionConfig.hpp" -#include "XString.hpp" -#include "XParsers.hpp" -#include - -#include -#include -#include - -#include -#include -#include -#include -#include - -#define X(str) XString(str).unicode_str() -#define S(str) str.c_str() - -using namespace xercesc; - -XString classPrefix; - -void usage() -{ - std::cerr - << "\nUsage:\n" - << " hddm-cpp [-v | -o ] {HDDM file}\n\n" - << "Options:\n" - << " -v validate only\n" - << " -o write to .hpp, ++.cpp" - << "Version: " << HDDM_VERSION_MAJOR << "." << HDDM_VERSION_MINOR - << std::endl; -} - -std::string guessType(const std::string &literal); -Particle_t lookupParticle(const std::string &name); - -class XtString : public XString -{ -/* XString class with a few extra methods for creating type - * strings that are useful in creating class names - */ - public: - XtString() {}; - XtString(const char* s): XString(s) {}; - XtString(const XMLCh* p): XString(p) {}; - XtString(const std::string& s): XString(s) {}; - XtString(const XString& x): XString(x) {}; - XtString(const XtString& t): XString((XString&)t) {}; - ~XtString() {}; - - XtString plural(); - XtString simpleType(); - XtString listType(); - XtString linkType(); -}; - -class CodeBuilder -{ -/* The methods in this class are used to write the c++ code - * that implements the hddm class library. - */ - public: - std::ofstream hFile; - std::ofstream cFile; - - CodeBuilder() {}; - ~CodeBuilder() {}; - - void checkConsistency(DOMElement* el, DOMElement* elref); - void writeClassdef(DOMElement* el); - void writeClassimp(DOMElement* el); - void constructDocument(DOMElement* el); - void constructGroup(DOMElement* el); - void constructIOstreams(DOMElement* el); - void constructMethods(DOMElement* el); - void constructStreamers(DOMElement* el); - void writeStreamers(DOMElement* el); - - private: - std::vector tagList; - typedef std::vector parentList_t; - typedef std::map parentTable_t; - parentList_t parentList; - parentTable_t parents; - parentTable_t children; - int element_in_list(XtString &name, parentList_t list); -}; - - -int main(int argC, char* argV[]) -{ - try - { - XMLPlatformUtils::Initialize(); - } - catch (const XMLException* toCatch) - { - XtString msg(toCatch->getMessage()); - std::cerr - << "hddm-cpp: Error during initialization! :\n" - << msg << std::endl; - return 1; - } - - if (argC < 2) - { - usage(); - return 1; - } - else if ((argC == 2) && (strcmp(argV[1], "-?") == 0)) - { - usage(); - return 2; - } - - XtString xmlFile; - XtString hFilename; - bool verifyOnly = false; - int argInd; - for (argInd = 1; argInd < argC; argInd++) - { - if (argV[argInd][0] != '-') - { - break; - } - if (strcmp(argV[argInd],"-v") == 0) - { - verifyOnly = true; - } - else if (strcmp(argV[argInd],"-o") == 0) - { - hFilename = XtString(argV[++argInd]); - } - else - { - std::cerr - << "Unknown option \'" << argV[argInd] - << "\', ignoring it\n" << std::endl; - } - } - - if (argInd != argC - 1) - { - usage(); - return 1; - } - xmlFile = XtString(argV[argInd]); - std::ifstream ifs(xmlFile.c_str()); - if (!ifs.good()) - { - std::cerr - << "hddm-cpp: Error opening hddm template " << xmlFile << std::endl; - exit(1); - } - std::ostringstream tmpFileStr; - tmpFileStr << "tmp" << getpid(); - std::ofstream ofs(tmpFileStr.str().c_str()); - if (! ofs.is_open()) - { - std::cerr - << "hddm-cpp: Error opening temp file " << tmpFileStr.str() << std::endl; - exit(2); - } - - XString xmlPreamble("\n"); - XString xmlHeader; - XString line; - while (getline(ifs,line)) - { - if (line.find("") != line.npos) - { - xmlPreamble += line + "\n"; - } - else if (line.size() == 0) - { - xmlPreamble += "\n"; - } - else if (line.find("") - { - break; - } - } - ofs.close(); - ifs.close(); - -#if defined OLD_STYLE_XERCES_PARSER - DOMDocument* document = parseInputDocument(tmpFileStr.str().c_str(),false); -#else - DOMDocument* document = buildDOMDocument(tmpFileStr.str().c_str(),false); -#endif - if (document == 0) - { - std::cerr - << "hddm-cpp : Error parsing HDDM document, " - << "cannot continue" << std::endl; - return 1; - } - unlink(tmpFileStr.str().c_str()); - - DOMElement* rootEl = document->getDocumentElement(); - XtString rootS(rootEl->getTagName()); - if (rootS != "HDDM") - { - std::cerr - << "hddm-cpp error: root element of input document is " - << "\"" << rootS << "\", expected \"HDDM\"" - << std::endl; - return 1; - } - - XtString classS(rootEl->getAttribute(X("class"))); - classPrefix = classS; - - XtString hname; - if (verifyOnly) - { - hname = "/dev/null"; - } - else if (hFilename.size()) - { - hname = hFilename + ".hpp"; - } - else - { - hname = "hddm_" + classPrefix + ".hpp"; - } - - CodeBuilder builder; - builder.hFile.open(hname.c_str()); - if (! builder.hFile.is_open()) - { - std::cerr - << "hddm-cpp error: unable to open output file " - << hname << std::endl; - return 1; - } - - XtString cname; - if (verifyOnly) - { - cname = "/dev/null"; - } - else if (hFilename.size()) - { - cname = hFilename + "++.cpp"; - } - else - { - cname = "hddm_" + classPrefix + "++.cpp"; - } - - builder.cFile.open(cname.c_str()); - if (! builder.cFile.is_open()) - { - std::cerr - << "hddm-cpp error: unable to open output file " - << cname << std::endl; - return 1; - } - - builder.hFile << - "/*\n" - " * hddm_" << classPrefix << ".hpp - DO NOT EDIT THIS FILE\n" - " *\n" - " * This file was generated automatically by hddm-cpp from the file\n" - << " * " << xmlFile << std::endl << - "\n" - " * This header file defines the c++ classes that hold the data\n" - " * described in the data model (from " << xmlFile << "). \n" - " *\n" - " * The hddm data model tool set was written by\n" - " * Richard Jones, University of Connecticut.\n" - " *\n" - " * For more information see the documentation at\n" - " * http://github.com/rjones30/HDDM\n" - " *\n" - " */\n" - "\n" - "#ifndef SAW_" << classPrefix << "_HDDM\n" - "#define SAW_" << classPrefix << "_HDDM\n" - "\n" - "#include \n" - "#include \n" - "#include \n" - "#include \n" - "#include \n" - "#include \n" - "#include \n" - "#include \n" - "#include \n" - "#include \n" - "#include \n" - "#include \n" - "#include \n" - "#include \n" - "#include \n" - "#include \n" - "#include \n" - "\n" - "#ifdef HDF5_SUPPORT\n" - "#include \n" - "#include \n" - "#include \n" - "#include \n" - "#include \n" - "#include \n" - "#endif\n" - "\n" - "#define MY_SETUP thread_private_data *my_private = lookup_private_data();\n" - "#define MY(VAR) my_private->m_ ## VAR\n" - "\n" - "namespace hddm_" << classPrefix << " {\n" - "\n" - "const int k_default_status = 0x0;\n" - "const int k_bits_compression = 0xf0;\n" - "const int k_no_compression = 0x00;\n" - "const int k_z_compression = 0x10;\n" - "const int k_bz2_compression = 0x20;\n" - "const int k_bits_integrity = 0x0f;\n" - "const int k_no_integrity = 0x00;\n" - "const int k_crc32_integrity = 0x01;\n" - "const int k_bits_randomaccess = 0xf00;\n" - "const int k_can_reposition = 0x100;\n" - "\n" - "enum hddm_type {\n" - " k_hddm_unknown,\n" - " k_hddm_int,\n" - " k_hddm_long,\n" - " k_hddm_float,\n" - " k_hddm_double,\n" - " k_hddm_boolean,\n" - " k_hddm_string,\n" - " k_hddm_anyURI,\n" - " k_hddm_Particle_t\n" - "};\n" - "\n" - "#ifdef HDF5_SUPPORT\n" - "#define HDF5_DEFAULT_CHUNK_SIZE 100\n" - "// gzip standard compression provided by hdf5\n" - "const H5Z_filter_t k_hdf5_gzip_filter(H5Z_FILTER_DEFLATE);\n" - "// szip standard compression provided by hdf5\n" - "const H5Z_filter_t k_hdf5_szip_filter(H5Z_FILTER_SZIP);\n" - "// bzip2 lossless compression used by PyTables\n" - "const H5Z_filter_t k_hdf5_bzip2_plugin(307);\n" - "// Blosc lossless compression used by PyTables\n" - "const H5Z_filter_t k_hdf5_blosc_plugin(32001);\n" - "// bitshuffle shuffle filter at bit level instead of byte level\n" - "const H5Z_filter_t k_hdf5_bshuf_plugin(32008);\n" - "// JPEG-XR compression filter used in jpeg images\n" - "const H5Z_filter_t k_hdf5_jpeg_plugin(32007);\n" - "// LZ4 fast lossless compression algorithm\n" - "const H5Z_filter_t k_hdf5_lz4_plugin(32004);\n" - "// LZF fast lossless compression used by H5Py project\n" - "const H5Z_filter_t k_hdf5_lzf_plugin(32000);\n" - "// modified LZMA compression filter (MAFISC)\n" - "const H5Z_filter_t k_hdf5_lzma_plugin(32002);\n" - "// zfp rate, accuracy, or precision bounded compression for arrays of floats\n" - "const H5Z_filter_t k_hdf5_zfp_plugin(32013);\n" - "#endif\n" - "\n" - "class HDDM;\n" - "class istream;\n" - "class ostream;\n" - "\n" - "class streamable {\n" - " public:\n" - " virtual ~streamable() {}\n" - " virtual void streamer(istream &istr) {}\n" - " virtual void streamer(ostream &ostr) {}\n" - "};\n" - "\n" - "class streamposition {\n" - " public:\n" - " uint64_t block_start;\n" - " uint32_t block_offset;\n" - " uint32_t block_status;\n" - " streamposition();\n" - " streamposition(uint64_t start, uint32_t offset, uint32_t status);\n" - " bool operator==(const streamposition src) const {\n" - " return (block_start == src.block_start &&\n" - " block_offset == src.block_offset &&\n" - " block_status == src.block_status);\n" - " }\n" - " bool operator!=(const streamposition src) const {\n" - " return !(*this == src);\n" - " }\n" - " bool operator>(const streamposition src) const {\n" - " return (block_start > src.block_start ||\n" - " (block_start == src.block_start &&\n" - " block_offset > src.block_offset));\n" - " }\n" - " bool operator>=(const streamposition src) const {\n" - " return (*this > src || *this == src);\n" - " }\n" - " bool operator<(const streamposition src) const {\n" - " return !(*this >= src);\n" - " }\n" - " bool operator<=(const streamposition src) const {\n" - " return !(*this > src);\n" - " }\n" - "};\n" - "\n" - "class threads {\n" - " public:\n" - " static thread_local int ID;\n" - " static int getID() {\n" - " // protected access to the ID tls data member\n" - " if (ID == 0) {\n" - " if (ID >= max_threads) {\n" - " throw std::runtime_error(\"hddm_" - << classPrefix << "::threads::getID - \"\n" - " \"thread count exceeds max_threads\");\n" - " }\n" - " ID = ++next_unique_ID;\n" - " }\n" - " return ID;\n" - " }\n" - " static const int max_threads = 999;\n" - " protected:\n" - " static std::atomic next_unique_ID;\n" - "};\n" - "\n" - "class istreambuffer : public std::streambuf {\n" - " public:\n" - " istreambuffer(char* buffer, std::streamsize bufferLength) {\n" - " setg(buffer, buffer, buffer + bufferLength);\n" - " }\n" - "\n" - " std::streampos tellg() {\n" - " return gptr() - eback();\n" - " }\n" - "\n" - " void seekg(std::streampos pos) {\n" - " reset();\n" - " gbump(pos);\n" - " }\n" - "\n" - " int size() {\n" - " return egptr() - gptr();\n" - " }\n" - "\n" - " void reset() {\n" - " char *gbegin = eback();\n" - " char *gend = egptr();\n" - " setg(gbegin, gbegin, gend);\n" - " }\n" - "\n" - " char *getbuf() {\n" - " return eback();\n" - " }\n" - "};\n" - "\n" - "class ostreambuffer : public std::streambuf {\n" - " public:\n" - " ostreambuffer(char* buffer, std::streamsize bufferLength) {\n" - " setp(buffer, buffer + bufferLength);\n" - " }\n" - "\n" - " std::streampos tellp() {\n" - " return pptr() - pbase();\n" - " }\n" - "\n" - " void seekp(std::streampos pos) {\n" - " reset();\n" - " pbump(pos);\n" - " }\n" - "\n" - " int size() {\n" - " return pptr() - pbase();\n" - " }\n" - "\n" - " void reset() {\n" - " char *pbegin = pbase();\n" - " char *pend = epptr();\n" - " setp(pbegin, pend);\n" - " }\n" - "\n" - " char *getbuf() {\n" - " return pbase();\n" - " }\n" - "};\n" - "\n" - "class ostream {\n" - " public:\n" - " ostream(std::ostream &src);\n" - " ~ostream();\n" - " ostream &operator<<(HDDM &record);\n" - " int getCompression() const;\n" - " void setCompression(int flags);\n" - " int getIntegrityChecks() const;\n" - " void setIntegrityChecks(int flags);\n" - " streamposition getPosition();\n" - " int getBytesWritten() const;\n" - " int getRecordsWritten() const;\n" - " //protected:\n" - " xstream::xdr::ostream *getXDRostream() {\n" - " return my_thread_private[threads::ID]->m_xstr;\n" - " }\n" - " ostream &operator<<(streamable &object);\n" - " private:\n" - " void configure_streambufs();\n" - " void update_streambufs();\n" - " void lock_streambufs();\n" - " void unlock_streambufs();\n" - " std::ostream &m_ostr;\n" - " std::atomic m_status_bits;\n" - " pthread_mutex_t m_streambuf_mutex;\n" - "\n" - " typedef struct {\n" - " xstream::xdr::ostream *m_xstr;\n" - " std::ostream *m_ostr;\n" - " ostreambuffer *m_sbuf;\n" - " std::streambuf *m_xcmp;\n" - " char *m_event_buffer;\n" - " int m_event_buffer_size;\n" - " std::streampos m_last_start;\n" - " std::streamoff m_last_offset;\n" - " int m_status_bits;\n" - " int m_mutex_lock;\n" - " int m_bytes_written;\n" - " int m_records_written;\n" - " } thread_private_data;\n" - "\n" - " thread_private_data *my_thread_private[threads::max_threads];\n" - " thread_private_data *lookup_private_data();\n" - " void init_private_data();\n" - "};\n" - "\n" - "class codon {\n" - " public:\n" - " codon(): m_order(0) {}\n" - " int m_order;\n" - " std::string m_tagname;\n" - " std::vector m_sequence;\n" - " std::deque m_target;\n" - "};\n" - "\n" - "typedef std::vector chromosome;\n" - "\n" - "class istream {\n" - " public:\n" - " istream(std::istream &src);\n" - " ~istream();\n" - " istream &operator>>(HDDM &record);\n" - " void skip(int count);\n" - " int getCompression() const;\n" - " int getIntegrityChecks() const;\n" - " streamposition getPosition();\n" - " void setPosition(const streamposition &pos);\n" - " int getBytesRead() const;\n" - " int getRecordsRead() const;\n" - " bool eof();\n" - " bool operator!();\n" - " operator void*();\n" - " //protected:\n" - " void reset_sequencer();\n" - " void sequencer(streamable &object);\n" - " istream &operator>>(streamable &object);\n" - " xstream::xdr::istream *getXDRistream() {\n" - " return my_thread_private[threads::ID]->m_xstr;\n" - " }\n" - "\n" - " private:\n" - " std::string m_documentString;\n" - " chromosome synthesize(const std::string &src, int p_src,\n" - " const std::string &ref, int p_ref);\n" - " int getTag(const std::string &src, int p_src, std::string &tag, int &level);\n" - " int getEndTag(const std::string &src, int p_src, const std::string &tag);\n" - " void collide(const std::string &itag, const std::string &rtag);\n" - " void configure_streambufs();\n" - " void update_streambufs();\n" - " void lock_streambufs();\n" - " void unlock_streambufs();\n" - " std::istream &m_istr;\n" - " std::atomic m_status_bits;\n" - " pthread_mutex_t m_streambuf_mutex;\n" - " int m_leftovers[100];\n" - "\n" - " typedef struct {\n" - " codon m_genome;\n" - " codon *m_codon;\n" - " int m_sequencing;\n" - " xstream::xdr::istream *m_xstr;\n" - " std::istream *m_istr;\n" - " istreambuffer *m_sbuf;\n" - " std::streambuf *m_xcmp;\n" - " int m_events_to_skip;\n" - " char *m_event_buffer;\n" - " int m_event_buffer_size;\n" - " int m_event_size;\n" - " std::streampos m_last_start;\n" - " std::streamoff m_last_offset;\n" - " std::streamoff m_next_start;\n" - " int m_status_bits;\n" - " int m_mutex_lock;\n" - " int m_bytes_read;\n" - " int m_records_read;\n" - " bool m_hit_eof;\n" - " } thread_private_data;\n" - "\n" - " thread_private_data *my_thread_private[threads::max_threads];\n" - " thread_private_data *lookup_private_data();\n" - " void init_private_data();\n" - "};\n" - "\n" - "template class HDDM_ElementList;\n" - "\n" - "class HDDM_Element: public streamable {\n" - " public:\n" - " virtual ~HDDM_Element() {}\n" - " virtual void clear() {}\n" - " virtual const void *getAttribute(const std::string &name,\n" - " hddm_type *atype=0) const {\n" - " return 0;\n" - " }\n" - " virtual std::string toString(int indent=0) {\n" - " return \"bad apple\";\n" - " }\n" - " virtual std::string toXML(int indent=0) {\n" - " return \"\";\n" - " }\n" - " friend class HDDM_ElementList;\n" - " protected:\n" - " HDDM_Element() : m_parent(0), m_host(0), m_owner(0) {}\n" - " HDDM_Element(HDDM_Element *parent, int owner=0)\n" - " : m_parent(parent),\n" - " m_host((parent != 0)? parent->m_host : 0),\n" - " m_owner(owner)\n" - " {}\n" - " HDDM_Element(const HDDM_Element &src)\n" - " : m_parent(src.m_parent),\n" - " m_host(src.m_host),\n" - " m_owner(0)\n" - " {}\n" - " HDDM_Element *m_parent;\n" - " HDDM *m_host;\n" - " int m_owner;\n" - "};\n" - "\n" - "template \n" - "class HDDM_ElementList: public streamable {\n" - " public:\n" - " HDDM_ElementList() : m_host_plist(0), m_parent(0) {}\n" - " HDDM_ElementList(typename std::list *plist,\n" - " typename std::list::iterator begin,\n" - " typename std::list::iterator end,\n" - " HDDM_Element *parent=0)\n" - " : m_host_plist(plist),\n" - " m_first_iter(begin),\n" - " m_last_iter(end),\n" - " m_parent(parent),\n" - " m_ref(0)\n" - " {\n" - " for (m_size = 0; begin != end; ++m_size, ++begin) {}\n" - " if (m_size) {\n" - " --m_last_iter;\n" - " }\n" - " }\n" - "\n" - " HDDM_ElementList(const HDDM_ElementList &src)\n" - " : m_host_plist(src.m_host_plist),\n" - " m_first_iter(src.m_first_iter),\n" - " m_last_iter(src.m_last_iter),\n" - " m_parent(src.m_parent),\n" - " m_size(src.m_size),\n" - " m_ref(src.m_ref)\n" - " {}\n" - "\n" - " bool empty() const { return (m_size == 0); }\n" - " int size() const { return m_size; }\n" - " T &front() const { return *m_first_iter; }\n" - " T &back() const { return *m_last_iter; }\n" - " T &operator()() { return *m_first_iter; }\n" - " T &operator()(int index) {\n" - " if (index == 0) {\n" - " return *m_first_iter;\n" - " }\n" - " else if (index == -1) {\n" - " return *m_last_iter;\n" - " }\n" - " else if (index > 0) {\n" - " return *(m_first_iter + index);\n" - " }\n" - " else {\n" - " return *(m_last_iter + (++index));\n" - " }\n" - " }\n" - "\n" - " class iterator: public std::list::iterator {\n" - " public:\n" - " iterator() {}\n" - " iterator(typename std::list::iterator src)\n" - " : std::list::iterator(src) {}\n" - "\n" - " T *operator->() const { \n" - " return *(typename std::list::iterator)(*this);\n" - " }\n" - "\n" - " T &operator*() const {\n" - " return **(typename std::list::iterator)(*this);\n" - " }\n" - "\n" - " iterator operator+=(int offset) {\n" - " if (offset > 0) {\n" - " for (int i=0; ioffset; --i, --(*this)) {}\n" - " }\n" - " return *this;\n" - " }\n" - "\n" - " iterator operator-=(int offset) {\n" - " if (offset > 0) {\n" - " for (int i=0; ioffset; --i, ++(*this)) {}\n" - " }\n" - " return *this;\n" - " }\n" - "\n" - " iterator operator+(int offset) const {\n" - " iterator iter(*this);\n" - " return iter += offset;\n" - " }\n" - "\n" - " iterator operator-(int offset) const {\n" - " iterator iter(*this);\n" - " return iter -= offset;\n" - " }\n" - "\n" - " int operator-(iterator iter) const {\n" - " if (*this == iter) {\n" - " return 0;\n" - " }\n" - " iterator iter2(iter);\n" - " for (int n=1; n < INT_MAX; ++n) {\n" - " if (++iter == *this) {\n" - " return n;\n" - " }\n" - " else if (--iter2 == *this) {\n" - " return -n;\n" - " }\n" - " }\n" - " return INT_MAX;\n" - " }\n" - " void *address() const {\n" - " return &*(typename std::list::iterator)(*this);\n" - " }\n" - " };\n" - "\n" - " class const_iterator: public std::list::const_iterator {\n" - " public:\n" - " const_iterator() {}\n" - " const_iterator(const typename std::list::const_iterator src)\n" - " : std::list::const_iterator(src) {}\n" - "\n" - " const_iterator(const typename std::list::iterator src)\n" - " : std::list::const_iterator(src) {}\n" - "\n" - " const T *operator->() const { \n" - " return *(typename std::list::const_iterator)(*this);\n" - " }\n" - "\n" - " const T &operator*() const { \n" - " return **(typename std::list::const_iterator)(*this);\n" - " }\n" - "\n" - " const const_iterator operator+=(int offset) {\n" - " if (offset > 0) {\n" - " for (int i=0; ioffset; --i, --(*this)) {}\n" - " }\n" - " return *this;\n" - " }\n" - "\n" - " const const_iterator operator-=(int offset) {\n" - " if (offset > 0) {\n" - " for (int i=0; i 0) {\n" - " for (int i=0; i>offset; --i, ++(*this)) {}\n" - " }\n" - " return *this;\n" - " }\n" - "\n" - " const const_iterator operator+(int offset) const {\n" - " const_iterator iter(*this);\n" - " return iter += offset;\n" - " }\n" - "\n" - " const const_iterator operator-(int offset) const {\n" - " const_iterator iter(*this);\n" - " return iter -= offset;\n" - " }\n" - "\n" - " int operator-(const_iterator iter) const {\n" - " if (*this == iter) {\n" - " return 0;\n" - " }\n" - " const_iterator iter2(iter);\n" - " for (int n=1; n < m_size; ++n) {\n" - " if (++iter == *this) {\n" - " return n;\n" - " }\n" - " else if (--iter2 == *this) {\n" - " return -n;\n" - " }\n" - " }\n" - " return m_size;\n" - " }\n" - " void *address() const {\n" - " return &*(typename std::list::iterator)(*this);\n" - " }\n" - " };\n" - "\n" - " iterator begin() const { return m_first_iter; }\n" - " iterator end() const { return (m_size)? m_last_iter + 1 : m_last_iter; }\n" - " void clear() { del(); }\n" - "\n" - " HDDM_ElementList add(int count=1, int start=-1) {\n" - " if (m_parent == 0) {\n" - " throw std::runtime_error(\"HDDM_ElementList error - \"\n" - " \"attempt to add to immutable list\");\n" - " }\n" - " iterator it = insert(start, count);\n" - " typename std::list::iterator iter(it);\n" - " for (int n=0; n= 0) {\n" - " iter_end = iter_begin + count;\n" - " }\n" - " }\n" - " else {\n" - " iter_begin += start;\n" - " if (count >= 0) {\n" - " iter_end = iter_begin + count;\n" - " }\n" - " }\n" - " typename std::list::iterator iter;\n" - " for (iter = iter_begin; iter != iter_end; ++iter) {\n" - " if ((*iter)->m_owner)\n" - " delete *iter;\n" - " else\n" - " (*iter)->clear();\n" - " }\n" - " erase(start, count);\n" - " }\n" - "\n" - " HDDM_ElementList slice(int first=0, int last=-1) {\n" - " int n1 = (first < 0)? first + m_size : first;\n" - " int n2 = (last < 0)? last + m_size + 1 : last + 1;\n" - " int count = n2 - n1;\n" - " iterator iter_begin;\n" - " if (first >= 0)\n" - " iter_begin = begin() + first;\n" - " else\n" - " iter_begin = end() + first;\n" - " iterator iter_end(iter_begin + count);\n" - " return HDDM_ElementList(m_host_plist, iter_begin, iter_end);\n" - " }\n" - " void debug_print() {\n" - " std::cout << \"HDDM_ElementList contents printout:\"\n" - " << std::endl\n" - " << \" this = \" << &*this << std::endl\n" - " << \" m_parent = \" << m_parent << std::endl\n" - " << \" m_host_plist = \" << m_host_plist << std::endl\n" - " << \" m_size = \" << m_size << std::endl\n" - " << \" m_ref = \" << m_ref << std::endl\n" - " << \" m_first_iter = \" << m_first_iter.address()\n" - " << std::endl\n" - " << \" m_last_iter = \" << m_last_iter.address()\n" - " << std::endl;\n" - " }\n" - "\n" - " void streamer(istream &istr) {\n" - " clear();\n" - " int size;\n" - " *istr.getXDRistream() >> size;\n" - " if (size) {\n" - " iterator iter = add(size).begin();\n" - " for (int n=0; n < size; ++n, ++iter) {\n" - " istr.sequencer(*iter);\n" - " }\n" - " }\n" - " istr.reset_sequencer();\n" - " }\n" - "\n" - " void streamer(ostream &ostr) {\n" - " if (m_size) {\n" - " *ostr.getXDRostream() << m_size;\n" - " for (iterator iter = begin(); iter != end(); ++iter) {\n" - " iter->streamer(ostr);\n" - " }\n" - " }\n" - " }\n" - " std::string toString(int indent=0) {\n" - " std::string result;\n" - " if (m_size) {\n" - " for (iterator iter = begin(); iter != end(); ++iter) {\n" - " result += iter->toString(indent);\n" - " }\n" - " }\n" - " return result;\n" - " }\n" - " std::string toXML(int indent=0) {\n" - " std::string result;\n" - " if (m_size) {\n" - " for (iterator iter = begin(); iter != end(); ++iter) {\n" - " result += iter->toXML(indent);\n" - " }\n" - " }\n" - " return result;\n" - " }\n" - "\n" - " private:\n" - " iterator insert(int start, int count) {\n" - " if (m_size == 0) {\n" - " if (count > 0) {\n" - " if (m_first_iter == m_host_plist->begin()) {\n" - " m_host_plist->insert(m_first_iter,count,(T*)0);\n" - " m_first_iter = m_host_plist->begin();\n" - " }\n" - " else {\n" - " m_host_plist->insert(m_first_iter--,count,(T*)0);\n" - " ++m_first_iter;\n" - " }\n" - " --m_last_iter;\n" - " m_size = count;\n" - " }\n" - " return m_first_iter;\n" - " }\n" - " else if (start == 0) {\n" - " if (count > 0) {\n" - " if (m_first_iter == m_host_plist->begin()) {\n" - " m_host_plist->insert(m_first_iter,count,(T*)0);\n" - " m_first_iter = m_host_plist->begin();\n" - " }\n" - " else {\n" - " m_host_plist->insert(m_first_iter--,count,(T*)0);\n" - " ++m_first_iter;\n" - " }\n" - " m_size += count;\n" - " }\n" - " return m_first_iter;\n" - " }\n" - " else if (start == -1) {\n" - " if (count > 0) {\n" - " iterator pos(m_last_iter);\n" - " m_host_plist->insert(++m_last_iter,count,(T*)0);\n" - " --m_last_iter;\n" - " m_size += count;\n" - " return ++pos;\n" - " }\n" - " return m_last_iter;\n" - " }\n" - " else if (start > 0) {\n" - " if (count > 0) {\n" - " iterator pos(m_first_iter);\n" - " iterator pos2(pos += start-1);\n" - " m_host_plist->insert(++pos,count,(T*)0);\n" - " if (m_last_iter == pos2) {\n" - " m_last_iter = --pos;\n" - " }\n" - " m_size += count;\n" - " return ++pos2;\n" - " }\n" - " return m_first_iter + start;\n" - " }\n" - " else {\n" - " if (count > 0) {\n" - " iterator pos(m_last_iter);\n" - " iterator pos2(pos += start+1);\n" - " m_host_plist->insert(++pos,count,(T*)0);\n" - " m_size += count;\n" - " return ++pos2;\n" - " }\n" - " return m_last_iter + (start+1);\n" - " }\n" - " }\n" - "\n" - " iterator erase(int start, int count) {\n" - " start = (start < 0)? start + m_size :\n" - " (start < m_size)? start : m_size;\n" - " count = (count == -1)? m_size - start : count;\n" - " assert(start >= 0 && count > 0 && start + count <= m_size);\n" - " if (count == m_size) {\n" - " m_first_iter = m_host_plist->erase(m_first_iter,++m_last_iter);\n" - " m_last_iter = m_first_iter;\n" - " m_size = 0;\n" - " return m_first_iter;\n" - " }\n" - " else if (start > 0 && count + start == m_size) {\n" - " iterator pos(m_first_iter + start);\n" - " m_last_iter = m_host_plist->erase(pos,pos+count);\n" - " iterator pos2(m_last_iter);\n" - " if (m_last_iter != m_first_iter) {\n" - " --m_last_iter;\n" - " }\n" - " m_size -= count;\n" - " return pos2;\n" - " }\n" - " else if (start == 0) {\n" - " iterator pos(m_first_iter);\n" - " m_first_iter = m_host_plist->erase(pos,pos+count);\n" - " m_size -= count;\n" - " return m_first_iter;\n" - " }\n" - " else {\n" - " iterator pos(m_first_iter + start);\n" - " iterator pos2 = m_host_plist->erase(pos,pos+count);\n" - " m_size -= count;\n" - " return pos2;\n" - " }\n" - " }\n" - "\n" - " public:\n" - " void inflate(HDDM *host, std::list *host_plist, HDDM_Element *parent) {\n" - " m_parent = parent;\n" - " m_host_plist = host_plist;\n" - " m_first_iter = m_host_plist->begin();\n" - " m_first_iter += m_ref;\n" - " m_last_iter = m_first_iter;\n" - " m_last_iter += m_size;\n" - " for (iterator iter = m_first_iter; iter != m_last_iter; ++iter) {\n" - " iter->m_parent = parent;\n" - " iter->m_host = host;\n" - " }\n" - " if (m_size) {\n" - " --m_last_iter;\n" - " }\n" - " }\n" - " void deflate() {\n" - " iterator iter = m_host_plist->begin();\n" - " for (m_ref=0; iter != m_first_iter; ++iter, ++m_ref) {}\n" - " }\n" - "\n" - " protected:\n" - " std::list *m_host_plist;\n" - " iterator m_first_iter;\n" - " iterator m_last_iter;\n" - " HDDM_Element *m_parent;\n" - " public:\n" - " int m_size;\n" - " int m_ref;\n" - "};\n" - "\n" - "template \n" - "class HDDM_ElementLink: public HDDM_ElementList {\n" - " public:\n" - " HDDM_ElementLink() {}\n" - " HDDM_ElementLink(typename std::list *plist,\n" - " typename std::list::iterator begin,\n" - " typename std::list::iterator end,\n" - " HDDM_Element *parent=0)\n" - " : HDDM_ElementList(plist,begin,end,parent)\n" - " {}\n" - " HDDM_ElementLink(const HDDM_ElementList &src)\n" - " : HDDM_ElementList(src)\n" - " {}\n" - "\n" - " void streamer(istream &istr) {\n" - " HDDM_ElementList::clear();\n" - " HDDM_ElementList::add().begin()->streamer(istr);\n" - " }\n" - "\n" - " void streamer(ostream &ostr) {\n" - " if (HDDM_ElementList::m_size) {\n" - " HDDM_ElementList::begin()->streamer(ostr);\n" - " }\n" - " }\n" - "};\n" - "\n" - "#ifdef HDF5_SUPPORT\n" - "typedef struct {\n" - " size_t len;\n" - " void *p;\n" - "} hdf5_hvl_t;\n" - "#endif\n" - "\n" - ; - - builder.cFile << - "/*\n" - " * hddm_" << classPrefix << "++.cpp - DO NOT EDIT THIS FILE\n" - " *\n" - " * This file was generated automatically by hddm-cpp from the file\n" - << " * " << xmlFile << std::endl << - "\n" - " * This c++ source implements the methods for the classes \n" - " * described in the data model (from " << xmlFile << "). \n" - " *\n" - " * The hddm data model tool set was written by\n" - " * Richard Jones, University of Connecticut.\n" - " *\n" - " * For more information see the documentation at\n" - " * http://github.com/rjones30/HDDM\n" - " */\n" - "\n" - "#include \n" - "#include \"hddm_" << classPrefix << ".hpp\"\n" - "\n" - "#ifndef _FILE_OFFSET_BITS\n" - "# define _FILE_OFFSET_BITS 64\n" - "#endif\n" - "\n" - "using namespace hddm_" << classPrefix << ";\n" - "\n" - "std::atomic threads::next_unique_ID(0);\n" - "thread_local int threads::ID(0);\n" - "\n" - "static int tags_match(const std::string &a, const std::string &b)\n" - "{\n" - " if (a == b) {\n" - " return true;\n" - " }\n" - " else if (a.find(\"\") {\n" - " break;\n" - " }\n" - " }\n" - " if (src.bad()) {\n" - " throw std::runtime_error(\"hddm_" + classPrefix + - "::istream::istream error - hddm header invalid\");\n" - " }\n" - " pthread_mutex_init(&m_streambuf_mutex,0);\n" - " for (int i=0; i\n" - " set_new_position(pos.block_start, pos.block_offset);\n" - " }\n" - " else if (MY(status_bits) & k_bz2_compression) {\n" - " ((xstream::bz::istreambuf*)MY(xcmp))->\n" - " set_new_position(pos.block_start, pos.block_offset);\n" - " }\n" - " }\n" - " else {\n" - " MY(next_start) = pos.block_start;\n" - " }\n" - "}\n" - "\n" - "void istream::update_streambufs() {\n" - " MY_SETUP\n" - " if ((int)m_status_bits != MY(status_bits)) {\n" - " configure_streambufs();\n" - " }\n" - "}\n" - "\n" - "void istream::configure_streambufs() {\n" - " MY_SETUP\n" - " int oldcmp = MY(status_bits) & k_bits_compression;\n" - " int newcmp = (int)m_status_bits & k_bits_compression;\n" - " if (oldcmp != newcmp) {\n" - " if (oldcmp != k_no_compression) {\n" - " MY(istr)->rdbuf(m_istr.rdbuf());\n" - " delete MY(xcmp);\n" - " MY(xcmp) = 0;\n" - " }\n" - " if (newcmp == k_z_compression) {\n" - " //std::cerr << \"input switched on z compression\" << std::endl;\n" - " MY(xcmp) = new xstream::z::istreambuf(m_istr.rdbuf(), m_leftovers,\n" - " sizeof(m_leftovers));\n" - " MY(istr)->rdbuf(MY(xcmp));\n" - " }\n" - " else if (newcmp == k_bz2_compression) {\n" - " //std::cerr << \"input switched on bz2 compression\" << std::endl;\n" - " MY(xcmp) = new xstream::bz::istreambuf(m_istr.rdbuf(), m_leftovers,\n" - " sizeof(m_leftovers));\n" - " MY(istr)->rdbuf(MY(xcmp));\n" - " }\n" - " else if (newcmp != k_no_compression) {\n" - " throw std::runtime_error(\"hddm_" - << classPrefix << "::istream::configure_streambufs error - \"\n" - " \"unrecognized compression flag requested.\");\n" - " }\n" - " }\n" - " MY(status_bits) = m_status_bits;\n" - "}\n" - "\n" - "void istream::lock_streambufs() {\n" - " MY_SETUP\n" - " if (MY(mutex_lock) != 0) {\n" - " unlock_streambufs();\n" - " throw std::runtime_error(\"hddm_" - << classPrefix << "::istream::lock_streambufs error - \"\n" - " \"mutex lock requested when lock already held.\");\n" - " }\n" - " if ((MY(status_bits) & k_bits_compression) == k_no_compression) {\n" - " pthread_mutex_lock(&m_streambuf_mutex);\n" - " MY(mutex_lock) = 1;\n" - " }\n" - " else if ((MY(status_bits) & k_bits_compression) == k_z_compression) {\n" - " ((xstream::z::istreambuf*)MY(xcmp))->set_streambuf_mutex(&m_streambuf_mutex);\n" - " MY(mutex_lock) = 2;\n" - " }\n" - " else if ((MY(status_bits) & k_bits_compression) == k_bz2_compression) {\n" - " ((xstream::bz::istreambuf*)MY(xcmp))->set_streambuf_mutex(&m_streambuf_mutex);\n" - " MY(mutex_lock) = 3;\n" - " }\n" - " else {\n" - " MY(mutex_lock) = -1;\n" - " }\n" - "}\n" - "\n" - "void istream::unlock_streambufs() {\n" - " MY_SETUP\n" - " if (MY(mutex_lock) == 0) {\n" - " throw std::runtime_error(\"hddm_" - << classPrefix << "::istream::unlock_streambufs error - \"\n" - " \"mutex unlock requested when lock not held.\");\n" - " }\n" - " else if (MY(mutex_lock) == 1) {\n" - " pthread_mutex_unlock(&m_streambuf_mutex);\n" - " }\n" - " else if (MY(mutex_lock) == 2) {\n" - " ((xstream::z::istreambuf*)MY(xcmp))->set_streambuf_mutex(0);\n" - " }\n" - " else if (MY(mutex_lock) == 3) {\n" - " ((xstream::bz::istreambuf*)MY(xcmp))->set_streambuf_mutex(0);\n" - " }\n" - " MY(mutex_lock) = 0;\n" - "}\n" - "\n" - "istream &istream::operator>>(HDDM &record) {\n" - " MY_SETUP\n" - " while (1 == 1) {\n" - " lock_streambufs();\n" - " MY(event_size) = 0;\n" - " while (MY(event_size) == 0) {\n" - " update_streambufs();\n" - " if (MY(status_bits) & (k_bz2_compression | k_z_compression)) {\n" - " if (MY(status_bits) & k_can_reposition) {\n" - " MY(istr)->clear();\n" - " MY(istr)->read(MY(event_buffer),4);\n" - " MY(bytes_read) += MY(istr)->gcount();\n" - " if (!MY(istr)->good()) {\n" - " unlock_streambufs();\n" - " MY(hit_eof) = 1;\n" - " return *this;\n" - " }\n" - " if (MY(status_bits) & k_bz2_compression) {\n" - " MY(last_start) = dynamic_cast\n" - " (MY(xcmp))->get_block_start();\n" - " MY(last_offset) = dynamic_cast\n" - " (MY(xcmp))->get_block_offset();\n" - " }\n" - " else {\n" - " MY(last_start) = dynamic_cast\n" - " (MY(xcmp))->get_block_start();\n" - " MY(last_offset) = dynamic_cast\n" - " (MY(xcmp))->get_block_offset();\n" - " }\n" - " MY(last_offset) -= 4;\n" - " }\n" - " else {\n" - " MY(last_start) = 0;\n" - " MY(last_offset) = 0;\n" - " }\n" - " }\n" - " else {\n" - " if (MY(next_start) > 0) {\n" - " m_istr.seekg(MY(next_start), std::ios_base::beg);\n" - " MY(istr)->clear();\n" - " MY(last_start) = MY(next_start);\n" - " MY(last_offset) = 0;\n" - " MY(next_start) = 0;\n" - " }\n" - " else {\n" - " MY(last_start) = m_istr.tellg();\n" - " MY(last_offset) = 0;\n" - " }\n" - " MY(istr)->read(MY(event_buffer),4);\n" - " MY(bytes_read) += MY(istr)->gcount();\n" - " if (!MY(istr)->good()) {\n" - " unlock_streambufs();\n" - " MY(hit_eof) = 1;\n" - " return *this;\n" - " }\n" - " }\n" - " MY(hit_eof) = 0;\n" - " MY(sbuf)->reset();\n" - " *MY(xstr) >> MY(event_size);\n" - " if (MY(event_size) == 1) {\n" - " MY(istr)->read(MY(event_buffer)+4,4);\n" - " MY(bytes_read) += MY(istr)->gcount();\n" - " if (!MY(istr)->good()) {\n" - " unlock_streambufs();\n" - " throw std::runtime_error(\"hddm_" - << classPrefix << "::istream::operator>> error -\"\n" - " \" read error on token input!\");\n" - " }\n" - " int size;\n" - " *MY(xstr) >> size;\n" - " MY(istr)->read(MY(event_buffer)+8,size);\n" - " MY(bytes_read) += MY(istr)->gcount();\n" - " if (!MY(istr)->good()) {\n" - " unlock_streambufs();\n" - " throw std::runtime_error(\"hddm_" - << classPrefix << "::istream::operator>> error -\"\n" - " \" read error on token input!\");\n" - " }\n" - " int format, flags;\n" - " *MY(xstr) >> format >> flags;\n" - " if (format != 0) {\n" - " unlock_streambufs();\n" - " throw std::runtime_error(\"hddm_" - << classPrefix << "::istream::operator>> error - \"\n" - " \"unsupported compression format!\");\n" - " }\n" - " m_status_bits.store(flags);\n" - " MY(event_size) = 0;\n" - " }\n" - " }\n" - " if (MY(event_size)+8 > MY(event_buffer_size)) {\n" - " delete MY(xstr);\n" - " delete MY(sbuf);\n" - " char *newbuf = new char[MY(event_buffer_size) = MY(event_size)+1000];\n" - " MY(sbuf) = new istreambuffer(newbuf, MY(event_buffer_size));\n" - " MY(xstr) = new xstream::xdr::istream(MY(sbuf));\n" - " memcpy(newbuf,MY(event_buffer),4);\n" - " delete [] MY(event_buffer);\n" - " MY(event_buffer) = newbuf;\n" - " }\n" - " MY(istr)->read(MY(event_buffer)+4,MY(event_size));\n" - " MY(bytes_read) += MY(istr)->gcount();\n" - " MY(records_read)++;\n" - " if (!MY(istr)->good()) {\n" - " unlock_streambufs();\n" - " throw std::runtime_error(\"hddm_" - << classPrefix << "::istream::operator>> error -\"\n" - " \" read error in mid-record!\");\n" - " }\n" - " if ((MY(status_bits) & k_crc32_integrity) != 0) {\n" - " unsigned int recorded_crc;\n" - " char crcbuf[10];\n" - " istreambuffer sbuf(crcbuf,10);\n" - " xstream::xdr::istream xstr(&sbuf);\n" - " MY(istr)->read(crcbuf,4);\n" - " MY(bytes_read) += MY(istr)->gcount();\n" - " xstr >> recorded_crc;\n" - " xstream::digest::crc32 crc;\n" - " std::ostream out(&crc);\n" - " out.write(MY(event_buffer),MY(event_size)+4);\n" - " out.flush();\n" - " if (crc.digest() != recorded_crc) {\n" - " char errmsg[] = \n" - " \"WARNING: crc data integrity check failed\"\n" - " \" on hddm_" << classPrefix << " input stream!\";\n" - " if ((MY(status_bits) & 0x02) == 0) {\n" - " std::cerr << errmsg << std::endl;\n" - " MY(status_bits) |= 0x02;\n" - " }\n" - " //unlock_streambufs();\n" - " //throw std::runtime_error(\"hddm_" - << classPrefix << "::istream::operator>> error -\"\n" - " // \" crc check error on input stream!\");\n" - " }\n" - " }\n" - " unlock_streambufs();\n" - " if (MY(events_to_skip) > 0) {\n" - " --MY(events_to_skip);\n" - " }\n" - " else {\n" - " break;\n" - " }\n" - " }\n" - " MY(sbuf)->reset();\n" - " MY(sequencing) = 0;\n" - " MY(codon) = &MY(genome);\n" - " record.clear();\n" - " *this >> (streamable&)record;\n" - " return *this;\n" - "}\n" - "\n" - "ostream::ostream(std::ostream &src)\n" - " : m_ostr(src),\n" - " m_status_bits(k_default_status)\n" - "{\n" - " m_ostr << HDDM::DocumentString();\n" - " if (!m_ostr.good()) {\n" - " throw std::runtime_error(\"hddm_" + classPrefix + - "::ostream::ostream(ostream) \"\n" - " \"error - write error on header output!\");\n" - " }\n" - " pthread_mutex_init(&m_streambuf_mutex,0);\n" - " for (int i=0; ipubsync();\n" - " MY(ostr)->rdbuf(m_ostr.rdbuf());\n" - " delete MY(xcmp);\n" - " }\n" - " if (MY(ostr)) {\n" - " MY(ostr)->flush();\n" - " delete MY(ostr);\n" - " }\n" - " delete [] MY(event_buffer);\n" - " delete my_private;\n" - " }\n" - " }\n" - "}\n" - "\n" - "void ostream::init_private_data() {\n" - " int threadID = threads::getID();\n" - " if (my_thread_private[threadID] == 0) {\n" - " my_thread_private[threadID] = new thread_private_data;\n" - " }\n" - " MY_SETUP\n" - " MY(event_buffer) = new char[MY(event_buffer_size) = 100000];\n" - " MY(sbuf) = new ostreambuffer(MY(event_buffer),MY(event_buffer_size));\n" - " MY(xstr) = new xstream::xdr::ostream(MY(sbuf));\n" - " MY(ostr) = new std::ostream(m_ostr.rdbuf());\n" - " MY(xcmp) = 0;\n" - " MY(last_start) = 0;\n" - " MY(last_offset) = 0;\n" - " MY(records_written) = 0;\n" - " MY(bytes_written) = 0;\n" - " MY(status_bits) = 0;\n" - " MY(mutex_lock) = 0;\n" - "}\n" - "\n" - "void ostream::setCompression(int flags) {\n" - " MY_SETUP\n" - " int oldcmp = (int)m_status_bits & k_bits_compression;\n" - " int newcmp = flags & k_bits_compression;\n" - " if (oldcmp != newcmp) {\n" - " m_status_bits.fetch_and(~k_bits_compression | flags);\n" - " m_status_bits.fetch_or(k_bits_compression & flags);\n" - " if (newcmp != 0)\n" - " m_status_bits.fetch_or(k_can_reposition);\n" - " MY(sbuf)->reset();\n" - " *MY(xstr) << 1 << 8 << 0 << (int)m_status_bits;\n" - " lock_streambufs();\n" - " MY(ostr)->write(MY(sbuf)->getbuf(),MY(sbuf)->size());\n" - " if (!MY(ostr)->good()) {\n" - " unlock_streambufs();\n" - " throw std::runtime_error(\"hddm_" - << classPrefix << "::ostream::setCompression\"\n" - " \" error - write error on token output!\");\n" - " }\n" - " MY(ostr)->flush();\n" - " update_streambufs();\n" - " unlock_streambufs();\n" - " }\n" - "}\n" - "\n" - "void ostream::setIntegrityChecks(int flags) {\n" - " MY_SETUP\n" - " int oldint = (int)m_status_bits & k_bits_integrity;\n" - " int newint = flags & k_bits_integrity;\n" - " if (oldint != newint) {\n" - " m_status_bits.fetch_and(~k_bits_integrity | flags);\n" - " m_status_bits.fetch_or(k_bits_integrity & flags);\n" - " MY(sbuf)->reset();\n" - " *MY(xstr) << 1 << 8 << 0 << (int)m_status_bits;\n" - " lock_streambufs();\n" - " MY(ostr)->write(MY(sbuf)->getbuf(),MY(sbuf)->size());\n" - " if (!MY(ostr)->good()) {\n" - " unlock_streambufs();\n" - " throw std::runtime_error(\"hddm_" - << classPrefix << "::ostream::setIntegrityChecks\"\n" - " \" error - write error on token output!\");\n" - " }\n" - " MY(ostr)->flush();\n" - " update_streambufs();\n" - " unlock_streambufs();\n" - " }\n" - "}\n" - "\n" - "streamposition ostream::getPosition() {\n" - " MY_SETUP\n" - " streamposition pos;\n" - " pos.block_start = MY(last_start);\n" - " pos.block_start = MY(last_offset);\n" - " pos.block_status = MY(status_bits);\n" - " return pos;\n" - "}\n" - "\n" - "void ostream::update_streambufs() {\n" - " MY_SETUP\n" - " if ((int)m_status_bits != MY(status_bits)) {\n" - " configure_streambufs();\n" - " }\n" - "}\n" - "\n" - "void ostream::configure_streambufs() {\n" - " MY_SETUP\n" - " int oldcmp = MY(status_bits) & k_bits_compression;\n" - " int newcmp = (int)m_status_bits & k_bits_compression;\n" - " if (oldcmp != newcmp) {\n" - " if (oldcmp != k_no_compression) {\n" - " MY(ostr)->rdbuf(m_ostr.rdbuf());\n" - " delete MY(xcmp);\n" - " MY(xcmp) = 0;\n" - " }\n" - " if (newcmp == k_z_compression) {\n" - " //std::cerr << \"output switched on z compression\" << std::endl;\n" - " MY(xcmp) = new xstream::z::ostreambuf(m_ostr.rdbuf());\n" - " MY(ostr)->rdbuf(MY(xcmp));\n" - " }\n" - " else if (newcmp == k_bz2_compression) {\n" - " //std::cerr << \"output switched on bz2 compression\" << std::endl;\n" - " MY(xcmp )= new xstream::bz::ostreambuf(m_ostr.rdbuf());\n" - " MY(ostr)->rdbuf(MY(xcmp));\n" - " }\n" - " else if (newcmp != k_no_compression) {\n" - " throw std::runtime_error(\"hddm_" - << classPrefix << "::ostream::configure_streambufs error - \"\n" - " \"unrecognized compression flag requested.\");\n" - " }\n" - " }\n" - " MY(status_bits) = m_status_bits;\n" - "}\n" - "\n" - "void ostream::lock_streambufs() {\n" - " MY_SETUP\n" - " if (MY(mutex_lock) != 0) {\n" - " unlock_streambufs();\n" - " throw std::runtime_error(\"hddm_" - << classPrefix << "::ostream::lock_streambufs error - \"\n" - " \"mutex lock requested when lock already held.\");\n" - " }\n" - " if ((MY(status_bits) & k_bits_compression) == k_no_compression) {\n" - " pthread_mutex_lock(&m_streambuf_mutex);\n" - " MY(mutex_lock) = 1;\n" - " }\n" - " else if ((MY(status_bits) & k_bits_compression) == k_z_compression) {\n" - " ((xstream::z::ostreambuf*)MY(xcmp))->set_streambuf_mutex(&m_streambuf_mutex);\n" - " MY(mutex_lock) = 2;\n" - " }\n" - " else if ((MY(status_bits) & k_bits_compression) == k_bz2_compression) {\n" - " ((xstream::bz::ostreambuf*)MY(xcmp))->set_streambuf_mutex(&m_streambuf_mutex);\n" - " MY(mutex_lock) = 3;\n" - " }\n" - " else {\n" - " MY(mutex_lock) = -1;\n" - " }\n" - "}\n" - "\n" - "void ostream::unlock_streambufs() {\n" - " MY_SETUP\n" - " if (MY(mutex_lock) == 0) {\n" - " throw std::runtime_error(\"hddm_" - << classPrefix << "::ostream::unlock_streambufs error - \"\n" - " \"mutex unlock requested when lock not held.\");\n" - " }\n" - " else if (MY(mutex_lock) == 1) {\n" - " pthread_mutex_unlock(&m_streambuf_mutex);\n" - " }\n" - " else if (MY(mutex_lock) == 2) {\n" - " ((xstream::z::ostreambuf*)MY(xcmp))->set_streambuf_mutex(0);\n" - " }\n" - " else if (MY(mutex_lock) == 3) {\n" - " ((xstream::bz::ostreambuf*)MY(xcmp))->set_streambuf_mutex(0);\n" - " }\n" - " MY(mutex_lock) = 0;\n" - "}\n" - "\n" - "int istream::getTag(const std::string &src, int start,\n" - " std::string &tag, int &level)\n" - "{\n" - " tag = \"\";\n" - " size_t p_btag = src.find(\"<\",start);\n" - " size_t p_bline = src.find_last_of(\"\\n\",p_btag);\n" - " if (p_bline == std::string::npos)\n" - " {\n" - " p_bline = 0;\n" - " }\n" - " else\n" - " {\n" - " ++p_bline;\n" - " }\n" - " level = (p_btag-p_bline)/2;\n" - " size_t p_etag = p_btag;\n" - " for (size_t quotes=0; p_etag < src.size(); ++p_etag) {\n" - " if (src[p_etag] == '\"') {\n" - " tag += \"\\\"\";\n" - " ++quotes;\n" - " }\n" - " else if (quotes/2*2 != quotes) {\n" - " tag += src[p_etag];\n" - " }\n" - " else if (src.find_first_of(\" \\t\\n\",p_etag) == 0) {\n" - " tag += \" \";\n" - " p_etag = src.find_first_not_of(\" \\t\\n\",p_etag)-1;\n" - " }\n" - " else if (src[p_etag] == '>') {\n" - " tag += \">\";\n" - " break;\n" - " }\n" - " else {\n" - " tag += src[p_etag];\n" - " }\n" - " }\n" - " if (p_etag == src.size()) {\n" - " std::stringstream sstr;\n" - " sstr << \"hddm_" + classPrefix + "::istream::getTag\"\n" - " << \" error - bad header format\" << std::endl\n" - " << \" tag \" << tag << \" at position \" << start\n" - " << std::endl;\n" - " throw std::runtime_error(sstr.str());\n" - " }\n" - " return p_etag+2;\n" - "}\n" - "\n" - "int istream::getEndTag(const std::string &src, int start,\n" - " const std::string &tag)\n" - "{\n" - " if (tag.rfind(\"/>\") == tag.size()-2) {\n" - " return src.find(tag,start) + tag.size()+1;\n" - " }\n" - " else {\n" - " std::string etag = \"\";\n" - " size_t p_etag = src.find(etag,start);\n" - " size_t p_quote = src.find_first_of('\"',start);\n" - " while (p_quote != std::string::npos && p_quote < p_etag) {\n" - " p_quote = src.find_first_of('\"',p_quote+1);\n" - " if (p_quote > p_etag) {\n" - " p_etag = src.find(etag,p_quote+1);\n" - " }\n" - " p_quote = src.find_first_of('\"',p_quote+1);\n" - " }\n" - " if (p_etag == std::string::npos) {\n" - " std::stringstream sstr;\n" - " sstr << \"hddm_" + classPrefix + "::istream::getEndTag\"\n" - " << \" error - bad header format\" << std::endl\n" - " << \" tag \" << tag << \" at position \" << start\n" - " << std::endl\n" - " << \" end tag \" << etag << \" not found.\"\n" - " << std::endl;\n" - " throw std::runtime_error(sstr.str());\n" - " }\n" - " return p_etag + etag.size()+1;\n" - " }\n" - "}\n" - "\n" - "void istream::collide(const std::string &itag, const std::string &rtag) {\n" - " std::string itagname = itag.substr(1,itag.find(\" \")-1);\n" - " std::string rtagname = rtag.substr(1,rtag.find(\" \")-1);\n" - " std::string errmsg = \"hddm_" + classPrefix + - "::istream::collide warning:\\n\"\n" - " \"tag \" + itagname + \" in input file \"\n" - " \"does not match c++ header hddm_" << classPrefix << ".hpp\\n\"\n" - " \" input file: \" + itag + \"\\n\"\n" - " \" c++ header: \" + rtag + \"\\n\"\n" - " \" === Tag \" + itagname + \" will be ignored,\"\n" - " \" rebuild to cure the problem ===\";\n" - " if (itagname != \"HDDM\") {\n" - " std::cerr << errmsg << std::endl;\n" - " }\n" - " else {\n" - " throw std::runtime_error(errmsg);\n" - " }\n" - "}\n" - "\n" - "chromosome istream::synthesize(const std::string &src, int p_src,\n" - " const std::string &ref, int p_ref)\n" - "{\n" - " chromosome chrom;\n" - " int slevel, rlevel;\n" - " std::string stag, rtag;\n" - " p_src = getTag(src,p_src,stag,slevel);\n" - " p_ref = getTag(ref,p_ref,rtag,rlevel);\n" - " std::string stagname = stag.substr(1,stag.find(\" \")-1);\n" - " std::string rtagname = rtag.substr(1,rtag.find(\" \")-1);\n" - " if (stagname != rtagname) {\n" - " throw std::runtime_error(\"hddm_" + classPrefix + - "::istream::synthesize error - matching algorithm error #2\");\n" - " }\n" - " else if (!tags_match(stag,rtag)) {\n" - " collide(stag,rtag);\n" - " return chrom;\n" - " }\n" - "\n" - " int p2_src, p2_ref;\n" - " int s2level, r2level;\n" - " std::string s2tag, r2tag;\n" - " getTag(src,p2_src=p_src,s2tag,s2level);\n" - " while (s2level > slevel) {\n" - " codon *gene = new codon();\n" - " std::string s2tagname = s2tag.substr(1,s2tag.find(\" \")-1);\n" - " getTag(ref,p2_ref=p_ref,r2tag,r2level);\n" - " int order_of_this_tag_in_ref = 1;\n" - " while (r2level == s2level) {\n" - " std::string r2tagname = r2tag.substr(1,r2tag.find(\" \")-1);\n" - " if (s2tagname == r2tagname) {\n" - " if (!tags_match(s2tag,r2tag)) {\n" - " collide(s2tag,r2tag);\n" - " break;\n" - " }\n" - " else {\n" - " gene->m_order = order_of_this_tag_in_ref;\n" - " }\n" - " gene->m_sequence = synthesize(src,p2_src,ref,p2_ref);\n" - " break;\n" - " }\n" - " p2_ref = getEndTag(ref,p2_ref,r2tag);\n" - " getTag(ref,p2_ref,r2tag,r2level);\n" - " ++order_of_this_tag_in_ref;\n" - " }\n" - " gene->m_tagname = s2tagname;\n" - " chrom.push_back(*gene);\n" - " delete gene;\n" - " p2_src = getEndTag(src,p2_src,s2tag);\n" - " getTag(src,p2_src,s2tag,s2level);\n" - " }\n" - " return chrom;\n" - "}\n" - "\n" - "#ifdef HDF5_SUPPORT\n" - "std::map HDDM::s_hdf5_datatype;\n" - "std::map HDDM::s_hdf5_memorytype;\n" - "std::map HDDM::s_hdf5_memoryspace;\n" - "std::map HDDM::s_hdf5_dataspace;\n" - "std::map HDDM::s_hdf5_chunking;\n" - "std::map HDDM::s_hdf5_dataset;\n" - "#endif\n" - ; - - XMLPlatformUtils::Terminate(); - return 0; -} - -XtString XtString::plural() -{ - XtString p(*this); - XtString::size_type len = p.size(); - if (len > 3 && p.substr(len-3,3) == "tum") - { - p.replace(len-3,3,"ta"); - } - else if (len > 1 && p.substr(len-3,3) == "ies") - { - p.replace(len-3,3,"iesList"); - } - else if (len > 2 && p.substr(len-2,2) == "ex") - { - p.replace(len-2,2,"ices"); - } - else if (len > 2 && p.substr(len-2,2) == "sh") - { - p.replace(len-2,2,"shes"); - } - else if (len > 1 && p.substr(len-1,1) == "s") - { - p.replace(len-1,1,"ses"); - } - else if (len > 1) - { - p += "s"; - } - return p; -} - -/* Map from tag name to name of the corresponding class - * for the case of simple tags (those that do not repeat) - */ -XtString XtString::simpleType() -{ - XtString p(*this); - p[0] = toupper(p[0]); - return p; -} - -/* Map from tag name to name of the corresponding class - * for the case of list tags (those that may repeat) - */ -XtString XtString::listType() -{ - XtString r(*this); - r[0] = toupper(r[0]); - r = r + "List"; - return r; -} - -/* Map from tag name to name of the corresponding class - * for the case of link tags (those that do not repeat) - */ -XtString XtString::linkType() -{ - XtString r(*this); - r[0] = toupper(r[0]); - r = r + "Link"; - return r; -} - -/* Look for a named element in a list of element pointers - * and return index of first instance in the list if found, - * otherwise return -1; - */ -int CodeBuilder::element_in_list(XtString &name, parentList_t list) -{ - int n=0; - parentList_t::iterator iter; - for (iter = list.begin(); iter != list.end(); ++iter, ++n) - { - DOMElement *el = (DOMElement*)(*iter); - XtString cnameS(el->getTagName()); - if (cnameS == name) { - return n; - } - } - return -1; -} - -/* Verify that the tag group under this element does not collide - * with existing tag group elref, otherwise exit with fatal error - */ -void CodeBuilder::checkConsistency(DOMElement* el, DOMElement* elref) -{ - XtString tagS(el->getTagName()); - if (el->getParentNode() == elref->getParentNode()) - { - std::cerr - << "hddm-cpp error: tag " << "\"" << tagS - << "\" is duplicated within one context in xml document." - << std::endl; - exit(1); - } - - DOMNamedNodeMap* oldAttr = elref->getAttributes(); - DOMNamedNodeMap* newAttr = el->getAttributes(); - unsigned int listLength = oldAttr->getLength(); - for (unsigned int n = 0; n < listLength; n++) - { - XtString nameS(oldAttr->item(n)->getNodeName()); - XtString oldS(elref->getAttribute(X(nameS))); - XtString newS(el->getAttribute(X(nameS))); - if (nameS == "minOccurs") - { - continue; - } - else if (nameS == "maxOccurs") - { - int maxold = (oldS == "unbounded")? INT_MAX : atoi(S(oldS)); - int maxnew = (newS == "unbounded")? INT_MAX : atoi(S(newS)); - if ((maxold < 2 && maxnew > 1) || (maxold > 1 && maxnew < 2)) - { - std::cerr - << "hddm-cpp error: inconsistent maxOccurs usage by tag " - << "\"" << tagS << "\" in xml document." << std::endl; - exit(1); - } - } - else if (newS != oldS) - { - std::cerr - << "hddm-cpp error: inconsistent usage of attribute " - << "\"" << nameS << "\" in tag " - << "\"" << tagS << "\" in xml document." << std::endl; - exit(1); - } - } - listLength = newAttr->getLength(); - for (unsigned int n = 0; n < listLength; n++) - { - XtString nameS(newAttr->item(n)->getNodeName()); - XtString oldS(elref->getAttribute(X(nameS))); - XtString newS(el->getAttribute(X(nameS))); - if (nameS == "minOccurs") - { - continue; - } - else if (nameS == "maxOccurs") - { - int maxold = (oldS == "unbounded")? INT_MAX : atoi(S(oldS)); - int maxnew = (newS == "unbounded")? INT_MAX : atoi(S(newS)); - if ((maxold < 2 && maxnew > 1) || (maxold > 1 && maxnew < 2)) - { - std::cerr - << "hddm-cpp error: inconsistent maxOccurs usage by tag " - << "\"" << tagS << "\" in xml document." << std::endl; - exit(1); - } - } - else if (newS != oldS) - { - std::cerr - << "hddm-cpp error: inconsistent usage of attribute " - << "\"" << nameS << "\" in tag " - << "\"" << tagS << "\" in xml document." << std::endl; - exit(1); - } - } - DOMNodeList* oldList = elref->getChildNodes(); - DOMNodeList* newList = el->getChildNodes(); - listLength = oldList->getLength(); - if (newList->getLength() != listLength) - { - std::cerr - << "hddm-cpp error: inconsistent usage of tag " - << "\"" << tagS << "\" in xml document." << std::endl; - exit(1); - } - for (unsigned int n = 0; n < listLength; n++) - { - DOMNode* cont = oldList->item(n); - XtString nameS(cont->getNodeName()); - short type = cont->getNodeType(); - if (type == DOMNode::ELEMENT_NODE) - { - DOMNodeList* contList = el->getElementsByTagName(X(nameS)); - if (contList->getLength() != 1) - { - std::cerr - << "hddm-cpp error: inconsistent usage of tag " - << "\"" << tagS << "\" in xml document." << std::endl; - exit(1); - } - } - } -} - -/* Write declaration of the classes for this tag to the header file */ - -void CodeBuilder::writeClassdef(DOMElement* el) -{ - XtString tagS(el->getTagName()); - hFile << "class " << tagS.simpleType() - << ": public HDDM_Element {" << std::endl - << " public:" << std::endl; - if (tagS == "HDDM") { - hFile << " HDDM();" << std::endl; - } - hFile << " ~" << tagS.simpleType() << "();" << std::endl; - hFile << " void clear();" << std::endl; - - std::map attrList; - DOMNamedNodeMap *myAttr = el->getAttributes(); - for (unsigned int n = 0; n < myAttr->getLength(); n++) - { - XtString attrS(myAttr->item(n)->getNodeName()); - XtString typeS(el->getAttribute(X(attrS))); - attrList[attrS] = typeS; - } - parentList_t::iterator iter; - for (iter = parents[tagS].begin(); iter != parents[tagS].end(); ++iter) - { - DOMElement *hostEl = (DOMElement*)(*iter); - XtString hostS(hostEl->getTagName()); - DOMNamedNodeMap *hostAttr = hostEl->getAttributes(); - for (unsigned int n = 0; n < hostAttr->getLength(); n++) - { - XtString attrS(hostAttr->item(n)->getNodeName()); - if (attrList.find(attrS) != attrList.end()) - { - continue; - } - XtString typeS(hostEl->getAttribute(X(attrS))); - attrList[attrS] = typeS; - XtString getS("get"+attrS.simpleType()); - if (typeS == "int") - { - hFile << " int " << getS << "() const;" << std::endl; - } - else if (typeS == "long") - { - hFile << " int64_t " << getS << "() const;" << std::endl; - } - else if (typeS == "float") - { - hFile << " float " << getS << "() const;" << std::endl; - } - else if (typeS == "double") - { - hFile << " double " << getS << "() const;" << std::endl; - } - else if (typeS == "boolean") - { - hFile << " bool " << getS << "() const;" << std::endl; - } - else if (typeS == "string") - { - hFile << " std::string " << getS << "() const;" << std::endl; - } - else if (typeS == "anyURI") - { - hFile << " std::string " << getS << "() const;" << std::endl; - } - else if (typeS == "Particle_t") - { - hFile << " Particle_t " << getS << "() const;" << std::endl; - } - else if (guessType(typeS) == "int") - { - hFile << " int " << getS << "() const;" << std::endl; - } - else if (guessType(typeS) == "long") - { - hFile << " int64_t " << getS << "() const;" << std::endl; - } - else if (guessType(typeS) == "float") - { - hFile << " float " << getS << "() const;" << std::endl; - } - else if (guessType(typeS) == "double") - { - hFile << " double " << getS << "() const;" << std::endl; - } - else if (guessType(typeS) == "boolean") - { - hFile << " bool " << getS << "() const;" << std::endl; - } - else if (guessType(typeS) == "Particle_t") - { - hFile << " Particle_t " << getS << "() const;" << std::endl; - } - else /* any values not matching the above are strings */ - { - hFile << " std::string " << getS << "() const;" << std::endl; - } - } - } - - myAttr = el->getAttributes(); - for (unsigned int n = 0; n < myAttr->getLength(); n++) - { - XtString attrS(myAttr->item(n)->getNodeName()); - XtString typeS(el->getAttribute(X(attrS))); - XtString getS("get" + attrS.simpleType()); - XtString setS("set" + attrS.simpleType()); - if (typeS == "int") - { - hFile << " int " << getS << "() const;" << std::endl - << " void " << setS << "(int " << attrS << ");" << std::endl; - } - else if (typeS == "long") - { - hFile << " int64_t " << getS << "() const;" << std::endl - << " void " << setS << "(int64_t " << attrS << ");" << std::endl; - } - else if (typeS == "float") - { - hFile << " float " << getS << "() const;" << std::endl - << " void " << setS << "(float " << attrS << ");" << std::endl; - } - else if (typeS == "double") - { - hFile << " double " << getS << "() const;" << std::endl - << " void " << setS << "(double " << attrS << ");" << std::endl; - } - else if (typeS == "boolean") - { - hFile << " bool " << getS << "() const;" << std::endl - << " void " << setS << "(bool " << attrS << ");" << std::endl; - } - else if (typeS == "string") - { - hFile << " std::string " << getS << "() const;" << std::endl - << " void " << setS << "(const std::string &" << attrS << ");" - << std::endl; - } - else if (typeS == "anyURI") - { - hFile << " std::string " << getS << "() const;" << std::endl - << " void " << setS << "(const std::string &" << attrS << ");" - << std::endl; - } - else if (typeS == "Particle_t") - { - hFile << " Particle_t " << getS << "() const;" << std::endl - << " void " << setS << "(Particle_t " << attrS << ");" << std::endl; - } - else if (guessType(typeS) == "int") - { - hFile << " int " << getS << "() const;" << std::endl; - } - else if (guessType(typeS) == "long") - { - hFile << " int64_t " << getS << "() const;" << std::endl; - } - else if (guessType(typeS) == "float") - { - hFile << " float " << getS << "() const;" << std::endl; - } - else if (guessType(typeS) == "double") - { - hFile << " double " << getS << "() const;" << std::endl; - } - else if (guessType(typeS) == "boolean") - { - hFile << " bool " << getS << "() const;" << std::endl; - } - else if (guessType(typeS) == "Particle_t") - { - hFile << " Particle_t " << getS << "() const;" << std::endl; - } - else /* any attributes not matching the above are strings */ - { - hFile << " std::string " << getS << "() const;" << std::endl; - } - } - - if (tagS == "HDDM") { - parentTable_t::iterator piter; - for (piter = parents.begin(); piter != parents.end(); ++piter) - { - XtString cnameS(piter->first); - if (cnameS != "HDDM" && element_in_list(cnameS,children[tagS]) == -1) - { - hFile << " " << cnameS.listType() << " get" - << cnameS.plural().simpleType() << "();" << std::endl; - } - } - } - - parentList_t::iterator citer; - for (citer = children[tagS].begin(); citer != children[tagS].end(); ++citer) - { - DOMElement *childEl = (DOMElement*)(*citer); - XtString cnameS(childEl->getTagName()); - XtString repS(childEl->getAttribute(X("maxOccurs"))); - int rep = (repS == "unbounded")? INT_MAX : atoi(S(repS)); - hFile << " " << cnameS.simpleType() << " &get" - << cnameS.simpleType() - << ((rep > 1)? "(int index=0);" : "();") << std::endl; - hFile << " " << cnameS.listType() << " &get" - << cnameS.plural().simpleType() << "();" << std::endl; - hFile << " " << cnameS.listType() << " add" - << cnameS.plural().simpleType() - << "(int count=1, int start=-1);" << std::endl; - hFile << " void delete" - << cnameS.plural().simpleType() - << "(int count=-1, int start=0);" << std::endl; - } - - hFile << " const void *getAttribute(const std::string &name," - << " hddm_type *atype=0) const;\n" - << " std::string toString(int indent=0);\n" - << " std::string toXML(int indent=0);\n"; - - if (tagS == "HDDM") - { - parentTable_t::iterator piter; - for (piter = parents.begin(); piter != parents.end(); ++piter) - { - XtString cnameS(piter->first); - if (cnameS != "HDDM") { - hFile << " friend class " << cnameS.simpleType() << ";" - << std::endl; - } - } - hFile << " static std::string DocumentString();" << std::endl; - hFile << " private:" << std::endl; - } - else - { - hFile << "#ifdef HDF5_SUPPORT" << std::endl - << " void hdf5DataPack();" << std::endl - << " void hdf5DataUnpack();" << std::endl - << " hid_t hdf5Datatype(int inmemory=0, int verbose=0);" - << std::endl - << "#endif" << std::endl; - hFile << " friend class HDDM_ElementList<" - << tagS.simpleType() << ">;" << std::endl - << " friend class HDDM_ElementLink<" - << tagS.simpleType() << ">;" << std::endl - << " " << tagS.simpleType() << "() {}" << std::endl - << " " << tagS.simpleType() - << "(HDDM_Element *parent, int owner=0);" << std::endl; - hFile << " private:" << std::endl; - } - - hFile << " void streamer(istream &istr);" << std::endl - << " void streamer(ostream &ostr);" << std::endl; - - for (unsigned int n = 0; n < myAttr->getLength(); n++) - { - XtString attrS(myAttr->item(n)->getNodeName()); - XtString typeS(el->getAttribute(X(attrS))); - if (typeS == "int") - { - hFile << " int m_" << attrS << ";" << std::endl; - } - else if (typeS == "long") - { - hFile << " int64_t m_" << attrS << ";" << std::endl; - } - else if (typeS == "float") - { - hFile << " float m_" << attrS << ";" << std::endl; - } - else if (typeS == "double") - { - hFile << " double m_" << attrS << ";" << std::endl; - } - else if (typeS == "boolean") - { - hFile << " int m_" << attrS << ";" << std::endl; - } - else if (typeS == "string") - { - hFile << " std::string m_" << attrS << ";" << std::endl; - hFile << " const char *mx_" << attrS << ";" << std::endl; - } - else if (typeS == "anyURI") - { - hFile << " std::string m_" << attrS << ";" << std::endl; - hFile << " const char *mx_" << attrS << ";" << std::endl; - } - else if (typeS == "Particle_t") - { - hFile << " int m_" << attrS << ";" << std::endl; - } - } - - if (tagS == "HDDM") { - parentTable_t::iterator piter; - for (piter = parents.begin(); piter != parents.end(); ++piter) - { - XtString dnameS(piter->first); - if (dnameS != "HDDM") { - hFile << " std::list<" << dnameS.simpleType() - << "*> m_" << dnameS << "_plist;" << std::endl; - } - } - } - - for (citer = children[tagS].begin(); citer != children[tagS].end(); ++citer) - { - DOMElement *childEl = (DOMElement*)(*citer); - XtString cnameS(childEl->getTagName()); - XtString repS(childEl->getAttribute(X("maxOccurs"))); - int rep = (repS == "unbounded")? INT_MAX : atoi(S(repS)); - hFile << " " << ((rep > 1)? cnameS.listType() : cnameS.linkType()) - << " m_" << cnameS - << ((rep > 1)? "_list;" : "_link;") << std::endl; - } - - if (tagS == "HDDM") { - hFile << "#ifdef HDF5_SUPPORT" << std::endl - << " public:" << std::endl - << " void hdf5DataPack();" << std::endl - << " void hdf5DataUnpack();" << std::endl - << " hid_t hdf5Datatype(int inmemory=0, int verbose=0);" - << std::endl - << " herr_t hdf5FileWrite(hid_t file_id, long int entry=-1);" - << std::endl - << " herr_t hdf5FileRead(hid_t file_id, long int entry=-1);" - << std::endl - << " static hid_t" - << " hdf5FileCreate(std::string name, unsigned int flags);" - << std::endl - << " static hid_t" - << " hdf5FileOpen(std::string name, unsigned int flags);" - << std::endl - << " static herr_t hdf5FileClose(hid_t file_id);" - << std::endl - << " static herr_t hdf5FileStamp(hid_t file_id, char **tags=0);" - << std::endl - << " static herr_t hdf5FileCheck(hid_t file_id, char **tags=0);" - << std::endl - << " static std::string hdf5DocumentString(hid_t file_id);" - << std::endl - << " static long int hdf5GetEntries(hid_t file_id);" - << std::endl - << " static herr_t hdf5SetChunksize(hid_t file_id," - << " hsize_t chunksize);" - << std::endl - << " static hsize_t hdf5GetChunksize(hid_t file_id);" - << std::endl - << " static herr_t hdf5SetFilters(hid_t file_id," - << " std::vector &filters);" - << std::endl - << " static herr_t hdf5GetFilters(hid_t file_id," - << " std::vector &filters);" - << std::endl - << " static void hdf5_memcpy(void *dst, void *src, int size) {" - << std::endl - << " memcpy(dst, src, size);" - << std::endl - << " }" << std::endl - << " private:" << std::endl - << " static std::map s_hdf5_datatype;" - << std::endl - << " static std::map s_hdf5_memorytype;" - << std::endl - << " static std::map s_hdf5_memoryspace;" - << std::endl - << " static std::map s_hdf5_dataspace;" - << std::endl - << " static std::map s_hdf5_chunking;" - << std::endl - << " static std::map s_hdf5_dataset;" - << std::endl - << " typedef struct {" << std::endl; - parentTable_t::iterator piter; - for (piter = parents.begin(); piter != parents.end(); ++piter) - { - XtString dnameS(piter->first); - if (dnameS != "HDDM") { - hFile << " hdf5_hvl_t vl_" << dnameS << ";" - << std::endl; - } - } - hFile << " } hdf5_record_t;" << std::endl - << " hdf5_record_t m_hdf5_record;" << std::endl - << " hsize_t m_hdf5_record_offset;" << std::endl - << " hsize_t m_hdf5_record_count;" << std::endl - << " hsize_t m_hdf5_record_extent;" << std::endl - << " std::vector m_hdf5_strings;" - << std::endl - << "#endif" << std::endl; - } - hFile << "};" << std::endl << std::endl; - - if (tagS != "HDDM") - { - hFile << "typedef HDDM_ElementList<" - << tagS.simpleType() << "> " - << tagS.listType() << ";" << std::endl - << "typedef HDDM_ElementLink<" - << tagS.simpleType() << "> " - << tagS.linkType() << ";" - << std::endl << std::endl; - } -} - -/* Generate class declarations for this tag and its descendants; - * this function calls itself recursively - */ - -void CodeBuilder::constructGroup(DOMElement* el) -{ - XtString tagS(el->getTagName()); - parentList_t::iterator piter; - parents[tagS].insert(parents[tagS].begin(), - parentList.begin(),parentList.end()); - std::vector::iterator iter; - for (iter = tagList.begin(); iter != tagList.end(); iter++) - { - DOMElement* targEl = *iter; - XtString targS(targEl->getTagName()); - if (tagS == targS) - { - checkConsistency(el,targEl); - return; - } - } - - parentList.push_back(el); - DOMNodeList* contList = el->getChildNodes(); - int contLength = contList->getLength(); - for (int c = 0; c < contLength; c++) - { - DOMNode* cont = contList->item(c); - short type = cont->getNodeType(); - if (type == DOMNode::ELEMENT_NODE) - { - DOMElement* contEl = (DOMElement*) cont; - XtString contS(contEl->getTagName()); - children[tagS].push_back(contEl); - constructGroup(contEl); - } - } - parentList.pop_back(); - - tagList.push_back(el); - - if (tagS == "HDDM") - { - std::vector::iterator iter; - for (iter = tagList.begin(); iter != tagList.end(); iter++) - { - writeClassdef(*iter); - } - } -} - -/* Write method implementation of the classes for this tag to the header file */ - -void CodeBuilder::writeClassimp(DOMElement* el) -{ - XtString tagS(el->getTagName()); - if (tagS == "HDDM") - { - hFile << "inline " << tagS.simpleType() << "::" - << tagS.simpleType() << "()" << std::endl - << " : HDDM_Element()"; - } - else - { - hFile << "inline " << tagS.simpleType() << "::" - << tagS.simpleType() << "(HDDM_Element *parent, int owner)" - << std::endl - << " : HDDM_Element(parent, owner)"; - } - DOMNamedNodeMap *myAttr = el->getAttributes(); - for (unsigned int n = 0; n < myAttr->getLength(); n++) - { - XtString attrS(myAttr->item(n)->getNodeName()); - XtString typeS(el->getAttribute(X(attrS))); - if (typeS == "int") - { - hFile << "," << std::endl << " m_" << attrS << "(0)"; - } - else if (typeS == "long") - { - hFile << "," << std::endl << " m_" << attrS << "(0)"; - } - else if (typeS == "float") - { - hFile << "," << std::endl << " m_" << attrS << "(0)"; - } - else if (typeS == "double") - { - hFile << "," << std::endl << " m_" << attrS << "(0)"; - } - else if (typeS == "boolean") - { - hFile << "," << std::endl << " m_" << attrS << "(0)"; - } - else if (typeS == "string") - { - hFile << "," << std::endl << " m_" << attrS << "(\"\")"; - } - else if (typeS == "anyURI") - { - hFile << "," << std::endl << " m_" << attrS << "(\"\")"; - } - else if (typeS == "Particle_t") - { - hFile << "," << std::endl << " m_" << attrS << "(0)"; - } - else - { - /* ignore attributes with unrecognized values */ - } - } - - // Write XXX_plist initializers first and then the XXX_list or - // XXX_link initializers. This is because the plist members - // appear first in the class definition. - // Dec. 3, 2012 David L. - parentList_t::iterator citer; - for (citer = children[tagS].begin(); - citer != children[tagS].end(); - ++citer) - { - DOMElement *childEl = (DOMElement*)(*citer); - XtString cnameS(childEl->getTagName()); - XtString repS(childEl->getAttribute(X("maxOccurs"))); - // int rep; commented out to avoid compiler warnings 4/26/2015 DL - // rep = (repS == "unbounded")? INT_MAX : atoi(S(repS)); - XtString hostS("m_host->"); - if (tagS == "HDDM") - { - hFile << "," << std::endl << " m_" << cnameS - << "_plist()"; - hostS = ""; - } - } - for (citer = children[tagS].begin(); - citer != children[tagS].end(); - ++citer) - { - DOMElement *childEl = (DOMElement*)(*citer); - XtString cnameS(childEl->getTagName()); - XtString repS(childEl->getAttribute(X("maxOccurs"))); - int rep = (repS == "unbounded")? INT_MAX : atoi(S(repS)); - const char *myHost = (tagS=="HDDM" ? "this->":"m_host->"); - XtString hostS(myHost); - hFile << "," << std::endl << " m_" << cnameS - << ((rep > 1)? "_list" : "_link") - << "(&" << hostS << "m_" << cnameS << "_plist," << std::endl - << " " - << hostS << "m_" << cnameS << "_plist.end()," << std::endl - << " " - << hostS << "m_" << cnameS << "_plist.end()," << std::endl - << " " - << "this)"; - } - if (tagS == "HDDM") - { - hFile << std::endl << "{" << std::endl - << " m_host = this;" << std::endl - << "#ifdef HDF5_SUPPORT" << std::endl - << " m_hdf5_record_offset = 0;" << std::endl - << " m_hdf5_record_count = 0;" << std::endl - << " m_hdf5_record_extent = 0;" << std::endl - << "#endif" << std::endl - << "}" << std::endl << std::endl; - } - else - { - hFile << std::endl << "{}" << std::endl << std::endl; - } - - hFile << "inline " << tagS.simpleType() << "::~" - << tagS.simpleType() << "() {" << std::endl - << " clear();" << std::endl - << "}" << std::endl; - if (tagS != "HDDM") - { - hFile << "inline void " << tagS.simpleType() - << "::clear() {"; - if (children[tagS].size() > 0) { - hFile << std::endl - << " if (m_host != 0) {" << std::endl; - for (citer = children[tagS].begin(); - citer != children[tagS].end(); - ++citer) - { - DOMElement *childEl = (DOMElement*)(*citer); - XtString cnameS(childEl->getTagName()); - hFile << " delete" << cnameS.plural().simpleType() - << "();" << std::endl; - } - hFile << " }" << std::endl; - } - hFile << "}" << std::endl << std::endl; - } - - std::map attrList; - myAttr = el->getAttributes(); - for (unsigned int n = 0; n < myAttr->getLength(); n++) - { - XtString attrS(myAttr->item(n)->getNodeName()); - XtString typeS(el->getAttribute(X(attrS))); - attrList[attrS] = typeS; - } - parentList_t::iterator iter; - for (iter = parents[tagS].begin(); iter != parents[tagS].end(); ++iter) - { - DOMElement *hostEl = (DOMElement*)(*iter); - DOMNamedNodeMap *hostAttr = hostEl->getAttributes(); - for (unsigned int n = 0; n < hostAttr->getLength(); n++) - { - XtString attrS(hostAttr->item(n)->getNodeName()); - if (attrList.find(attrS) != attrList.end()) - { - continue; - } - XtString typeS(hostEl->getAttribute(X(attrS))); - attrList[attrS] = typeS; - XtString getS("get" + attrS.simpleType()); - if (typeS == "int") - { - hFile << "inline int " << tagS.simpleType() - << "::" << getS << "() const {" << std::endl - << " return *(int*)m_parent->getAttribute(\"" - << attrS << "\");" << std::endl - << "}" << std::endl << std::endl; - } - else if (typeS == "long") - { - hFile << "inline int64_t " << tagS.simpleType() - << "::" << getS << "() const {" << std::endl - << " return *(int64_t*)m_parent->getAttribute(\"" - << attrS << "\");" << std::endl - << "}" << std::endl << std::endl; - } - else if (typeS == "float") - { - hFile << "inline float " << tagS.simpleType() - << "::" << getS << "() const {" << std::endl - << " return *(float*)m_parent->getAttribute(\"" - << attrS << "\");" << std::endl - << "}" << std::endl << std::endl; - } - else if (typeS == "double") - { - hFile << "inline double " << tagS.simpleType() - << "::" << getS << "() const {" << std::endl - << " return *(double*)m_parent->getAttribute(\"" - << attrS << "\");" << std::endl - << "}" << std::endl << std::endl; - } - else if (typeS == "boolean") - { - hFile << "inline bool " << tagS.simpleType() - << "::" << getS << "() const {" << std::endl - << " return *(bool*)m_parent->getAttribute(\"" - << attrS << "\");" << std::endl - << "}" << std::endl << std::endl; - } - else if (typeS == "string") - { - hFile << "inline std::string " << tagS.simpleType() - << "::" << getS << "() const {" << std::endl - << " return *(const std::string*)m_parent->getAttribute(\"" - << attrS << "\");" << std::endl - << "}" << std::endl << std::endl; - } - else if (typeS == "anyURI") - { - hFile << "inline std::string " << tagS.simpleType() - << "::" << getS << "() const {" << std::endl - << " return *(const std::string*)m_parent->getAttribute(\"" - << attrS << "\");" << std::endl - << "}" << std::endl << std::endl; - } - else if (typeS == "Particle_t") - { - hFile << "inline Particle_t " << tagS.simpleType() - << "::" << getS << "() const {" << std::endl - << " return *(Particle_t*)m_parent->getAttribute(\"" - << attrS << "\");" << std::endl - << "}" << std::endl << std::endl; - } - else if (guessType(typeS) == "int") - { - hFile << "inline int " << tagS.simpleType() - << "::" << getS << "() const {" << std::endl - << " return *(int*)m_parent->getAttribute(\"" - << attrS << "\");" << std::endl - << "}" << std::endl << std::endl; - } - else if (guessType(typeS) == "long") - { - hFile << "inline int64_t " << tagS.simpleType() - << "::" << getS << "() const {" << std::endl - << " return *(long long int*)m_parent->getAttribute(\"" - << attrS << "\");" << std::endl - << "}" << std::endl << std::endl; - } - else if (guessType(typeS) == "float") - { - hFile << "inline float " << tagS.simpleType() - << "::" << getS << "() const {" << std::endl - << " return *(float*)m_parent->getAttribute(\"" - << attrS << "\");" << std::endl - << "}" << std::endl << std::endl; - } - else if (guessType(typeS) == "double") - { - hFile << "inline double " << tagS.simpleType() - << "::" << getS << "() const {" << std::endl - << " return *(double*)m_parent->getAttribute(\"" - << attrS << "\");" << std::endl - << "}" << std::endl << std::endl; - } - else if (guessType(typeS) == "boolean") - { - hFile << "inline bool " << tagS.simpleType() - << "::" << getS << "() const {" << std::endl - << " return *(bool*)m_parent->getAttribute(\"" - << attrS << "\");" << std::endl - << "}" << std::endl << std::endl; - } - else if (guessType(typeS) == "Particle_t") - { - hFile << "inline Particle_t " << tagS.simpleType() - << "::" << getS << "() const {" << std::endl - << " return *(Particle_t*)m_parent->getAttribute(\"" - << attrS << "\");" << std::endl - << "}" << std::endl << std::endl; - } - else /* any attributes not of the above types are strings */ - { - hFile << "inline std::string " << tagS.simpleType() - << "::" << getS << "() const {" << std::endl - << " return *(std::string*)m_parent->getAttribute(\"" - << attrS << "\");" << std::endl - << "}" << std::endl << std::endl; - } - } - } - - for (unsigned int n = 0; n < myAttr->getLength(); n++) - { - XtString attrS(myAttr->item(n)->getNodeName()); - XtString typeS(el->getAttribute(X(attrS))); - XtString getS("get" + attrS.simpleType()); - XtString setS("set" + attrS.simpleType()); - if (typeS == "int") - { - hFile << "inline int " << tagS.simpleType() << "::" << getS - << "() const {" << std::endl - << " return m_" << attrS << ";" << std::endl - << "}" << std::endl << std::endl - << "inline void " << tagS.simpleType() << "::" << setS - << "(int " << attrS << ") {" << std::endl - << " m_" << attrS << " = " << attrS << ";" << std::endl - << "}" << std::endl << std::endl; - } - else if (typeS == "long") - { - hFile << "inline int64_t " << tagS.simpleType() << "::" << getS - << "() const {" << std::endl - << " return m_" << attrS << ";" << std::endl - << "}" << std::endl << std::endl - << "inline void " << tagS.simpleType() << "::" << setS - << "(int64_t " << attrS << ") {" << std::endl - << " m_" << attrS << " = " << attrS << ";" << std::endl - << "}" << std::endl << std::endl; - } - else if (typeS == "float") - { - hFile << "inline float " << tagS.simpleType() << "::" << getS - << "() const {" << std::endl - << " return m_" << attrS << ";" << std::endl - << "}" << std::endl << std::endl - << "inline void " << tagS.simpleType() << "::" << setS - << "(float " << attrS << ") {" << std::endl - << " m_" << attrS << " = " << attrS << ";" << std::endl - << "}" << std::endl << std::endl; - } - else if (typeS == "double") - { - hFile << "inline double " << tagS.simpleType() << "::" << getS - << "() const {" << std::endl - << " return m_" << attrS << ";" << std::endl - << "}" << std::endl << std::endl - << "inline void " << tagS.simpleType() << "::" << setS - << "(double " << attrS << ") {" << std::endl - << " m_" << attrS << " = " << attrS << ";" << std::endl - << "}" << std::endl << std::endl; - } - else if (typeS == "boolean") - { - hFile << "inline bool " << tagS.simpleType() << "::" << getS - << "() const {" << std::endl - << " return m_" << attrS << ";" << std::endl - << "}" << std::endl << std::endl - << "inline void " << tagS.simpleType() << "::" << setS - << "(bool " << attrS << ") {" << std::endl - << " m_" << attrS << " = " << attrS << ";" << std::endl - << "}" << std::endl << std::endl; - } - else if (typeS == "string") - { - hFile << "inline std::string " << tagS.simpleType() << "::" << getS - << "() const {" << std::endl - << " return m_" << attrS << ";" << std::endl - << "}" << std::endl << std::endl - << "inline void " << tagS.simpleType() << "::" << setS - << "(const std::string &" << attrS << ") {" << std::endl - << " m_" << attrS << " = " << attrS << ";" << std::endl - << "}" << std::endl << std::endl; - } - else if (typeS == "anyURI") - { - hFile << "inline std::string " << tagS.simpleType() << "::" << getS - << "() const {" << std::endl - << " return m_" << attrS << ";" << std::endl - << "}" << std::endl << std::endl - << "inline void " << tagS.simpleType() << "::" << setS - << "(const std::string &" << attrS << ") {" << std::endl - << " m_" << attrS << " = " << attrS << ";" << std::endl - << "}" << std::endl << std::endl; - } - else if (typeS == "Particle_t") - { - hFile << "inline Particle_t " << tagS.simpleType() << "::" << getS - << "() const {" << std::endl - << " return (Particle_t)m_" << attrS << ";" << std::endl - << "}" << std::endl << std::endl - << "inline void " << tagS.simpleType() << "::" << setS - << "(Particle_t " << attrS << ") {" << std::endl - << " m_" << attrS << " = " << attrS << ";" << std::endl - << "}" << std::endl << std::endl; - } - else if (guessType(typeS) == "int") - { - hFile << "inline int " << tagS.simpleType() << "::" << getS - << "() const {" << std::endl - << " return " << typeS << ";" << std::endl - << "}" << std::endl << std::endl; - } - else if (guessType(typeS) == "long") - { - hFile << "inline int64_t " << tagS.simpleType() << "::" << getS - << "() const {" << std::endl - << " return " << typeS << "LL;" << std::endl - << "}" << std::endl << std::endl; - } - else if (guessType(typeS) == "float") - { - hFile << "inline float " << tagS.simpleType() << "::" << getS - << "() const {" << std::endl - << " return " << typeS << ";" << std::endl - << "}" << std::endl << std::endl; - } - else if (guessType(typeS) == "double") - { - hFile << "inline double " << tagS.simpleType() << "::" << getS - << "() const {" << std::endl - << " return " << typeS << ";" << std::endl - << "}" << std::endl << std::endl; - } - else if (guessType(typeS) == "boolean") - { - hFile << "inline bool " << tagS.simpleType() << "::" << getS - << "() const {" << std::endl - << " return " << typeS << ";" << std::endl - << "}" << std::endl << std::endl; - } - else if (guessType(typeS) == "Particle_t") - { - hFile << "inline Particle_t " << tagS.simpleType() - << "::" << getS << "() const {" << std::endl - << " return (Particle_t)" << lookupParticle(typeS) - << ";" << std::endl - << "}" << std::endl << std::endl; - } - else /* anything not listed above is classed as a string */ - { - hFile << "inline std::string " << tagS.simpleType() - << "::" << getS << "() const {" << std::endl - << " return \"" << typeS << "\";" << std::endl - << "}" << std::endl << std::endl; - } - } - - if (tagS == "HDDM") - { - hFile << "inline void HDDM::clear() {" << std::endl; - for (citer = children[tagS].begin(); - citer != children[tagS].end(); - ++citer) - { - DOMElement *childEl = (DOMElement*)(*citer); - XtString cnameS(childEl->getTagName()); - hFile << " delete" << cnameS.simpleType().plural() - << "();" << std::endl; - } - hFile << "#ifdef HDF5_SUPPORT" << std::endl - << " if (m_hdf5_record_count > 0) {" << std::endl - << " for (unsigned i=0; i < m_hdf5_strings.size(); ++i) {" - << std::endl - << " m_hdf5_strings[i]->std::string::~string();" - << std::endl - << " }" << std::endl - << " m_hdf5_strings.clear();" << std::endl - << " H5Dvlen_reclaim(s_hdf5_memorytype[\"HDDM\"]," << std::endl - << " s_hdf5_memoryspace[\"HDDM\"]," << std::endl - << " H5P_DEFAULT, &m_hdf5_record);" << std::endl - << " m_hdf5_record_count = 0;" << std::endl - << " }" << std::endl - << "#endif" << std::endl - << "}" << std::endl << std::endl; - } - hFile << "inline const void *" << tagS.simpleType() - << "::getAttribute(const std::string &name,\n" - << " " - << "hddm_type *atype) const {" << std::endl; - for (unsigned int n = 0; n < myAttr->getLength(); n++) - { - XtString attrS(myAttr->item(n)->getNodeName()); - XtString typeS(el->getAttribute(X(attrS))); - hFile << " if (name == \"" << attrS << "\") {\n" - << " if (atype != 0)\n"; - if (typeS == "int") - { - hFile << " *atype = k_hddm_int;\n"; - } - else if (typeS == "long") - { - hFile << " *atype = k_hddm_long;\n"; - } - else if (typeS == "float") - { - hFile << " *atype = k_hddm_float;\n"; - } - else if (typeS == "double") - { - hFile << " *atype = k_hddm_double;\n"; - } - else if (typeS == "boolean") - { - hFile << " *atype = k_hddm_boolean;\n"; - } - else if (typeS == "string") - { - hFile << " *atype = k_hddm_string;\n"; - } - else if (typeS == "anyURI") - { - hFile << " *atype = k_hddm_anyURI;\n"; - } - else if (typeS == "Particle_t") - { - hFile << " *atype = k_hddm_Particle_t;\n"; - } - else if (guessType(typeS) == "int") - { - hFile << " *atype = k_hddm_int;\n" - << " static int m_" << attrS - << " = get" << attrS.simpleType() << "();\n"; - } - else if (guessType(typeS) == "long") - { - hFile << " *atype = k_hddm_long;\n" - << " static long m_" << attrS - << " = get" << attrS.simpleType() << "();\n"; - } - else if (guessType(typeS) == "float") - { - hFile << " *atype = k_hddm_float;\n" - << " static float m_" << attrS - << " = get" << attrS.simpleType() << "();\n"; - } - else if (guessType(typeS) == "double") - { - hFile << " *atype = k_hddm_double;\n" - << " static double m_" << attrS - << " = get" << attrS.simpleType() << "();\n"; - } - else if (guessType(typeS) == "boolean") - { - hFile << " *atype = k_hddm_boolean;\n" - << " static int m_" << attrS - << " = get" << attrS.simpleType() << "();\n"; - } - else if (guessType(typeS) == "Particle_t") - { - hFile << " *atype = k_hddm_Particle_t;\n" - << " static Particle_t m_" << attrS - << " = get" << attrS.simpleType() << "();\n"; - } - else - { - hFile << " *atype = k_hddm_unknown;\n" - << " static std::string m_" << attrS - << " = get" << attrS.simpleType() << "();\n"; - } - hFile << " return &m_" << attrS << ";\n" - << " }\n"; - } - if (tagS != "HDDM") - { - hFile << " return m_parent->getAttribute(name, atype);" << std::endl; - } - else - { - hFile << " return 0;" << std::endl; - } - hFile << "}" << std::endl << std::endl; - - cFile << "std::string " << tagS.simpleType() - << "::toString(int indent) {\n" - << " std::stringstream ostr;\n" - << " for (int n=0; n < indent; ++n)\n" - << " ostr << \" \";\n" - << " ostr << \"" << tagS << "\"\n"; - for (unsigned int n = 0; n < myAttr->getLength(); n++) - { - XtString attrS(myAttr->item(n)->getNodeName()); - XtString typeS(el->getAttribute(X(attrS))); - if (typeS == "int" || typeS == "long" || - typeS == "float" || typeS == "double") - { - cFile << " << \" " << attrS << "=\" << " - << "m_" << attrS << std::endl; - } - else if (typeS == "boolean") - { - cFile << " << \" " << attrS << "=\" << " - << "((m_" << attrS << " == 0)? \"true\" : \"false\")" - << std::endl; - } - else if (typeS == "string" || typeS == "anyURI") - { - cFile << " << \" " << attrS << "=\" << " - << "\"\\\"\" << m_" << attrS << " << \"\\\"\"" << std::endl; - } - else if (typeS == "Particle_t") - { - cFile << " << \" " << attrS << "=\" << " - << "ParticleType((Particle_t)m_" << attrS << ")" << std::endl; - } - } - cFile << " << std::endl;" << std::endl; - for (citer = children[tagS].begin(); citer != children[tagS].end(); ++citer) - { - DOMElement *childEl = (DOMElement*)(*citer); - XtString cnameS(childEl->getTagName()); - XtString repS(childEl->getAttribute(X("maxOccurs"))); - int rep = (repS == "unbounded")? INT_MAX : atoi(S(repS)); - if (rep > 1) - { - cFile << " int " << cnameS.listType() << "Count=0;" << std::endl - << " for (" << cnameS.listType() << "::iterator it = " - << "m_" << cnameS << "_list.begin();" << std::endl - << " it != " - << "m_" << cnameS << "_list.end(); ++it)" << std::endl - << " {" << std::endl - << " if (++" << cnameS.listType() << "Count > " - << "m_" << cnameS << "_list.size()) {" << std::endl - << " throw std::runtime_error(\"hddm_" - << classPrefix << "::toString error - " - "list improperly terminated!\");" << std::endl - << " }" << std::endl - << " ostr << it->toString(indent + 2);" << std::endl - << " }" << std::endl; - } - else - { - cFile << " if (! m_" << cnameS << "_link.empty()) {\n" - << " ostr << m_" << cnameS << "_link.begin()" - << "->toString(indent + 2);\n" - << " }" << std::endl; - } - } - cFile << " return ostr.str();" << std::endl - << "}" << std::endl << std::endl; - - cFile << "std::string " << tagS.simpleType() - << "::toXML(int indent) {\n" - << " std::stringstream ostr;\n" - << " for (int n=0; n < indent; ++n)\n" - << " ostr << \" \";\n" - << " ostr << \"<" << tagS << "\"\n"; - for (unsigned int n = 0; n < myAttr->getLength(); n++) - { - XtString attrS(myAttr->item(n)->getNodeName()); - XtString typeS(el->getAttribute(X(attrS))); - if (attrS == "minOccurs" || attrS == "maxOccurs") - { - continue; - } - if (typeS == "boolean") - { - cFile << " << \" " << attrS << "=\" << " - << "((m_" << attrS << " == 0)? \"\\\"true\\\"\" : \"\\\"false\\\"\")" - << std::endl; - } - else if (typeS == "Particle_t") - { - cFile << " << \" " << attrS << "=\\\"\" << " - << "ParticleType((Particle_t)m_" << attrS << ") << \"\\\"\"" - << std::endl; - } - else - { - cFile << " << \" " << attrS << "=\" << " - << "\"\\\"\" << get" << attrS.simpleType() - << "() << \"\\\"\"" << std::endl; - } - } - if (children[tagS].size() > 0) - { - cFile << " << \">\" << std::endl;" << std::endl; - } - else - { - cFile << " << \" />\" << std::endl;" << std::endl; - } - for (citer = children[tagS].begin(); citer != children[tagS].end(); ++citer) - { - DOMElement *childEl = (DOMElement*)(*citer); - XtString cnameS(childEl->getTagName()); - XtString repS(childEl->getAttribute(X("maxOccurs"))); - int rep = (repS == "unbounded")? INT_MAX : atoi(S(repS)); - if (rep > 1) - { - cFile << " int " << cnameS.listType() << "Count=0;" << std::endl - << " for (" << cnameS.listType() << "::iterator it = " - << "m_" << cnameS << "_list.begin();" << std::endl - << " it != " - << "m_" << cnameS << "_list.end(); ++it)" << std::endl - << " {" << std::endl - << " if (++" << cnameS.listType() << "Count > " - << "m_" << cnameS << "_list.size()) {" << std::endl - << " throw std::runtime_error(\"hddm_" - << classPrefix << "::toXML error - " - "list improperly terminated!\");" << std::endl - << " }" << std::endl - << " ostr << it->toXML(indent + 2);" << std::endl - << " }" << std::endl; - } - else - { - cFile << " if (! m_" << cnameS << "_link.empty()) {\n" - << " ostr << m_" << cnameS << "_link.begin()" - << "->toXML(indent + 2);" << std::endl - << " }" << std::endl; - } - } - if (children[tagS].size() > 0) - { - cFile << " for (int n=0; n < indent; ++n)\n" - << " ostr << \" \";\n" - << " ostr << \"\"\n" - << " << std::endl;" << std::endl; - } - cFile << " return ostr.str();" << std::endl - << "}" << std::endl << std::endl; - - cFile << "#ifdef HDF5_SUPPORT" << std::endl - << "hid_t " << tagS.simpleType() - << "::hdf5Datatype(int inmemory, int verbose)" << std::endl - << "{" << std::endl - << " std::string tname(\"" << tagS << "\");" << std::endl - << " if (inmemory) {" << std::endl - << " if (HDDM::s_hdf5_memorytype.find(tname)" - << " != HDDM::s_hdf5_memorytype.end())" << std::endl - << " return HDDM::s_hdf5_memorytype[tname];" << std::endl - << " }" << std::endl - << " else {" << std::endl - << " if (HDDM::s_hdf5_datatype.find(tname)" - << " != HDDM::s_hdf5_datatype.end())" << std::endl - << " return HDDM::s_hdf5_datatype[tname];" << std::endl - << " }" << std::endl - << " hid_t tid = H5Tcreate(H5T_COMPOUND, sizeof(*this));" - << std::endl - << " hid_t vl_string_tid = H5Tcopy(H5T_C_S1);" << std::endl - << " H5Tset_size(vl_string_tid, H5T_VARIABLE);" << std::endl; - if (tagS != "HDDM") { - for (unsigned int n = 0; n < myAttr->getLength(); n++) - { - XtString attrS(myAttr->item(n)->getNodeName()); - XtString typeS(el->getAttribute(X(attrS))); - if (typeS == "int") - { - cFile << " H5Tinsert(tid, \"" << attrS << "\", " - << "(char*)&m_" << attrS << " - (char*)this, " - << "((inmemory)? H5T_NATIVE_INT : H5T_STD_I32LE));" - << std::endl; - } - else if (typeS == "long") - { - cFile << " H5Tinsert(tid, \"" << attrS << "\", " - << "(char*)&m_" << attrS << " - (char*)this, " - << "((inmemory)? H5T_NATIVE_LONG : H5T_STD_I64LE));" - << std::endl; - } - else if (typeS == "float") - { - cFile << " H5Tinsert(tid, \"" << attrS << "\", " - << "(char*)&m_" << attrS << " - (char*)this, " - << "((inmemory)? H5T_NATIVE_FLOAT : H5T_IEEE_F32LE));" - << std::endl; - } - else if (typeS == "double") - { - cFile << " H5Tinsert(tid, \"" << attrS << "\", " - << "(char*)&m_" << attrS << " - (char*)this, " - << "((inmemory)? H5T_NATIVE_DOUBLE : H5T_IEEE_F64LE));" - << std::endl; - } - else if (typeS == "boolean") - { - cFile << " H5Tinsert(tid, \"" << attrS << "\", " - << "(char*)&m_" << attrS << " - (char*)this, " - << "((inmemory)? H5T_NATIVE_INT : H5T_STD_I32LE));" - << std::endl; - } - else if (typeS == "string") - { - cFile << " H5Tinsert(tid, \"" << attrS << "\", " - << "(char*)&mx_" << attrS << " - (char*)this, " - << "vl_string_tid);" - << std::endl; - } - else if (typeS == "anyURI") - { - cFile << " H5Tinsert(tid, \"" << attrS << "\", " - << "(char*)&mx_" << attrS << " - (char*)this, " - << "vl_string_tid);" - << std::endl; - } - else if (typeS == "Particle_t") - { - cFile << " H5Tinsert(tid, \"" << attrS << "\", " - << "(char*)&m_" << attrS << " - (char*)this, " - << "((inmemory)? H5T_NATIVE_INT : H5T_STD_I32LE));" - << std::endl; - } - } - for (citer = children[tagS].begin(); citer != children[tagS].end(); ++citer) - { - DOMElement *childEl = (DOMElement*)(*citer); - XtString cnameS(childEl->getTagName()); - XtString repS(childEl->getAttribute(X("maxOccurs"))); - int rep = (repS == "unbounded")? INT_MAX : atoi(S(repS)); - cFile << " H5Tinsert(tid, \"" << cnameS.listType() << "_size\", " - << "(char*)&m_" << cnameS - << ((rep > 1)? "_list" : "_link") << ".m_size - (char*)this, " - << "((inmemory)? H5T_NATIVE_INT : H5T_STD_I16LE));" - << std::endl; - cFile << " H5Tinsert(tid, \"" << cnameS.listType() << "_offset\", " - << "(char*)&m_" << cnameS - << ((rep > 1)? "_list" : "_link") << ".m_ref - (char*)this, " - << "((inmemory)? H5T_NATIVE_INT : H5T_STD_I16LE));" - << std::endl; - } - } - else { - cFile << " hid_t vl_tid;" << std::endl; - parentTable_t::iterator piter; - for (piter = parents.begin(); piter != parents.end(); ++piter) - { - XtString dnameS(piter->first); - if (dnameS != "HDDM") { - cFile << " " << dnameS.simpleType() - << " l_" << dnameS << ";" << std::endl - << " vl_tid = H5Tvlen_create(l_" << dnameS - << ".hdf5Datatype(inmemory));" << std::endl - << " H5Tinsert(tid, \"vl_" << dnameS << "\", " - << "(char*)&m_hdf5_record.vl_" << dnameS - << " - (char*)&m_hdf5_record, vl_tid);" - << std::endl; - } - } - cFile << " if (inmemory == 0)" << std::endl - << " H5Tpack(tid);" << std::endl; - } - cFile << " if (inmemory) {" << std::endl - << " HDDM::s_hdf5_memorytype[\"" << tagS << "\"] = tid;" - << std::endl - << " }" << std::endl - << " else {" << std::endl - << " HDDM::s_hdf5_datatype[\"" << tagS << "\"] = tid;" << std::endl - << " }" << std::endl - << " if (verbose) {" << std::endl - << " size_t slen;" << std::endl - << " H5LTdtype_to_text(tid, 0, H5LT_DDL, &slen);" << std::endl - << " char *ddlstring = (char*)malloc(slen);" << std::endl - << " H5LTdtype_to_text(tid, ddlstring, H5LT_DDL, &slen);" << std::endl - << " if (inmemory)" << std::endl - << " printf(\"=== in-memory datatype %ld for %s is:\\n %s\\n\"," - << " tid, \"" << tagS << "\", ddlstring);" << std::endl - << " else" << std::endl - << " printf(\"=== on-disk datatype %ld for %s is:\\n %s\\n\"," - << " tid, \"" << tagS << "\", ddlstring);" << std::endl - << " free(ddlstring);" << std::endl - << " }" << std::endl - << " return tid;" << std::endl - << "}" << std::endl; - - if (tagS == "HDDM") { - cFile << "herr_t " << tagS.simpleType() - << "::hdf5FileStamp(hid_t file_id, char **tags)" << std::endl - << "{" << std::endl - << " std::string stamp(DocumentString());" << std::endl - << " while (tags != 0 && *tags != 0) {" << std::endl - << " stamp += \"\";" << std::endl - << " stamp += *tags;" << std::endl - << " stamp += \"\\n\";" << std::endl - << " ++tags;" << std::endl - << " }" << std::endl - << " hid_t stamp_tid = H5Tcopy(H5T_C_S1);" << std::endl - << " H5Tset_size(stamp_tid, H5T_VARIABLE);" << std::endl - << " hsize_t dims[1] = {1};" << std::endl - << " hsize_t maxdims[1] = {1};" << std::endl - << " hid_t stamp_sid = H5Screate_simple(1, dims, maxdims);" - << std::endl - << " char *pstamp = (char*)stamp.c_str();" - << std::endl - << " hid_t stamp_id =" - << " H5Lexists(file_id, \"HDDMstamp\", H5P_DEFAULT);" << std::endl - << " if (stamp_id > 0) {" << std::endl - << " stamp_id = H5Dopen(file_id, \"HDDMstamp\"," - << " H5P_DEFAULT);" << std::endl - << " }" << std::endl - << " else {" << std::endl - << " stamp_id = H5Dcreate(file_id, \"HDDMstamp\"," - << std::endl - << " stamp_tid, stamp_sid," - << std::endl - << " H5P_DEFAULT, H5P_DEFAULT," - << std::endl - << " H5P_DEFAULT);" - << std::endl - << " }" << std::endl - << " herr_t res = H5Dwrite(stamp_id, stamp_tid," - << std::endl - << " H5S_ALL, H5S_ALL," - << std::endl - << " H5P_DEFAULT, &pstamp);" - << std::endl - << " return res;" << std::endl - << "}" << std::endl; - cFile << "herr_t " << tagS.simpleType() - << "::hdf5FileCheck(hid_t file_id, char **tags)" << std::endl - << "{" << std::endl - << " char *pstamp;" << std::endl - << " hid_t stamp_id = H5Dopen(file_id, \"HDDMstamp\"," - << " H5P_DEFAULT);" << std::endl - << " hid_t stamp_sid = H5Dget_space(stamp_id);" << std::endl - << " hid_t stamp_tid = H5Dget_type(stamp_id);" << std::endl - << " stamp_tid = H5Tget_native_type(stamp_tid, H5T_DIR_DEFAULT);" - << std::endl - << " herr_t res = H5Dread(stamp_id, stamp_tid," << std::endl - << " H5S_ALL, H5S_ALL," << std::endl - << " H5P_DEFAULT, &pstamp);" << std::endl - << " std::string sstamp(pstamp);" << std::endl - << " H5Dvlen_reclaim(stamp_tid, stamp_sid," << std::endl - << " H5P_DEFAULT, &pstamp);" << std::endl - << " if (sstamp.find(DocumentString()) != 0) {" << std::endl - << " throw std::runtime_error(\"hddm_" - << classPrefix << "::hdf5FileCheck - \"" << std::endl - << " \"HDF5 input record format mismatch!\");" - << std::endl - << " }" << std::endl - << " while (tags != 0 && *tags != 0) {" << std::endl - << " std::string stag(\"\");" << std::endl - << " stag += *tags;" << std::endl - << " stag += \"\";" << std::endl - << " if (sstamp.find(stag) == sstamp.npos) {" << std::endl - << " throw std::runtime_error(\"hddm_" - << classPrefix << "::hdf5FileCheck - \"" << std::endl - << " \"HDF5 input record tag is missing!\");" - << std::endl - << " }" << std::endl - << " ++tags;" << std::endl - << " }" < &filters)" - << std::endl - << "{" << std::endl - << " hid_t chunking_id;" << std::endl - << " if (s_hdf5_chunking.find(file_id)" - << " == s_hdf5_chunking.end()) {" << std::endl - << " chunking_id = H5Pcreate(H5P_DATASET_CREATE);" - << std::endl - << " s_hdf5_chunking[file_id] = chunking_id;" << std::endl - << " }" << std::endl - << " else {" << std::endl - << " chunking_id = s_hdf5_chunking[file_id];" << std::endl - << " }" << std::endl - << " for (auto filter : filters) {" << std::endl - << " if (filter == H5Z_FILTER_DEFLATE) {" << std::endl - << " H5Pset_deflate(chunking_id, 9);" << std::endl - << " }" << std::endl - << " else if (filter == H5Z_FILTER_SZIP) {" << std::endl - << " H5Pset_szip(chunking_id, H5_SZIP_NN_OPTION_MASK, 8);" - << std::endl - << " }" << std::endl - << " else if (filter == H5Z_FILTER_SHUFFLE) {" << std::endl - << " H5Pset_shuffle(chunking_id);" << std::endl - << " }" << std::endl - << " else if (filter == H5Z_FILTER_SCALEOFFSET) {" << std::endl - << " H5Pset_scaleoffset(chunking_id, H5Z_SO_INT," << std::endl - << " H5Z_SO_INT_MINBITS_DEFAULT);" - << std::endl - << " }" << std::endl - << " else if (filter == H5Z_FILTER_NBIT) {" << std::endl - << " H5Pset_nbit(chunking_id);" << std::endl - << " }" << std::endl - << " else if (filter == H5Z_FILTER_FLETCHER32) {" << std::endl - << " H5Pset_fletcher32(chunking_id);" << std::endl - << " }" << std::endl - << " else {" << std::endl - << " unsigned int cd_values[] = {6};" << std::endl - << " H5Pset_filter(chunking_id, filter," << std::endl - << " H5Z_FLAG_MANDATORY, (size_t)1, cd_values);" - << " }" << std::endl - << std::endl - << " }" << std::endl - << " return 0;" << std::endl - << "}" << std::endl; - cFile << "herr_t " << tagS.simpleType() << "::hdf5GetFilters" - << "(hid_t file_id, std::vector &filters)" - << std::endl - << "{" << std::endl - << " filters.clear();" << std::endl - << " if (s_hdf5_chunking.find(file_id)" - << " == s_hdf5_chunking.end()) {" << std::endl - << " return 0;" << std::endl - << " }" << std::endl - << " hid_t chunking_id = s_hdf5_chunking[file_id];" - << std::endl - << " for (int i=0; i < H5Pget_nfilters(chunking_id); ++i) {" - << std::endl - << " unsigned int flags;" << std::endl - << " size_t cd_nelmts = 9;" << std::endl - << " unsigned int cd_values[9];" << std::endl - << " size_t namelen = 99;" << std::endl - << " char name[99];" << std::endl - << " unsigned int filter_config;" << std::endl - << " filters.push_back(H5Pget_filter2(chunking_id, i," - << std::endl - << " &flags, &cd_nelmts, cd_values," - << std::endl - << " namelen, name, &filter_config));" - << std::endl - << " }" << std::endl - << " return 0;" << std::endl - << "}" << std::endl; - cFile << "herr_t " << tagS.simpleType() << "::hdf5FileWrite" - << "(hid_t file_id, long int entry)" << std::endl - << "{" << std::endl - << " hdf5_record_t hdf5_record;" << std::endl - << " int size;\n" << std::endl - << " int len;\n" << std::endl; - parentTable_t::iterator piter; - for (piter = parents.begin(); piter != parents.end(); ++piter) - { - XtString dnameS(piter->first); - if (dnameS != "HDDM") { - cFile << " if ((len = hdf5_record.vl_" << dnameS << ".len" - << " = m_" << dnameS << "_plist.size()) > 0) {" - << std::endl - << " size = sizeof(" << dnameS.simpleType() << ");" - << std::endl - << " hdf5_record.vl_" << dnameS << ".p" - << " = malloc(len * size);" << std::endl - << " std::list<" << dnameS.simpleType() << "*>" - << "::iterator iter = m_" << dnameS << "_plist.begin();" - << std::endl - << " " << dnameS.simpleType() << " *p = " - << "(" << dnameS.simpleType() << "*)hdf5_record.vl_" - << dnameS << ".p;" << std::endl - << " for (int i=0; i < len; ++i, ++iter) {" << std::endl - << " hdf5_memcpy(p+i, *iter, size);" << std::endl - << " p[i].hdf5DataPack();" << std::endl - << " }" << std::endl - << " }" << std::endl; - } - } - cFile << " hid_t eventtype_id = hdf5Datatype();" << std::endl - << " hid_t memorytype_id = hdf5Datatype(1);" << std::endl - << " hid_t chunking_id;" << std::endl - << " if (s_hdf5_chunking.find(file_id)" - << " == s_hdf5_chunking.end()) {" << std::endl - << " hdf5SetChunksize(file_id, HDF5_DEFAULT_CHUNK_SIZE);" - << std::endl - << " }" << std::endl - << " chunking_id = s_hdf5_chunking[file_id];" << std::endl - << " hid_t memoryspace_id;" << std::endl - << " if (s_hdf5_memoryspace.find(\"HDDM\")" - << " == s_hdf5_memoryspace.end()) {" << std::endl - << " hsize_t dims[1] = {1};" << std::endl - << " hsize_t maxdims[1] = {H5S_UNLIMITED};" << std::endl - << " memoryspace_id = H5Screate_simple(1, dims, maxdims);" - << std::endl - << " s_hdf5_memoryspace[\"HDDM\"] = memoryspace_id;" - << std::endl - << " }" << std::endl - << " else {" << std::endl - << " memoryspace_id = s_hdf5_memoryspace[\"HDDM\"];" - << std::endl - << " }" << std::endl - << " hid_t eventspace_id;" << std::endl - << " if (s_hdf5_dataspace.find(file_id)" - << " == s_hdf5_dataspace.end()) {" << std::endl - << " hsize_t dims[1] = {1};" << std::endl - << " hsize_t maxdims[1] = {H5S_UNLIMITED};" << std::endl - << " eventspace_id = H5Screate_simple(1, dims, maxdims);" - << std::endl - << " s_hdf5_dataspace[file_id] = eventspace_id;" << std::endl - << " }" << std::endl - << " else {" << std::endl - << " eventspace_id = HDDM::s_hdf5_dataspace[file_id];" - << std::endl - << " }" << std::endl - << " hid_t eventdata_id;" << std::endl - << " if (s_hdf5_dataset.find(file_id)" - << " == s_hdf5_dataset.end()) {" - << std::endl - << " eventdata_id = H5Dcreate(file_id, \"HDDMevents\"," - << std::endl - << " eventtype_id, eventspace_id," - << std::endl - << " H5P_DEFAULT, chunking_id," - << std::endl - << " H5P_DEFAULT);" - << std::endl - << " s_hdf5_dataset[file_id] = eventdata_id;" << std::endl - << " m_hdf5_record_extent = 0;" << std::endl - << " m_hdf5_record_offset = 0;" - << std::endl - << " }" << std::endl - << " else {" << std::endl - << " eventdata_id = s_hdf5_dataset[file_id];" << std::endl - << " hsize_t maxdims;" << std::endl - << " H5Sget_simple_extent_dims(eventspace_id," - << " &m_hdf5_record_extent, &maxdims);" << std::endl - << " H5Sget_select_bounds(eventspace_id," - << " &m_hdf5_record_offset, &maxdims);" << std::endl - << " ++m_hdf5_record_offset;" << std::endl - << " }" << std::endl - << " if (entry >= 0) {" << std::endl - << " m_hdf5_record_offset = entry;" << std::endl - << " }" << std::endl - << " if (m_hdf5_record_offset >= m_hdf5_record_extent) {" - << std::endl - << " m_hdf5_record_extent = m_hdf5_record_offset + 1;" - << std::endl - << " H5Dset_extent(eventdata_id, &m_hdf5_record_extent);" - << std::endl - << " H5Sclose(eventspace_id);" - << std::endl - << " eventspace_id = H5Dget_space(eventdata_id);" - << std::endl - << " s_hdf5_dataspace[file_id] = eventspace_id;" - << std::endl - << " }" - << std::endl - << " hsize_t hdf5_record_count = 1;" - << std::endl - << " H5Sselect_hyperslab(eventspace_id, H5S_SELECT_SET," - << std::endl - << " &m_hdf5_record_offset, NULL," - << std::endl - << " &hdf5_record_count, NULL);" - << std::endl - << " herr_t res = H5Dwrite(eventdata_id, memorytype_id," - << std::endl - << " memoryspace_id, eventspace_id," - << std::endl - << " H5P_DEFAULT, &hdf5_record);" - << std::endl; - for (piter = parents.begin(); piter != parents.end(); ++piter) - { - XtString dnameS(piter->first); - if (dnameS != "HDDM") { - cFile << " if ((len = hdf5_record.vl_" << dnameS << ".len" - << " = m_" << dnameS << "_plist.size()) > 0) {" - << std::endl - << " free(hdf5_record.vl_" << dnameS << ".p);" - << std::endl - << " }" << std::endl; - } - } - cFile << " return res;" << std::endl - << "}" << std::endl; - cFile << "herr_t " << tagS.simpleType() << "::hdf5FileRead" - << "(hid_t file_id, long int entry)" << std::endl - << "{" << std::endl - << " clear();" << std::endl - << " hid_t memorytype_id = hdf5Datatype(1);" << std::endl - << " hid_t memoryspace_id;" << std::endl - << " if (s_hdf5_memoryspace.find(\"HDDM\")" - << " == s_hdf5_memoryspace.end()) {" << std::endl - << " hsize_t dims[1] = {1};" << std::endl - << " hsize_t maxdims[1] = {H5S_UNLIMITED};" << std::endl - << " memoryspace_id = H5Screate_simple(1, dims, maxdims);" - << std::endl - << " s_hdf5_memoryspace[\"HDDM\"] = memoryspace_id;" - << std::endl - << " }" << std::endl - << " else {" << std::endl - << " memoryspace_id = s_hdf5_memoryspace[\"HDDM\"];" - << std::endl - << " }" << std::endl - << " hid_t eventdata_id;" << std::endl - << " hid_t chunking_id;" << std::endl - << " if (s_hdf5_dataset.find(file_id)" - << " == s_hdf5_dataset.end()) {" << std::endl - << std::endl - << " eventdata_id = H5Dopen(file_id, \"HDDMevents\"," - << std::endl - << " H5P_DEFAULT);" - << std::endl - << " chunking_id = H5Dget_create_plist(eventdata_id);" - << std::endl - << " s_hdf5_dataset[file_id] = eventdata_id;" - << " s_hdf5_chunking[file_id] = chunking_id;" - << std::endl - << " }" << std::endl - << " else {" << std::endl - << " eventdata_id = s_hdf5_dataset[file_id];" << std::endl - << " chunking_id = s_hdf5_chunking[file_id];" - << std::endl - << " }" << std::endl - << " hid_t eventspace_id;" << std::endl - << " if (s_hdf5_dataspace.find(file_id)" - << " == s_hdf5_dataspace.end()) {" << std::endl - << " eventspace_id = H5Dget_space(eventdata_id);" << std::endl - << " s_hdf5_dataspace[file_id] = eventspace_id;" << std::endl - << " hsize_t maxdims;" << std::endl - << " H5Sget_simple_extent_dims(eventspace_id," - << " &m_hdf5_record_extent, &maxdims);" << std::endl - << " m_hdf5_record_offset = 0;" << std::endl - << " }" << std::endl - << " else {" << std::endl - << " eventspace_id = HDDM::s_hdf5_dataspace[file_id];" - << std::endl - << " hsize_t maxdims;" << std::endl - << " H5Sget_simple_extent_dims(eventspace_id," - << " &m_hdf5_record_extent, &maxdims);" << std::endl - << " H5Sget_select_bounds(eventspace_id," - << " &m_hdf5_record_offset, &maxdims);" << std::endl - << " ++m_hdf5_record_offset;" << std::endl - << " }" << std::endl - << " if (entry >= 0) {" << std::endl - << " m_hdf5_record_offset = entry;" << std::endl - << " }" << std::endl - << " if (m_hdf5_record_offset >= m_hdf5_record_extent)" - << std::endl - << " return -1;" << std::endl - << " m_hdf5_record_count = 1;" << std::endl - << " H5Sselect_hyperslab(eventspace_id, H5S_SELECT_SET," - << std::endl - << " &m_hdf5_record_offset, NULL," - << std::endl - << " &m_hdf5_record_count, NULL);" - << std::endl - << " herr_t res = H5Dread(eventdata_id, memorytype_id," - << std::endl - << " memoryspace_id, eventspace_id," - << std::endl - << " H5P_DEFAULT, &m_hdf5_record);" - << std::endl - << " int len;" << std::endl; - for (piter = parents.begin(); piter != parents.end(); ++piter) - { - XtString dnameS(piter->first); - if (dnameS != "HDDM") { - cFile << " if ((len = m_hdf5_record.vl_" << dnameS << ".len)" - << " > 0) {" << std::endl - << " " << dnameS.simpleType() << " *p =" - << "(" << dnameS.simpleType() << "*)" - << "m_hdf5_record.vl_" << dnameS << ".p;" << std::endl - << " for (int i=0; i < len; ++i ) {" << std::endl - << " m_" << dnameS << "_plist.push_back(" - << "new(p+i) " << dnameS.simpleType() << ");" - << std::endl - << " }" << std::endl - << " }" << std::endl; - } - } - for (citer = children[tagS].begin(); citer != children[tagS].end(); ++citer) - { - DOMElement *childEl = (DOMElement*)(*citer); - XtString cnameS(childEl->getTagName()); - XtString repS(childEl->getAttribute(X("maxOccurs"))); - int rep = (repS == "unbounded")? INT_MAX : atoi(S(repS)); - cFile << " new(&m_" << cnameS << ((rep > 1)? "_list)" : "_link)") - << " " << ((rep > 1)? cnameS.listType() : cnameS.linkType()) - << "(&m_" << cnameS << "_plist," << std::endl - << " m_" << cnameS << "_plist.begin()," << std::endl - << " m_" << cnameS << "_plist.end()," << std::endl - << " this);" << std::endl; - } - cFile << " hdf5DataUnpack();" << std::endl - << " return res;" << std::endl - << "}" << std::endl; - cFile << "hid_t " << tagS.simpleType() << "::hdf5FileCreate(" - << "std::string name, unsigned int flags)" << std::endl - << "{" << std::endl - << " hid_t file_id = H5Fcreate(name.c_str(), flags," - << " H5P_DEFAULT, H5P_DEFAULT);" << std::endl - << " hdf5FileStamp(file_id);" << std::endl - << " return file_id;" << std::endl - << "}" << std::endl; - cFile << "hid_t " << tagS.simpleType() << "::hdf5FileOpen(" - << "std::string name, unsigned int flags)" << std::endl - << "{" << std::endl - << " hid_t file_id = H5Fopen(name.c_str(), flags, H5P_DEFAULT);" - << std::endl - << " hdf5FileCheck(file_id);" << std::endl - << " return file_id;" << std::endl - << "}" << std::endl; - cFile << "herr_t " << tagS.simpleType() << "::hdf5FileClose(" - << "hid_t file_id)" << std::endl - << "{" << std::endl - << " herr_t res = H5Fclose(file_id);" << std::endl - << " if (HDDM::s_hdf5_dataspace.find(file_id) !=" - << " HDDM::s_hdf5_dataspace.end()) {" << std::endl - << " H5Sclose(s_hdf5_dataspace[file_id]);" << std::endl - << " s_hdf5_dataspace.erase(file_id);" << std::endl - << " }" << std::endl - << " if (s_hdf5_chunking.find(file_id) !=" - << " s_hdf5_chunking.end()) {" << std::endl - << " H5Pclose(s_hdf5_chunking[file_id]);" << std::endl - << " s_hdf5_chunking.erase(file_id);" << std::endl - << " }" << std::endl - << " if (s_hdf5_dataset.find(file_id) !=" - << " s_hdf5_dataset.end()) {" << std::endl - << " H5Dclose(s_hdf5_dataset[file_id]);" << std::endl - << " s_hdf5_dataset.erase(file_id);" << std::endl - << " }" << std::endl - << " return res;" << std::endl - << "}" << std::endl << std::endl; - } - cFile << "void " << tagS.simpleType() << "::hdf5DataPack()" - << std::endl - << "{" << std::endl; - for (unsigned int n = 0; n < myAttr->getLength(); n++) - { - XtString attrS(myAttr->item(n)->getNodeName()); - XtString typeS(el->getAttribute(X(attrS))); - if (typeS == "string" || typeS == "anyURI") - { - cFile << " mx_" << attrS << " = m_" << attrS << ".c_str();" - << std::endl; - } - } - for (citer = children[tagS].begin(); citer != children[tagS].end(); ++citer) - { - DOMElement *childEl = (DOMElement*)(*citer); - XtString cnameS(childEl->getTagName()); - XtString repS(childEl->getAttribute(X("maxOccurs"))); - int rep = (repS == "unbounded")? INT_MAX : atoi(S(repS)); - cFile << " m_" << cnameS << ((rep > 1)? "_list" : "_link") - << ".deflate();" << std::endl; - } - cFile << "}" << std::endl; - cFile << "void " << tagS.simpleType() << "::hdf5DataUnpack()" - << std::endl - << "{" << std::endl; - for (unsigned int n = 0; n < myAttr->getLength(); n++) - { - XtString attrS(myAttr->item(n)->getNodeName()); - XtString typeS(el->getAttribute(X(attrS))); - if (typeS == "string" || typeS == "anyURI") - { - cFile << " new(&m_" << attrS << ") std::string();" << std::endl - << " if (mx_" << attrS << " != 0) {" << std::endl - << " m_" << attrS << " = mx_" << attrS << ";" - << std::endl - << " m_host->m_hdf5_strings.push_back" - << "(&m_" << attrS << ");" << std::endl - << " }" << std::endl; - } - } - for (citer = children[tagS].begin(); citer != children[tagS].end(); ++citer) - { - DOMElement *childEl = (DOMElement*)(*citer); - XtString cnameS(childEl->getTagName()); - XtString repS(childEl->getAttribute(X("maxOccurs"))); - int rep = (repS == "unbounded")? INT_MAX : atoi(S(repS)); - cFile << " {" << std::endl - << " std::list<" << cnameS.simpleType() << "*> *host_plist =" - << " &m_host->m_" << cnameS << "_plist;" << std::endl - << " m_" << cnameS << ((rep > 1)? "_list" : "_link") - << ".inflate(m_host, host_plist, this);" << std::endl - << " " << cnameS.listType() << "::iterator iter;" << std::endl - << " for (iter = m_" << cnameS << ((rep > 1)? "_list" : "_link") - << ".begin();" << std::endl - << " iter != m_" << cnameS << ((rep > 1)? "_list" : "_link") - << ".end(); ++iter)" << std::endl - << " {" << std::endl - << " iter->hdf5DataUnpack();" << std::endl - << " }" << std::endl - << " }" << std::endl; - } - cFile << "}" << std::endl; - - cFile << "#endif" << std::endl << std::endl; - - for (citer = children[tagS].begin(); citer != children[tagS].end(); ++citer) - { - DOMElement *childEl = (DOMElement*)(*citer); - XtString cnameS(childEl->getTagName()); - XtString repS(childEl->getAttribute(X("maxOccurs"))); - int rep = (repS == "unbounded")? INT_MAX : atoi(S(repS)); - if (rep > 1) - { - hFile << "inline " << cnameS.simpleType() << " &" - << tagS.simpleType() << "::get" << cnameS.simpleType() - << "(int index) {" << std::endl - << " return m_" << cnameS << "_list(index);" << std::endl - << "}" << std::endl << std::endl - << "inline " << cnameS.listType() << " &" - << tagS.simpleType() << "::get" << cnameS.plural().simpleType() - << "() {" << std::endl - << " return m_" << cnameS << "_list;" << std::endl - << "}" << std::endl << std::endl - << "inline " << cnameS.listType() << " " - << tagS.simpleType() << "::add" << cnameS.plural().simpleType() - << "(int count, int start) {" << std::endl - << " return m_" << cnameS << "_list.add(count,start);" - << std::endl << "}" << std::endl << std::endl - << "inline void " << tagS.simpleType() << "::delete" - << cnameS.simpleType().plural() - << "(int count, int start) {" << std::endl - << " m_" << cnameS << "_list.del(count,start);" - << std::endl << "}" << std::endl << std::endl; - } - else - { - hFile << "inline " << cnameS.simpleType() << " &" - << tagS.simpleType() << "::get" << cnameS.simpleType() - << "() {" << std::endl - << " return m_" << cnameS << "_link.front();" << std::endl - << "}" << std::endl << std::endl - << "inline " << cnameS.listType() << " &" - << tagS.simpleType() << "::get" << cnameS.plural().simpleType() - << "() {" << std::endl - << " return m_" << cnameS << "_link;" << std::endl - << "}" << std::endl << std::endl - << "inline " << cnameS.listType() << " " - << tagS.simpleType() << "::add" << cnameS.plural().simpleType() - << "(int count, int start) {" << std::endl - << " return m_" << cnameS << "_link.add(count,start);" - << std::endl << "}" << std::endl << std::endl - << "inline void " << tagS.simpleType() << "::delete" - << cnameS.simpleType().plural() - << "(int count, int start) {" << std::endl - << " m_" << cnameS << "_link.del(count,start);" - << std::endl << "}" << std::endl << std::endl; - } - } - - if (tagS == "HDDM") - { - parentTable_t::iterator piter; - for (piter = parents.begin(); piter != parents.end(); ++piter) - { - XtString cnameS(piter->first); - if (cnameS != "HDDM" && element_in_list(cnameS,children[tagS]) == -1) - { - hFile << "inline " << cnameS.listType() << " " - << "HDDM::get" << cnameS.plural().simpleType() << "() {" - << std::endl << " return " << cnameS.listType() - << "(&m_" << cnameS << "_plist," << std::endl - << " " - << "m_" << cnameS << "_plist.begin()," << std::endl - << " " - << "m_" << cnameS << "_plist.end());" << std::endl - << "}" << std::endl << std::endl; - } - if (cnameS != "HDDM") - { - cFile << std::endl - << "void debug_print(" << cnameS.listType() << " &list) {" - << std::endl - << " list.debug_print();" << std::endl - << "}" << std::endl; - } - } - } -} - -/* Generate implementation code for data model classes */ - -void CodeBuilder::constructMethods(DOMElement* el) -{ - std::vector::iterator iter; - for (iter = tagList.begin(); iter != tagList.end(); iter++) - { - writeClassimp(*iter); - } -} - -/* Generate methods for serializing classes to a stream and back again */ - -void CodeBuilder::writeStreamers(DOMElement* el) -{ - XtString tagS(el->getTagName()); - - std::vector attrV; - DOMNamedNodeMap *myAttr = el->getAttributes(); - for (unsigned int n = 0; n < myAttr->getLength(); n++) - { - XtString attrS(myAttr->item(n)->getNodeName()); - XtString typeS(el->getAttribute(X(attrS))); - if (typeS == "int" || typeS == "long" || typeS == "float" || - typeS == "double" || typeS == "boolean" || typeS == "string" || - typeS == "anyURI" || typeS == "Particle_t") - { - attrV.push_back(attrS); - } - } - - std::vector contV; - DOMNodeList* contList = el->getChildNodes(); - int contListLength = contList->getLength(); - for (int c = 0; c < contListLength; c++) - { - DOMNode* node = contList->item(c); - if (node->getNodeType() == DOMNode::ELEMENT_NODE) - { - DOMElement *contEl = (DOMElement*)node; - XtString contS(contEl->getTagName()); - XtString repS(contEl->getAttribute(X("maxOccurs"))); - int rep = (repS == "unbounded")? INT_MAX : atoi(S(repS)); - contV.push_back(contS + ((rep > 1)? "_list" : "_link")); - } - } - - hFile << "inline void " << tagS.simpleType() << "::streamer" - << "(istream &istr) {" << std::endl; - if (attrV.size()) { - hFile << " *istr.getXDRistream()"; - for (unsigned int n=0; n < attrV.size(); ++n) - { - hFile << " >> m_" << attrV[n]; - } - hFile << ";" << std::endl; - } - if (contV.size()) { - hFile << " istr"; - for (unsigned int n=0; n < contV.size(); ++n) - { - hFile << " >> m_" << contV[n]; - } - hFile << ";" << std::endl; - } - hFile << "}" << std::endl << std::endl; - - hFile << "inline void " << tagS.simpleType() << "::streamer" - << "(ostream &ostr) {" << std::endl; - if (attrV.size()) { - hFile << " *ostr.getXDRostream()"; - for (unsigned int n=0; n < attrV.size(); ++n) - { - hFile << " << m_" << attrV[n]; - } - hFile << ";" << std::endl; - } - if (contV.size()) { - hFile << " ostr"; - for (unsigned int n=0; n < contV.size(); ++n) - { - hFile << " << m_" << contV[n]; - } - hFile << ";" << std::endl; - } - hFile << "}" << std::endl << std::endl; -} - -void CodeBuilder::constructStreamers(DOMElement* el) -{ - std::vector::iterator iter; - for (iter = tagList.begin(); iter != tagList.end(); ++iter) - { - writeStreamers(*iter); - } -} - -/* Generate methods to read from binary stream into classes */ - -void CodeBuilder::constructIOstreams(DOMElement* el) -{ - hFile << - "inline istream::thread_private_data *istream::lookup_private_data() {\n" - " thread_private_data *my_private = my_thread_private[threads::getID()];\n" - " if (my_private != 0)\n" - " return my_private;\n" - " init_private_data();\n" - " return my_thread_private[threads::ID];\n" - "}\n" - "\n" - "inline ostream::thread_private_data *ostream::lookup_private_data() {\n" - " thread_private_data *my_private = my_thread_private[threads::getID()];\n" - " if (my_private != 0)\n" - " return my_private;\n" - " init_private_data();\n" - " return my_thread_private[threads::ID];\n" - "}\n" - "\n" - "inline void istream::skip(int count) {\n" - " MY_SETUP\n" - " MY(events_to_skip) += count;\n" - "}\n" - "\n" - "inline bool istream::eof() {\n" - " MY_SETUP\n" - " return MY(hit_eof);\n" - "}\n" - "\n" - "inline bool istream::operator!() {\n" - " return eof();\n" - "}\n" - "\n" - "inline istream::operator void*() {\n" - " MY_SETUP\n" - " if (MY(hit_eof))\n" - " return NULL;\n" - " else\n" - " return this;\n" - "}\n" - "\n" - "inline int istream::getCompression() const {\n" - " return (int)m_status_bits & k_bits_compression;\n" - "}\n" - "\n" - "inline int ostream::getCompression() const {\n" - " return (int)m_status_bits & k_bits_compression;\n" - "}\n" - "\n" - "inline int istream::getIntegrityChecks() const {\n" - " return (int)m_status_bits & k_bits_integrity;\n" - "}\n" - "\n" - "inline int istream::getBytesRead() const {\n" - " int bytes = 0;\n" - " for (int i=1; i < threads::max_threads; ++i)\n" - " if (my_thread_private[i])\n" - " bytes += my_thread_private[i]->m_bytes_read;\n" - " return bytes;\n" - "}\n" - "\n" - "inline int istream::getRecordsRead() const {\n" - " int records = 0;\n" - " for (int i=1; i < threads::max_threads; ++i)\n" - " if (my_thread_private[i])\n" - " records += my_thread_private[i]->m_records_read;\n" - " return records;\n" - "}\n" - "\n" - "inline int ostream::getIntegrityChecks() const {\n" - " return (int)m_status_bits & k_bits_integrity;\n" - "}\n" - "\n" - "inline int ostream::getBytesWritten() const {\n" - " int bytes = 0;\n" - " for (int i=1; i < threads::max_threads; ++i)\n" - " if (my_thread_private[i])\n" - " bytes += my_thread_private[i]->m_bytes_written;\n" - " return bytes;\n" - "}\n" - "\n" - "inline int ostream::getRecordsWritten() const {\n" - " int records = 0;\n" - " for (int i=1; i < threads::max_threads; ++i)\n" - " if (my_thread_private[i])\n" - " records += my_thread_private[i]->m_records_written;\n" - " return records;\n" - "}\n" - "\n" - "inline istream &istream::operator>>(streamable &object) {\n" - " MY_SETUP\n" - " if (MY(sequencing)) {\n" - " MY(codon)->m_target.push_back(&object);\n" - " }\n" - " else {\n" - " int size;\n" - " *MY(xstr) >> size;\n" - " if (size > 0) {\n" - " std::streampos start = MY(sbuf)->tellg();\n" - " sequencer(object);\n" - " MY(sbuf)->seekg(start+(std::streamoff)size);\n" - " }\n" - " }\n" - " return *this;\n" - "}\n" - "\n" - "inline void istream::reset_sequencer() {\n" - " MY_SETUP\n" - " MY(sequencing) = 0;\n" - "}\n" - "\n" - "inline void istream::sequencer(streamable &object) {\n" - " MY_SETUP\n" - " MY(sequencing) = 1;\n" - " MY(codon)->m_target.clear();\n" - " object.streamer(*this);\n" - " if (MY(sequencing)) {\n" - " MY(sequencing) = 0;\n" - " codon &gene = *MY(codon);\n" - " streamable null_streamable;\n" - " gene.m_target.push_front(&null_streamable);\n" - " chromosome::iterator iter;\n" - " for (iter = gene.m_sequence.begin();\n" - " iter != gene.m_sequence.end();\n" - " ++iter)\n" - " {\n" - " MY(codon) = &(*iter);\n" - " *this >> *gene.m_target[iter->m_order];\n" - " }\n" - " MY(codon) = &gene;\n" - " }\n" - "}\n" - "\n" - "inline ostream &ostream::operator<<(HDDM &record) {\n" - " MY_SETUP\n" - " MY(sbuf)->reset();\n" - " *this << (streamable&)record;\n" - " while (MY(sbuf)->size() == MY(event_buffer_size)) {\n" - " delete MY(xstr);\n" - " delete MY(sbuf);\n" - " char *newbuf = new char[MY(event_buffer_size) *= 2];\n" - " MY(sbuf) = new ostreambuffer(newbuf, MY(event_buffer_size));\n" - " MY(xstr) = new xstream::xdr::ostream(MY(sbuf));\n" - " delete [] MY(event_buffer);\n" - " MY(event_buffer) = newbuf;\n" - " *this << (streamable&)record;\n" - " }\n" - " lock_streambufs();\n" - " update_streambufs();\n" - " if ((MY(status_bits) & k_crc32_integrity) != 0) {\n" - " xstream::digest::crc32 crc;\n" - " std::ostream out(&crc);\n" - " out.write(MY(sbuf)->getbuf(),MY(sbuf)->size());\n" - " out.flush();\n" - " unsigned int crc32 = crc.digest();\n" - " *MY(xstr) << crc32;\n" - " }\n" - " MY(ostr)->write(MY(sbuf)->getbuf(),MY(sbuf)->size());\n" - " if (!MY(ostr)->good()) {\n" - " unlock_streambufs();\n" - " throw std::runtime_error(\"hddm_" - << classPrefix << "::ostream::operator<< error - \"\n" - " \"write error on event output!\");\n" - " }\n" - " if (MY(status_bits) & k_bz2_compression) {\n" - " MY(last_start) = ((xstream::bz::ostreambuf*)MY(xcmp))->get_block_start();\n" - " MY(last_offset) = ((xstream::bz::ostreambuf*)MY(xcmp))->get_block_offset();\n" - " }\n" - " else if (MY(status_bits) & k_z_compression) {\n" - " MY(last_start) = ((xstream::z::ostreambuf*)MY(xcmp))->get_block_start();\n" - " MY(last_offset) = ((xstream::z::ostreambuf*)MY(xcmp))->get_block_offset();\n" - " }\n" - " else {\n" - " MY(last_start) = m_ostr.tellp();\n" - " MY(last_offset) = 0;\n" - " }\n" - " unlock_streambufs();\n" - " MY(bytes_written) += MY(sbuf)->size();\n" - " MY(records_written)++;\n" - " return *this;\n" - "}\n" - "\n" - "inline ostream &ostream::operator<<(streamable &object) {\n" - " MY_SETUP\n" - " *MY(xstr) << 0;\n" - " std::streampos start = MY(sbuf)->tellp();\n" - " object.streamer(*this);\n" - " std::streampos end = MY(sbuf)->tellp();\n" - " MY(sbuf)->seekp(start-std::streamoff(4));\n" - " *MY(xstr) << (int)(end-start);\n" - " MY(sbuf)->seekp(end);\n" - " return *this;\n" - "}\n\n" - ; -} - -/* Generate the xml template in normal form and store in a string */ - -void CodeBuilder::constructDocument(DOMElement* el) -{ - static int indent = 0; - hFile << "\""; - for (int n = 0; n < indent; n++) - { - hFile << " "; - } - - XtString tagS(el->getTagName()); - hFile << "<" << tagS; - DOMNamedNodeMap* attrList = el->getAttributes(); - int attrListLength = attrList->getLength(); - for (int a = 0; a < attrListLength; a++) - { - DOMNode* node = attrList->item(a); - XtString nameS(node->getNodeName()); - XtString valueS(node->getNodeValue()); - hFile << " " << nameS << "=\\\"" << valueS << "\\\""; - } - - DOMNodeList* contList = el->getChildNodes(); - int contListLength = contList->getLength(); - if (contListLength > 0) - { - hFile << ">\\n\"" << std::endl; - indent++; - for (int c = 0; c < contListLength; c++) - { - DOMNode* node = contList->item(c); - if (node->getNodeType() == DOMNode::ELEMENT_NODE) - { - DOMElement* contEl = (DOMElement*) node; - constructDocument(contEl); - } - } - indent--; - hFile << "\""; - for (int n = 0; n < indent; n++) - { - hFile << " "; - } - hFile << "\\n\"" << std::endl; - } - else - { - hFile << " />\\n\"" << std::endl; - } -} - -std::string guessType(const std::string &literal) -{ - const char *str = literal.c_str(); - char *endptr; - errno=0; - long long int llvalue = strtoll(str,&endptr,0); - if (errno == 0 && *endptr == 0) { - errno=0; - int lvalue = strtol(str,&endptr,0); - if (errno == 0 && *endptr == 0 && lvalue == llvalue) { - return "int"; - } - else { - return "long"; - } - } - errno=0; - strtof(str,&endptr); - if (errno == 0 && *endptr == 0) { - return "float"; - } - errno=0; - strtod(str,&endptr); - if (errno == 0 && *endptr == 0) { - return "double"; - } - if (literal == "true" || literal == "false") { - return "boolean"; - } - if ((int)lookupParticle(literal) != 0) { - return "Particle_t"; - } - if (XMLUri::isValidURI(false,X(literal))) { - return "anyURI"; - } - return "string"; -} - -Particle_t lookupParticle(const std::string &name) -{ - for (int p=0; p<100; ++p) { - if (ParticleType((Particle_t)p) == name) { - return (Particle_t)p; - } - } - return Unknown; -} diff --git a/src/programs/Utilities/hddm/hddm-py.cpp b/src/programs/Utilities/hddm/hddm-py.cpp deleted file mode 100644 index dd85e2322c..0000000000 --- a/src/programs/Utilities/hddm/hddm-py.cpp +++ /dev/null @@ -1,3213 +0,0 @@ -/* - * hddm-py : tool that reads in a HDDM document (Hall D Data Model) - * and writes a c++ class library that expresses the model as a - * python extension module. It does this by wrapping the classes - * of the c++ API as python classes, adding convenience methods - * to provide natural pythonic semantics for handling hddm files - * and objects. - * - * author: richard.t.jones at uconn.edu - * version: june 24, 2016 - original release. - * - * Version 1.1 - Richard Jones, February 10, 2021. - * - Modified to be able to accept a hddm file as a valid hddm template. - * This simplifies the documentation by eliminating the false distinction - * between a hddm template and the text header that appears at the top of - * every hddm file. It also gets rid of the unnecessary step of having - * to delete the binary data following the header in a hddm file before - * it can be used as a template. - */ - -#include "VersionConfig.hpp" -#include "XString.hpp" -#include "XParsers.hpp" -#include - -#include -#include -#include - -#include -#include -#include -#include -#include - -#define X(str) XString(str).unicode_str() -#define S(str) str.c_str() - -using namespace xercesc; - -XString classPrefix; - -void usage() -{ - std::cerr - << "\nUsage:\n" - << " hddm-py [-v | -o ] {HDDM file}\n\n" - << "Options:\n" - << " -v validate only\n" - << " -o write to .cpy" - << "Version: " << HDDM_VERSION_MAJOR << "." << HDDM_VERSION_MINOR - << std::endl; -} - -std::string guessType(const std::string &literal); -Particle_t lookupParticle(const std::string &name); - -class XtString : public XString -{ -/* XString class with a few extra methods for creating type - * strings that are useful in creating class names - */ - public: - XtString() {}; - XtString(const char* s): XString(s) {}; - XtString(const XMLCh* p): XString(p) {}; - XtString(const std::string& s): XString(s) {}; - XtString(const XString& x): XString(x) {}; - XtString(const XtString& t): XString((XString&)t) {}; - ~XtString() {}; - - XtString plural(); - XtString simpleType(); - XtString listType(); - XtString linkType(); -}; - -class CodeBuilder -{ -/* The methods in this class are used to write the c++ code - * that implements the hddm python extension library. - */ - public: - std::ofstream pyFile; - - CodeBuilder() {}; - ~CodeBuilder() {}; - - void checkConsistency(DOMElement* el, DOMElement* elref); - void writeClassdef(DOMElement* el); - void writeClassimp(DOMElement* el); - void constructDocument(DOMElement* el); - void constructGroup(DOMElement* el); - void constructIOstreams(DOMElement* el); - void constructMethods(DOMElement* el); - void constructStreamers(DOMElement* el); - void writeStreamers(DOMElement* el); - - typedef struct { - std::string name; - std::string args; - std::string docs; - } method_descr; - - std::map typesList; - - private: - std::vector tagList; - typedef std::vector parentList_t; - typedef std::map parentTable_t; - parentList_t parentList; - parentTable_t parents; - parentTable_t children; - int element_in_list(XtString &name, parentList_t list); -}; - - -int main(int argC, char* argV[]) -{ - try - { - XMLPlatformUtils::Initialize(); - } - catch (const XMLException* toCatch) - { - XtString msg(toCatch->getMessage()); - std::cerr - << "hddm-py: Error during initialization! :\n" - << msg << std::endl; - return 1; - } - - if (argC < 2) - { - usage(); - return 1; - } - else if ((argC == 2) && (strcmp(argV[1], "-?") == 0)) - { - usage(); - return 2; - } - - XtString xmlFile; - XtString pyFilename; - bool verifyOnly = false; - int argInd; - for (argInd = 1; argInd < argC; argInd++) - { - if (argV[argInd][0] != '-') - { - break; - } - if (strcmp(argV[argInd],"-v") == 0) - { - verifyOnly = true; - } - else if (strcmp(argV[argInd],"-o") == 0) - { - pyFilename = XtString(argV[++argInd]); - } - else - { - std::cerr - << "Unknown option \'" << argV[argInd] - << "\', ignoring it\n" << std::endl; - } - } - - if (argInd != argC - 1) - { - usage(); - return 1; - } - xmlFile = XtString(argV[argInd]); - std::ifstream ifs(xmlFile.c_str()); - if (!ifs.good()) - { - std::cerr - << "hddm-py: Error opening hddm template " << xmlFile << std::endl; - exit(1); - } - std::ostringstream tmpFileStr; - tmpFileStr << "tmp" << getpid(); - std::ofstream ofs(tmpFileStr.str().c_str()); - if (! ofs.is_open()) - { - std::cerr - << "hddm-py: Error opening temp file " << tmpFileStr.str() << std::endl; - exit(2); - } - - XString xmlPreamble("\n"); - XString xmlHeader; - XString line; - while (getline(ifs,line)) - { - if (line.find("") != line.npos) - { - xmlPreamble += line + "\n"; - } - else if (line.size() == 0) - { - xmlPreamble += "\n"; - } - else if (line.find("") - { - break; - } - } - ofs.close(); - ifs.close(); - -#if defined OLD_STYLE_XERCES_PARSER - DOMDocument* document = parseInputDocument(tmpFileStr.str().c_str(),false); -#else - DOMDocument* document = buildDOMDocument(tmpFileStr.str().c_str(),false); -#endif - if (document == 0) - { - std::cerr - << "hddm-py : Error parsing HDDM document, " - << "cannot continue" << std::endl; - return 1; - } - unlink(tmpFileStr.str().c_str()); - - DOMElement* rootEl = document->getDocumentElement(); - XtString rootS(rootEl->getTagName()); - if (rootS != "HDDM") - { - std::cerr - << "hddm-py error: root element of input document is " - << "\"" << rootS << "\", expected \"HDDM\"" - << std::endl; - return 1; - } - - XtString classS(rootEl->getAttribute(X("class"))); - classPrefix = classS; - - XtString pyname; - if (verifyOnly) - { - pyname = "/dev/null"; - } - else if (pyFilename.size()) - { - pyname = pyFilename + ".cpy"; - } - else - { - pyname = "pyhddm_" + classPrefix + ".cpy"; - } - - CodeBuilder builder; - builder.pyFile.open(pyname.c_str()); - if (! builder.pyFile.is_open()) - { - std::cerr - << "hddm-py error: unable to open output file " - << pyname << std::endl; - return 1; - } - - builder.pyFile << - "/*\n" - " * pyhddm_" << classPrefix << ".cpy - DO NOT EDIT THIS FILE\n" - " *\n" - " * This file was generated automatically by hddm-py from the file\n" - << " * " << xmlFile << std::endl << - "\n" - " * This source file contains the Python/C++ API wrappers that\n" - " * provide a python interface to the hddm classes and methods\n" - " * generated by hddm-cpp from " << xmlFile << ".\n" - " *\n" - " * The hddm data model tool set was written by\n" - " * Richard Jones, University of Connecticut.\n" - " *\n" - " * For more information see the documentation at\n" - " * http://github.com/rjones30/HDDM\n" - " *\n" - " */\n" - "\n" - "#include \n" - "#include \n" - "\n" - "#include \n" - "#include \n" - "#include \n" - "#include \n" - "#include \n" - "\n" - "using namespace hddm_" << classPrefix << ";\n" - "\n" - "#if PY_MAJOR_VERSION >= 3\n" - " #define PyInt_FromLong PyLong_FromLong\n" - " #define PyInt_AsLong PyLong_AsLong\n" - "#endif\n" - "\n" - "\n" - "inline void LOG_NEW(PyTypeObject *t, PyTypeObject *subt=0, int own=0) {\n" - "#if 0\n" - " if (subt == 0)\n" - " std::cout << \"creating a new element of \" << t->tp_name\n" - " << \" \" << ((own == 0)? \"(borrowed)\" : \"(owned)\")\n" - " << std::endl;\n" - " else\n" - " std::cout << \"creating a new list of \" << subt->tp_name\n" - " << \" \" << ((own == 0)? \"(borrowed)\" : \"(owned)\")\n" - " << std::endl;\n" - "#endif\n" - "}\n" - "\n" - "inline void LOG_DEALLOC(PyTypeObject *t, PyTypeObject *subt=0, int own=0) {\n" - "#if 0\n" - " if (subt == 0)\n" - " std::cout << \"destroying an element of \" << t->tp_name\n" - " << \" \" << ((own == 0)? \"(borrowed)\" : \"(owned)\")\n" - " << std::endl;\n" - " else\n" - " std::cout << \"destroying a list of \" << subt->tp_name\n" - " << \" \" << ((own == 0)? \"(borrowed)\" : \"(owned)\")\n" - " << std::endl;\n" - "#endif\n" - "}\n" - "\n" - "inline void My_INCREF(PyObject *o) {\n" - " //std::cout << \"incrementing reference at \" << o << std::endl;\n" - " Py_INCREF(o);\n" - "}\n" - "\n" - "inline void My_DECREF(PyObject *o) {\n" - " //std::cout << \"decrementing reference at \" << o << std::endl;\n" - " Py_DECREF(o);\n" - "}\n" - "\n" - "// wrap base class hddm_" << classPrefix << "::HDDM_Element" - " as hddm_" << classPrefix << ".HDDM_Element\n" - "\n" - "typedef struct {\n" - " PyObject_HEAD\n" - " HDDM_Element *elem;\n" - " PyObject *host;\n" - "} _HDDM_Element;\n" - "\n" - "static void\n" - "_HDDM_Element_dealloc(_HDDM_Element* self)\n" - "{\n" - " if (self->elem != 0) {\n" - " LOG_DEALLOC(Py_TYPE(self), 0, self->host == (PyObject*)self);\n" - " if (self->host == (PyObject*)self)\n" - " delete self->elem;\n" - " else\n" - " My_DECREF(self->host);\n" - " }\n" - " Py_TYPE(self)->tp_free((PyObject*)self);\n" - "}\n" - "\n" - "static PyObject*\n" - "_HDDM_Element_new(PyTypeObject *type, PyObject *args, PyObject *kwds)\n" - "{\n" - " _HDDM_Element *self;\n" - " self = (_HDDM_Element*)type->tp_alloc(type, 0);\n" - " if (self != NULL) {\n" - " self->elem = 0;\n" - " self->host = 0;\n" - " }\n" - " return (PyObject*)self;\n" - "}\n" - "\n" - "static int\n" - "_HDDM_Element_init(_HDDM_Element *self, PyObject *args, PyObject *kwds)\n" - "{\n" - " PyErr_SetString(PyExc_RuntimeError, \"illegal constructor\");\n" - " return -1;\n" - "}\n" - "\n" - "static PyObject*\n" - "_HDDM_Element_getAttribute(PyObject *self, PyObject *args)\n" - "{\n" - " char *attr;\n" - " if (! PyArg_ParseTuple(args, \"s\", &attr)) {\n" - " return NULL;\n" - " }\n" - " _HDDM_Element *me = (_HDDM_Element*)self;\n" - " if (me->elem == 0) {\n" - " PyErr_SetString(PyExc_RuntimeError, \"lookup attempted on invalid" - " element\");\n" - " return NULL;\n" - " }\n" - " hddm_type atype;\n" - " void *val((int*)me->elem->getAttribute(std::string(attr),&atype));\n" - " if (val == 0) {\n" - " Py_INCREF(Py_None);\n" - " return Py_None;\n" - " }\n" - " else if (atype == k_hddm_int) {\n" - " return PyLong_FromLong(*(int*)val);\n" - " }\n" - " else if (atype == k_hddm_long) {\n" - " return PyLong_FromLong(*(long*)val);\n" - " }\n" - " else if (atype == k_hddm_float) {\n" - " return PyFloat_FromDouble(double(*(float*)val));\n" - " }\n" - " else if (atype == k_hddm_double) {\n" - " return PyFloat_FromDouble(*(double*)val);\n" - " }\n" - " else if (atype == k_hddm_boolean) {\n" - " if (*(bool*)val == 0) {\n" - " Py_INCREF(Py_False);\n" - " return Py_False;\n" - " }\n" - " else {\n" - " Py_INCREF(Py_True);\n" - " return Py_True;\n" - " }\n" - " }\n" - " else if (atype == k_hddm_string) {\n" - " return PyUnicode_FromString(((std::string*)val)->c_str());\n" - " }\n" - " else if (atype == k_hddm_anyURI) {\n" - " return PyUnicode_FromString(((std::string*)val)->c_str());\n" - " }\n" - " else if (atype == k_hddm_Particle_t) {\n" - " return PyUnicode_FromString(ParticleType(*(Particle_t*)val));\n" - " }\n" - " return PyUnicode_FromString(((std::string*)val)->c_str());\n" - "}\n\n" - "static PyMemberDef _HDDM_Element_members[] = {\n" - " {NULL} /* Sentinel */\n" - "};\n" - "\n" - "static PyMethodDef _HDDM_Element_methods[] = {\n" - " {\"getAttribute\", _HDDM_Element_getAttribute, METH_VARARGS,\n" - " \"look up named attribute in this element\"},\n" - " {NULL} /* Sentinel */\n" - "};\n" - "\n" - "static PyTypeObject _HDDM_Element_type = {\n" - " PyVarObject_HEAD_INIT(NULL,0)\n" - " \"hddm_" << classPrefix << ".HDDM_Element\", /*tp_name*/\n" - " sizeof(_HDDM_Element), /*tp_basicsize*/\n" - " 0, /*tp_itemsize*/\n" - " (destructor)_HDDM_Element_dealloc, /*tp_dealloc*/\n" - " 0, /*tp_print*/\n" - " 0, /*tp_getattr*/\n" - " 0, /*tp_setattr*/\n" - " 0, /*tp_compare*/\n" - " 0, /*tp_repr*/\n" - " 0, /*tp_as_number*/\n" - " 0, /*tp_as_sequence*/\n" - " 0, /*tp_as_mapping*/\n" - " 0, /*tp_hash */\n" - " 0, /*tp_call*/\n" - " 0, /*tp_str*/\n" - " 0, /*tp_getattro*/\n" - " 0, /*tp_setattro*/\n" - " 0, /*tp_as_buffer*/\n" - " Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/\n" - " \"hddm_" << classPrefix << " basic element\", /* tp_doc */\n" - " 0, /* tp_traverse */\n" - " 0, /* tp_clear */\n" - " 0, /* tp_richcompare */\n" - " 0, /* tp_weaklistoffset */\n" - " 0, /* tp_iter */\n" - " 0, /* tp_iternext */\n" - " _HDDM_Element_methods, /* tp_methods */\n" - " _HDDM_Element_members, /* tp_members */\n" - " 0, /* tp_getset */\n" - " 0, /* tp_base */\n" - " 0, /* tp_dict */\n" - " 0, /* tp_descr_get */\n" - " 0, /* tp_descr_set */\n" - " 0, /* tp_dictoffset */\n" - " (initproc)_HDDM_Element_init, /* tp_init */\n" - " 0, /* tp_alloc */\n" - " _HDDM_Element_new, /* tp_new */\n" - "};\n" - "\n" - "\n" - "// wrap base class hddm_" << classPrefix << "::HDDM_ElementList" - " as hddm_" << classPrefix << ".HDDM_ElementList\n" - "\n" - "typedef struct {\n" - " PyObject_HEAD\n" - " PyTypeObject *subtype; // type of wrapper derived from _HDDM_Element\n" - " HDDM_ElementList *list;\n" - " PyObject *host;\n" - " int borrowed;\n" - "} _HDDM_ElementList;\n" - "\n" - "static void\n" - "_HDDM_ElementList_dealloc(_HDDM_ElementList* self)\n" - "{\n" - " if (self->list != 0) {\n" - " LOG_DEALLOC(Py_TYPE(self), self->subtype, self->borrowed == 0);\n" - " if (self->borrowed == 0)\n" - " delete self->list;\n" - " My_DECREF(self->host);\n" - " }\n" - " Py_TYPE(self)->tp_free((PyObject*)self);\n" - "}\n" - "\n" - "static PyObject*\n" - "_HDDM_ElementList_new(PyTypeObject *type, PyObject *args, PyObject *kwds)\n" - "{\n" - " _HDDM_ElementList *self;\n" - " self = (_HDDM_ElementList*)type->tp_alloc(type, 0);\n" - " if (self != NULL) {\n" - " self->subtype = 0;\n" - " self->borrowed = 0;\n" - " self->host = 0;\n" - " }\n" - " return (PyObject*)self;\n" - "}\n" - "\n" - "static int\n" - "_HDDM_ElementList_init(_HDDM_ElementList *self, PyObject *args, PyObject *kwds)\n" - "{\n" - " PyErr_SetString(PyExc_RuntimeError, \"illegal constructor\");\n" - " return -1;\n" - "}\n" - "\n" - "static Py_ssize_t\n" - "_HDDM_ElementList_size(_HDDM_ElementList *self, void *closure)\n" - "{\n" - " if (self->list == 0) {\n" - " PyErr_SetString(PyExc_RuntimeError, \"size attempted on invalid list\");\n" - " return -1;\n" - " }\n" - " return self->list->size();\n" - "}\n" - "\n" - "static PyObject*\n" - "_HDDM_ElementList_item(_HDDM_ElementList *self, Py_ssize_t i)\n" - "{\n" - " if (self->list == 0)\n" - " return NULL;\n" - " int len = self->list->size();\n" - " if (i < 0 || i >= len) {\n" - " PyErr_Format(PyExc_IndexError, \"index \\%ld out of bounds.\", i);\n" - " return NULL;\n" - " }\n" - " PyObject *elem_obj = _HDDM_Element_new(self->subtype, 0, 0);\n" - " ((_HDDM_Element*)elem_obj)->elem = &(HDDM_Element&)(*self->list)(i);\n" - " ((_HDDM_Element*)elem_obj)->host = self->host;\n" - " My_INCREF(self->host);\n" - " LOG_NEW(self->subtype);\n" - " return elem_obj;\n" - "}\n" - "\n" - "extern PyTypeObject _HDDM_ElementList_type;\n" - "\n" - "static PyObject *\n" - "_HDDM_ElementList_add(PyObject *self, PyObject *args)\n" - "{\n" - " int count=0;\n" - " int start=-1;\n" - " if (! PyArg_ParseTuple(args, \"i|i\", &count, &start)) {\n" - " return NULL;\n" - " }\n" - " _HDDM_ElementList *me = (_HDDM_ElementList*)self;\n" - " if (me->list == 0) {\n" - " PyErr_SetString(PyExc_RuntimeError, \"add attempted on invalid list\");\n" - " return NULL;\n" - " }\n" - " PyObject *list = _HDDM_ElementList_new(&_HDDM_ElementList_type, 0, 0);\n" - " ((_HDDM_ElementList*)list)->subtype = me->subtype;\n" - " ((_HDDM_ElementList*)list)->list = (HDDM_ElementList*)\n" - " new HDDM_ElementList(me->list->add(count, start));\n" - " ((_HDDM_ElementList*)list)->borrowed = 0;\n" - " ((_HDDM_ElementList*)list)->host = me->host;\n" - " My_INCREF(me->host);\n" - " LOG_NEW(Py_TYPE(self), me->subtype, 1);\n" - " return list;\n" - "}\n" - "\n" - "static PyObject *\n" - "_HDDM_ElementList_del(PyObject *self, PyObject *args)\n" - "{\n" - " int start=0;\n" - " int count=-1;\n" - " if (! PyArg_ParseTuple(args, \"|ii\", &count, &start)) {\n" - " return NULL;\n" - " }\n" - " _HDDM_ElementList *list_obj;\n" - " list_obj = (_HDDM_ElementList*)self;\n" - " if (list_obj->list == 0) {\n" - " PyErr_SetString(PyExc_RuntimeError, \"del attempted on invalid list\");\n" - " return NULL;\n" - " }\n" - " list_obj->list->del(count, start);\n" - " Py_INCREF(self);\n" - " return self;\n" - "}\n" - "\n" - "static PyObject *\n" - "_HDDM_ElementList_clear(PyObject *self, PyObject *args)\n" - "{\n" - " _HDDM_ElementList *list_obj;\n" - " list_obj = (_HDDM_ElementList*)self;\n" - " if (list_obj->list == 0) {\n" - " PyErr_SetString(PyExc_RuntimeError, \"clear attempted on invalid list\");\n" - " return NULL;\n" - " }\n" - " list_obj->list->clear();\n" - " Py_INCREF(self);\n" - " return self;\n" - "}\n" - "\n" - "static PyMemberDef _HDDM_ElementList_members[] = {\n" - " {NULL} /* Sentinel */\n" - "};\n" - "\n" - "static PyMethodDef _HDDM_ElementList_methods[] = {\n" - " {\"add\", _HDDM_ElementList_add, METH_VARARGS,\n" - " \"add (or insert) a new element to the list.\"},\n" - " {\"del\", _HDDM_ElementList_del, METH_VARARGS,\n" - " \"delete an existing element from the list.\"},\n" - " {\"clear\", _HDDM_ElementList_clear, METH_NOARGS,\n" - " \"reset the list to zero elements.\"},\n" - " {NULL} /* Sentinel */\n" - "};\n" - "\n" - "static PySequenceMethods _HDDM_ElementList_as_sequence = {\n" - " (lenfunc)_HDDM_ElementList_size, /* sq_length */\n" - " 0, /* sq_concat */\n" - " 0, /* sq_repeat */\n" - " (ssizeargfunc)_HDDM_ElementList_item, /* sq_item */\n" - " 0, /* sq_slice */\n" - " 0, /* sq_ass_item */\n" - " 0, /* sq_ass_slice */\n" - " 0, /* sq_contains */\n" - " 0, /* sq_inplace_concat */\n" - " 0, /* sq_inplace_repeat */\n" - "};\n" - "\n" - "PyTypeObject _HDDM_ElementList_type = {\n" - " PyVarObject_HEAD_INIT(NULL,0)\n" - " \"hddm_" << classPrefix << ".HDDM_ElementList\", /*tp_name*/\n" - " sizeof(_HDDM_ElementList), /*tp_basicsize*/\n" - " 0, /*tp_itemsize*/\n" - " (destructor)_HDDM_ElementList_dealloc, /*tp_dealloc*/\n" - " 0, /*tp_print*/\n" - " 0, /*tp_getattr*/\n" - " 0, /*tp_setattr*/\n" - " 0, /*tp_compare*/\n" - " 0, /*tp_repr*/\n" - " 0, /*tp_as_number*/\n" - " &_HDDM_ElementList_as_sequence, /*tp_as_sequence*/\n" - " 0, /*tp_as_mapping*/\n" - " 0, /*tp_hash */\n" - " 0, /*tp_call*/\n" - " 0, /*tp_str*/\n" - " 0, /*tp_getattro*/\n" - " 0, /*tp_setattro*/\n" - " 0, /*tp_as_buffer*/\n" - " Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/\n" - " \"hddm_" << classPrefix << " output stream\", /* tp_doc */\n" - " 0, /* tp_traverse */\n" - " 0, /* tp_clear */\n" - " 0, /* tp_richcompare */\n" - " 0, /* tp_weaklistoffset */\n" - " 0, /* tp_iter */\n" - " 0, /* tp_iternext */\n" - " _HDDM_ElementList_methods, /* tp_methods */\n" - " _HDDM_ElementList_members, /* tp_members */\n" - " 0, /* tp_getset */\n" - " 0, /* tp_base */\n" - " 0, /* tp_dict */\n" - " 0, /* tp_descr_get */\n" - " 0, /* tp_descr_set */\n" - " 0, /* tp_dictoffset */\n" - " (initproc)_HDDM_ElementList_init, /* tp_init */\n" - " 0, /* tp_alloc */\n" - " _HDDM_ElementList_new, /* tp_new */\n" - "};\n" - ; - - builder.constructGroup(rootEl); - builder.constructIOstreams(rootEl); - builder.constructMethods(rootEl); - builder.constructStreamers(rootEl); - - builder.typesList["HDDM_Element"] = "_HDDM_Element_type"; - builder.typesList["HDDM_ElementList"] = "_HDDM_ElementList_type"; - builder.typesList["streamposition"] = "_streamposition_type"; - builder.typesList["ostream"] = "_ostream_type"; - builder.typesList["istream"] = "_istream_type"; - - builder.pyFile << - "\n" - "\n" - "// wrap class hddm_" << classPrefix << "::streamposition" - " as hddm_" << classPrefix << ".streamposition\n" - "\n" - "typedef struct {\n" - " PyObject_HEAD\n" - " streamposition *streampos;\n" - "} _streamposition;\n" - "\n" - "static void\n" - "_streamposition_dealloc(_streamposition* self)\n" - "{\n" - " if (self->streampos != 0)\n" - " delete self->streampos;\n" - " Py_TYPE(self)->tp_free((PyObject*)self);\n" - "}\n" - "\n" - "static PyObject*\n" - "_streamposition_new(PyTypeObject *type, PyObject *args, PyObject *kwds)\n" - "{\n" - " _streamposition *self;\n" - " self = (_streamposition*)type->tp_alloc(type, 0);\n" - " if (self != NULL)\n" - " self->streampos = 0;\n" - " return (PyObject*)self;\n" - "}\n" - "\n" - "static int\n" - "_streamposition_init(_streamposition *self, PyObject *args, PyObject *kwds)\n" - "{\n" - " const char *kwlist[] = {\"start\", \"offset\", \"status\", NULL};\n" - " uint64_t start = 0;\n" - " uint32_t offset = 0;\n" - " uint32_t status = 0;\n" - " if (PyArg_ParseTuple(args, \"\") ||\n" - " PyArg_ParseTupleAndKeywords(args, kwds, \"kII\", (char**)kwlist, \n" - " &start, &offset, &status))\n" - " {\n" - " PyErr_Clear();\n" - " if (self->streampos != 0)\n" - " delete self->streampos;\n" - " self->streampos = new streamposition(start, offset, status);\n" - " return 0;\n" - " }\n" - " return -1; \n" - "}\n" - "\n" - "static PyObject*\n" - "_streamposition_richcompare(PyObject *a, PyObject *b, int op)\n" - "{\n" - " int res = 0;\n" - " streamposition *apos = ((_streamposition*)a)->streampos;\n" - " streamposition *bpos = ((_streamposition*)b)->streampos;\n" - " if (op == Py_LT)\n" - " res = (*apos < *bpos);\n" - " else if (op == Py_LE)\n" - " res = (*apos <= *bpos);\n" - " else if (op == Py_EQ)\n" - " res = (*apos == *bpos);\n" - " else if (op == Py_NE)\n" - " res = (*apos != *bpos);\n" - " else if (op == Py_GT)\n" - " res = (*apos > *bpos);\n" - " else if (op == Py_GE)\n" - " res = (*apos >= *bpos);\n" - " if (res) {\n" - " Py_INCREF(Py_True);\n" - " return Py_True;\n" - " }\n" - " else {\n" - " Py_INCREF(Py_False);\n" - " return Py_False;\n" - " }\n" - "}\n" - "static PyObject*\n" - "_streamposition_toString(PyObject *self, PyObject *args=0)\n" - "{\n" - " std::stringstream ostr;\n" - " ostr << \"hddm_" << classPrefix << ".streamposition(\"\n" - " << ((_streamposition*)self)->streampos->block_start << \",\"\n" - " << ((_streamposition*)self)->streampos->block_offset << \",\"\n" - " << ((_streamposition*)self)->streampos->block_status\n" - " << \")\";\n" - " return PyUnicode_FromString(ostr.str().c_str());\n" - "}\n" - "\n" - "static PyObject*\n" - "_streamposition_toRepr(PyObject *self, PyObject *args=0)\n" - "{\n" - " std::stringstream ostr;\n" - " ostr << \"\\\'\";\n" - " ostr << \"hddm_" << classPrefix << ".streamposition(\"\n" - " << ((_streamposition*)self)->streampos->block_start << \",\"\n" - " << ((_streamposition*)self)->streampos->block_offset << \",\"\n" - " << ((_streamposition*)self)->streampos->block_status\n" - " << \")\";\n" - " ostr << \"\\\'\";\n" - " return PyUnicode_FromString(ostr.str().c_str());\n" - "}\n" - "\n" - "static PyObject*\n" - "_streamposition_getstart(_streamposition *self, void *closure)\n" - "{\n" - " return Py_BuildValue(\"k\", self->streampos->block_start);\n" - "}\n" - "\n" - "static int\n" - "_streamposition_setstart(_streamposition *self, PyObject *value, void *closure)\n" - "{\n" - " if (value == NULL) {\n" - " PyErr_SetString(PyExc_TypeError, \"unexpected null argument\");\n" - " return -1;\n" - " }\n" - " long start = PyInt_AsLong(value);\n" - " if (start < 0 && PyErr_Occurred()) {\n" - " return -1;\n" - " }\n" - " self->streampos->block_start = start;\n" - " return 0;\n" - "}\n" - "\n" - "static PyObject*\n" - "_streamposition_getoffset(_streamposition *self, void *closure)\n" - "{\n" - " return Py_BuildValue(\"I\", self->streampos->block_offset);\n" - "}\n" - "\n" - "static int\n" - "_streamposition_setoffset(_streamposition *self, PyObject *value, void *closure)\n" - "{\n" - " if (value == NULL) {\n" - " PyErr_SetString(PyExc_TypeError, \"unexpected null argument\");\n" - " return -1;\n" - " }\n" - " long offset = PyInt_AsLong(value);\n" - " if (offset < 0 && PyErr_Occurred()) {\n" - " return -1;\n" - " }\n" - " self->streampos->block_offset = offset;\n" - " return 0;\n" - "}\n" - "\n" - "static PyObject*\n" - "_streamposition_getstatus(_streamposition *self, void *closure)\n" - "{\n" - " return Py_BuildValue(\"I\", self->streampos->block_status);\n" - "}\n" - "\n" - "static int\n" - "_streamposition_setstatus(_streamposition *self, PyObject *value, void *closure)\n" - "{\n" - " if (value == NULL) {\n" - " PyErr_SetString(PyExc_TypeError, \"unexpected null argument\");\n" - " return -1;\n" - " }\n" - " long status = PyInt_AsLong(value);\n" - " if (status == -1 && PyErr_Occurred()) {\n" - " return -1;\n" - " }\n" - " self->streampos->block_status = status;\n" - " return 0;\n" - "}\n" - "\n" - "static PyGetSetDef _streamposition_getsetters[] = {\n" - " {(char*)\"start\", \n" - " (getter)_streamposition_getstart, (setter)_streamposition_setstart,\n" - " (char*)\"block start position\",\n" - " NULL},\n" - " {(char*)\"offset\", \n" - " (getter)_streamposition_getoffset, (setter)_streamposition_setoffset,\n" - " (char*)\"block offset position\",\n" - " NULL},\n" - " {(char*)\"status\", \n" - " (getter)_streamposition_getstatus, (setter)_streamposition_setstatus,\n" - " (char*)\"block status flags\",\n" - " NULL},\n" - " {NULL} /* Sentinel */\n" - "};\n" - "\n" - "static PyMemberDef _streamposition_members[] = {\n" - " {NULL} /* Sentinel */\n" - "};\n" - "\n" - "static PyMethodDef _streamposition_methods[] = {\n" - " {NULL} /* Sentinel */\n" - "};\n" - "\n" - "static PyTypeObject _streamposition_type = {\n" - " PyVarObject_HEAD_INIT(NULL,0)\n" - " \"hddm_" << classPrefix << ".streamposition\", /*tp_name*/\n" - " sizeof(_streamposition), /*tp_basicsize*/\n" - " 0, /*tp_itemsize*/\n" - " (destructor)_streamposition_dealloc, /*tp_dealloc*/\n" - " 0, /*tp_print*/\n" - " 0, /*tp_getattr*/\n" - " 0, /*tp_setattr*/\n" - " 0, /*tp_compare*/\n" - " (reprfunc)_streamposition_toRepr, /*tp_repr*/\n" - " 0, /*tp_as_number*/\n" - " 0, /*tp_as_sequence*/\n" - " 0, /*tp_as_mapping*/\n" - " 0, /*tp_hash */\n" - " 0, /*tp_call*/\n" - " (reprfunc)_streamposition_toString, /*tp_str*/\n" - " 0, /*tp_getattro*/\n" - " 0, /*tp_setattro*/\n" - " 0, /*tp_as_buffer*/\n" - " Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/\n" - " \"hddm_" << classPrefix << " streamposition objects\", /* tp_doc */\n" - " 0, /* tp_traverse */\n" - " 0, /* tp_clear */\n" - " _streamposition_richcompare, /* tp_richcompare */\n" - " 0, /* tp_weaklistoffset */\n" - " 0, /* tp_iter */\n" - " 0, /* tp_iternext */\n" - " _streamposition_methods, /* tp_methods */\n" - " _streamposition_members, /* tp_members */\n" - " _streamposition_getsetters, /* tp_getset */\n" - " 0, /* tp_base */\n" - " 0, /* tp_dict */\n" - " 0, /* tp_descr_get */\n" - " 0, /* tp_descr_set */\n" - " 0, /* tp_dictoffset */\n" - " (initproc)_streamposition_init, /* tp_init */\n" - " 0, /* tp_alloc */\n" - " _streamposition_new, /* tp_new */\n" - "};\n" - "\n" - "\n" - "// wrap class hddm_" << classPrefix << "::ostream" - " as hddm_" << classPrefix << ".ostream\n" - "\n" - "typedef struct {\n" - " PyObject_HEAD\n" - " std::string *fname;\n" - " std::ofstream *fstr;\n" - " ostream *ostr;\n" - "} _ostream;\n" - "\n" - "static void\n" - "_ostream_dealloc(_ostream* self)\n" - "{\n" - " if (self->fname != 0)\n" - " delete self->fname;\n" - " if (self->ostr != 0)\n" - " delete self->ostr;\n" - " if (self->fstr != 0)\n" - " delete self->fstr;\n" - " Py_TYPE(self)->tp_free((PyObject*)self);\n" - "}\n" - "\n" - "static PyObject*\n" - "_ostream_new(PyTypeObject *type, PyObject *args, PyObject *kwds)\n" - "{\n" - " _ostream *self;\n" - " self = (_ostream*)type->tp_alloc(type, 0);\n" - " if (self != NULL) {\n" - " self->fname = 0;\n" - " self->fstr = 0;\n" - " self->ostr = 0;\n" - " }\n" - " return (PyObject*)self;\n" - "}\n" - "\n" - "static int\n" - "_ostream_init(_ostream *self, PyObject *args, PyObject *kwds)\n" - "{\n" - " const char *kwlist[] = {\"file\", NULL};\n" - " char *filename;\n" - " if (PyArg_ParseTupleAndKeywords(args, kwds, \"s\", (char**)kwlist, &filename))\n" - " {\n" - " if (self->fname != 0)\n" - " delete self->fname;\n" - " if (self->ostr != 0)\n" - " delete self->ostr;\n" - " if (self->fstr != 0)\n" - " delete self->fstr;\n" - " self->fname = new std::string(filename);\n" - " self->fstr = new std::ofstream(filename);\n" - " if (! self->fstr->good()) {\n" - " PyErr_Format(PyExc_IOError, \"Cannot open output file \\%s\", filename);\n" - " return -1;\n" - " }\n" - " try {\n" - " self->ostr = new ostream(*self->fstr);\n" - " }\n" - " catch (std::exception& e) {\n" - " PyErr_SetString(PyExc_RuntimeError, e.what());\n" - " return -1;\n" - " }\n" - " return 0;\n" - " }\n" - " return -1; \n" - "}\n" - "\n" - "static PyObject*\n" - "_ostream_getCompression(_ostream *self, void *closure)\n" - "{\n" - " return Py_BuildValue(\"i\", self->ostr->getCompression());\n" - "}\n" - "\n" - "static int\n" - "_ostream_setCompression(_ostream *self, PyObject *value, void *closure)\n" - "{\n" - " if (value == NULL) {\n" - " PyErr_SetString(PyExc_TypeError, \"unexpected null argument\");\n" - " return -1;\n" - " }\n" - " long flags = PyInt_AsLong(value);\n" - " if (flags == -1 && PyErr_Occurred()) {\n" - " return -1;\n" - " }\n" - " try {\n" - " self->ostr->setCompression(flags);\n" - " }\n" - " catch (std::exception& e) {\n" - " PyErr_SetString(PyExc_RuntimeError, e.what());\n" - " return -1;\n" - " }\n" - " return 0;\n" - "}\n" - "\n" - "static PyObject*\n" - "_ostream_getIntegrityChecks(_ostream *self, void *closure)\n" - "{\n" - " PyObject *flags = Py_BuildValue(\"i\", self->ostr->getIntegrityChecks());\n" - " return flags;\n" - "}\n" - "\n" - "static int\n" - "_ostream_setIntegrityChecks(_ostream *self, PyObject *value, void *closure)\n" - "{\n" - " if (value == NULL) {\n" - " PyErr_SetString(PyExc_TypeError, \"unexpected null argument\");\n" - " return -1;\n" - " }\n" - " long flags = PyInt_AsLong(value);\n" - " if (flags == -1 && PyErr_Occurred()) {\n" - " return -1;\n" - " }\n" - " try {\n" - " self->ostr->setIntegrityChecks(flags);\n" - " }\n" - " catch (std::exception& e) {\n" - " PyErr_SetString(PyExc_RuntimeError, e.what());\n" - " return -1;\n" - " }\n" - " return 0;\n" - "}\n" - "\n" - "static PyObject*\n" - "_ostream_getPosition(_ostream *self, void *closure)\n" - "{\n" - " streamposition *pos = new streamposition();\n" - " if (self->ostr != 0)\n" - " *pos = self->ostr->getPosition();\n" - " PyObject *pos_obj = _streamposition_new(&_streamposition_type, 0, 0);\n" - " ((_streamposition*)pos_obj)->streampos = pos;\n" - " return pos_obj;\n" - "}\n" - "\n" - "static PyObject*\n" - "_ostream_getRecordsWritten(_ostream *self, void *closure)\n" - "{\n" - " int records = 0;\n" - " if (self->ostr != 0)\n" - " try {\n" - " records = self->ostr->getRecordsWritten();\n" - " }\n" - " catch (std::exception& e) {\n" - " PyErr_SetString(PyExc_RuntimeError, e.what());\n" - " return NULL;\n" - " }\n" - " return PyLong_FromLong(records);\n" - "}\n" - "\n" - "static PyObject*\n" - "_ostream_getBytesWritten(_ostream *self, void *closure)\n" - "{\n" - " int bytes = 0;\n" - " if (self->ostr != 0)\n" - " try {\n" - " bytes = self->ostr->getBytesWritten();\n" - " }\n" - " catch (std::exception& e) {\n" - " PyErr_SetString(PyExc_RuntimeError, e.what());\n" - " return NULL;\n" - " }\n" - " return PyLong_FromLong(bytes);\n" - "}\n" - "\n" - "static PyObject*\n" - "_ostream_write(PyObject *self, PyObject *args)\n" - "{\n" - " _HDDM *record_obj;\n" - " if (! PyArg_ParseTuple(args, \"O!\", &_HDDM_type, (PyObject*)&record_obj))\n" - " return NULL;\n" - " ostream *ostr = ((_ostream*)self)->ostr;\n" - " try {\n" - " Py_BEGIN_ALLOW_THREADS\n" - " *ostr << *record_obj->elem;\n" - " Py_END_ALLOW_THREADS\n" - " }\n" - " catch (std::exception& e) {\n" - " PyErr_SetString(PyExc_RuntimeError, e.what());\n" - " return NULL;\n" - " }\n" - " Py_INCREF(Py_None);\n" - " return Py_None;\n" - "}\n" - "\n" - "static PyObject*\n" - "_ostream_toString(PyObject *self, PyObject *args=0)\n" - "{\n" - " std::stringstream ostr;\n" - " if (((_ostream*)self)->fname != 0)\n" - " ostr << \"hddm_" << classPrefix << ".ostream(\\\"\"\n" - " << *((_ostream*)self)->fname << \"\\\")\";\n" - " else\n" - " ostr << \"hddm_" << classPrefix << ".ostream(NULL)\";\n" - " return PyUnicode_FromString(ostr.str().c_str());\n" - "}\n" - "\n" - "static PyObject*\n" - "_ostream_toRepr(PyObject *self, PyObject *args=0)\n" - "{\n" - " std::stringstream ostr;\n" - " ostr << \"\\\'\";\n" - " if (((_ostream*)self)->fname != 0)\n" - " ostr << \"hddm_" << classPrefix << ".ostream(\\\"\"\n" - " << *((_ostream*)self)->fname << \"\\\")\";\n" - " else\n" - " ostr << \"hddm_" << classPrefix << ".ostream()\";\n" - " ostr << \"\\\'\";\n" - " return PyUnicode_FromString(ostr.str().c_str());\n" - "}\n" - "\n" - "static PyGetSetDef _ostream_getsetters[] = {\n" - " {(char*)\"compression\", \n" - " (getter)_ostream_getCompression, (setter)_ostream_setCompression,\n" - " (char*)\"ostream compression mode (k_no_compression, k_z_compression, ...)\",\n" - " NULL},\n" - " {(char*)\"integrityChecks\", \n" - " (getter)_ostream_getIntegrityChecks, (setter)_ostream_setIntegrityChecks,\n" - " (char*)\"ostream data integrity checking mode (k_no_integrity, ...)\",\n" - " NULL},\n" - " {(char*)\"position\", \n" - " (getter)_ostream_getPosition, 0,\n" - " (char*)\"output stream position\",\n" - " NULL},\n" - " {(char*)\"recordsWritten\", \n" - " (getter)_ostream_getRecordsWritten, 0,\n" - " (char*)\"total records written to ostream\",\n" - " NULL},\n" - " {(char*)\"bytesWritten\", \n" - " (getter)_ostream_getBytesWritten, 0,\n" - " (char*)\"total bytes written to ostream\",\n" - " NULL},\n" - " {NULL} /* Sentinel */\n" - "};\n" - "\n" - "static PyMemberDef _ostream_members[] = {\n" - " {NULL} /* Sentinel */\n" - "};\n" - "\n" - "static PyMethodDef _ostream_methods[] = {\n" - " {\"write\", _ostream_write, METH_VARARGS,\n" - " \"write a HDDM record to the output stream.\"},\n" - " {NULL} /* Sentinel */\n" - "};\n" - "\n" - "static PyTypeObject _ostream_type = {\n" - " PyVarObject_HEAD_INIT(NULL,0)\n" - " \"hddm_" << classPrefix << ".ostream\", /*tp_name*/\n" - " sizeof(_ostream), /*tp_basicsize*/\n" - " 0, /*tp_itemsize*/\n" - " (destructor)_ostream_dealloc, /*tp_dealloc*/\n" - " 0, /*tp_print*/\n" - " 0, /*tp_getattr*/\n" - " 0, /*tp_setattr*/\n" - " 0, /*tp_compare*/\n" - " (reprfunc)_ostream_toRepr, /*tp_repr*/\n" - " 0, /*tp_as_number*/\n" - " 0, /*tp_as_sequence*/\n" - " 0, /*tp_as_mapping*/\n" - " 0, /*tp_hash */\n" - " 0, /*tp_call*/\n" - " (reprfunc)_ostream_toString, /*tp_str*/\n" - " 0, /*tp_getattro*/\n" - " 0, /*tp_setattro*/\n" - " 0, /*tp_as_buffer*/\n" - " Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/\n" - " \"hddm_" << classPrefix << " output stream\", /* tp_doc */\n" - " 0, /* tp_traverse */\n" - " 0, /* tp_clear */\n" - " 0, /* tp_richcompare */\n" - " 0, /* tp_weaklistoffset */\n" - " 0, /* tp_iter */\n" - " 0, /* tp_iternext */\n" - " _ostream_methods, /* tp_methods */\n" - " _ostream_members, /* tp_members */\n" - " _ostream_getsetters, /* tp_getset */\n" - " 0, /* tp_base */\n" - " 0, /* tp_dict */\n" - " 0, /* tp_descr_get */\n" - " 0, /* tp_descr_set */\n" - " 0, /* tp_dictoffset */\n" - " (initproc)_ostream_init, /* tp_init */\n" - " 0, /* tp_alloc */\n" - " _ostream_new, /* tp_new */\n" - "};\n" - "\n" - "\n" - "// wrap class hddm_" << classPrefix << "::istream" - " as hddm_" << classPrefix << ".istream\n" - "\n" - "typedef struct {\n" - " PyObject_HEAD\n" - " std::string *fname;\n" - " std::ifstream *fstr;\n" - " istream *istr;\n" - "} _istream;\n" - "\n" - "static void\n" - "_istream_dealloc(_istream* self)\n" - "{\n" - " if (self->fname != 0)\n" - " delete self->fname;\n" - " if (self->istr != 0)\n" - " delete self->istr;\n" - " if (self->fstr != 0)\n" - " delete self->fstr;\n" - " Py_TYPE(self)->tp_free((PyObject*)self);\n" - "}\n" - "\n" - "static PyObject*\n" - "_istream_new(PyTypeObject *type, PyObject *args, PyObject *kwds)\n" - "{\n" - " _istream *self;\n" - " self = (_istream*)type->tp_alloc(type, 0);\n" - " if (self != NULL) {\n" - " self->fname = 0;\n" - " self->fstr = 0;\n" - " self->istr = 0;\n" - " }\n" - " return (PyObject*)self;\n" - "}\n" - "\n" - "static int\n" - "_istream_init(_istream *self, PyObject *args, PyObject *kwds)\n" - "{\n" - " const char *kwlist[] = {\"file\", NULL};\n" - " char *filename;\n" - " if (PyArg_ParseTupleAndKeywords(args, kwds, \"s\", (char**)kwlist, &filename))\n" - " {\n" - " if (self->fname != 0)\n" - " delete self->fname;\n" - " if (self->istr != 0)\n" - " delete self->istr;\n" - " if (self->fstr != 0)\n" - " delete self->fstr;\n" - " self->fname = new std::string(filename);\n" - " self->fstr = new std::ifstream(filename);\n" - " if (! self->fstr->good()) {\n" - " PyErr_Format(PyExc_IOError, \"Cannot open input file \\%s\", filename);\n" - " return -1;\n" - " }\n" - " try {\n" - " self->istr = new istream(*self->fstr);\n" - " }\n" - " catch (std::exception& e) {\n" - " PyErr_SetString(PyExc_RuntimeError, e.what());\n" - " return -1;\n" - " }\n" - " return 0;\n" - " }\n" - " return -1; \n" - "}\n" - "\n" - "static PyObject*\n" - "_istream_getCompression(_istream *self, void *closure)\n" - "{\n" - " return Py_BuildValue(\"i\", self->istr->getCompression());\n" - "}\n" - "\n" - "static PyObject*\n" - "_istream_getIntegrityChecks(_istream *self, void *closure)\n" - "{\n" - " return Py_BuildValue(\"i\", self->istr->getIntegrityChecks());\n" - "}\n" - "\n" - "static PyObject*\n" - "_istream_getPosition(_istream *self, void *closure)\n" - "{\n" - " streamposition *pos = new streamposition();\n" - " if (self->istr != 0)\n" - " try {\n" - " *pos = self->istr->getPosition();\n" - " }\n" - " catch (std::exception& e) {\n" - " PyErr_SetString(PyExc_RuntimeError, e.what());\n" - " return NULL;\n" - " }\n" - " PyObject *pos_obj = _streamposition_new(&_streamposition_type, 0, 0);\n" - " ((_streamposition*)pos_obj)->streampos = pos;\n" - " return pos_obj;\n" - "}\n" - "\n" - "static int\n" - "_istream_setPosition(_istream *self, PyObject *value, void *closure)\n" - "{\n" - " if (Py_TYPE(value) != &_streamposition_type)\n" - " {\n" - " PyErr_SetString(PyExc_TypeError, \"unexpected argument type\");\n" - " return -1;\n" - " }\n" - " streamposition *pos = ((_streamposition*)value)->streampos;\n" - " if (pos == 0) {\n" - " PyErr_SetString(PyExc_TypeError, \"unexpected null argument\");\n" - " return -1;\n" - " }\n" - " try {\n" - " self->istr->setPosition(*pos);\n" - " }\n" - " catch (std::exception& e) {\n" - " PyErr_SetString(PyExc_RuntimeError, e.what());\n" - " return -1;\n" - " }\n" - " return 0;\n" - "}\n" - "\n" - "static PyObject*\n" - "_istream_getRecordsRead(_istream *self, void *closure)\n" - "{\n" - " int records = 0;\n" - " if (self->istr != 0)\n" - " try {\n" - " records = self->istr->getRecordsRead();\n" - " }\n" - " catch (std::exception& e) {\n" - " PyErr_SetString(PyExc_RuntimeError, e.what());\n" - " return NULL;\n" - " }\n" - " return PyLong_FromLong(records);\n" - "}\n" - "\n" - "static PyObject*\n" - "_istream_getBytesRead(_istream *self, void *closure)\n" - "{\n" - " int bytes = 0;\n" - " if (self->istr != 0)\n" - " try {\n" - " bytes = self->istr->getBytesRead();\n" - " }\n" - " catch (std::exception& e) {\n" - " PyErr_SetString(PyExc_RuntimeError, e.what());\n" - " return NULL;\n" - " }\n" - " return PyLong_FromLong(bytes);\n" - "}\n" - "\n" - "static PyObject*\n" - "_istream_skip(PyObject *self, PyObject *args)\n" - "{\n" - " int count=0;\n" - " if (! PyArg_ParseTuple(args, \"I\", &count)) {\n" - " PyErr_SetString(PyExc_TypeError, \"missing argument in skip\");\n" - " return NULL;\n" - " }\n" - " else if (count < 0) {\n" - " PyErr_SetString(PyExc_TypeError, \"skip count cannot be negative\");\n" - " return NULL;\n" - " }\n" - " istream *istr = ((_istream*)self)->istr;\n" - " if (istr == 0) {\n" - " PyErr_SetString(PyExc_TypeError, \"unexpected null istream ptr\");\n" - " return NULL;\n" - " }\n" - " istr->skip(count);\n" - " return PyLong_FromLong(0);\n" - "}\n" - "\n" - "static PyObject*\n" - "_istream_read(PyObject *self, PyObject *args)\n" - "{\n" - " istream *istr = ((_istream*)self)->istr;\n" - " if (istr == 0) {\n" - " PyErr_SetString(PyExc_TypeError, \"unexpected null input stream\");\n" - " return NULL;\n" - " }\n" - " _HDDM *record_obj = (_HDDM*)_HDDM_new(&_HDDM_type, 0, 0);\n" - " record_obj->elem = new HDDM();\n" - " record_obj->host = (PyObject*)record_obj;\n" - " try {\n" - " Py_BEGIN_ALLOW_THREADS\n" - " *istr >> *record_obj->elem;\n" - " Py_END_ALLOW_THREADS\n" - " }\n" - " catch (std::exception& e) {\n" - " PyErr_SetString(PyExc_RuntimeError, e.what());\n" - " return NULL;\n" - " }\n" - " if (*istr) {\n" - " LOG_NEW(Py_TYPE(record_obj), 0, 1);\n" - " return (PyObject*)record_obj;\n" - " }\n" - " return NULL;\n" - "}\n" - "\n" - "static PyObject*\n" - "_istream_toString(PyObject *self, PyObject *args=0)\n" - "{\n" - " std::stringstream ostr;\n" - " if (((_ostream*)self)->fname != 0)\n" - " ostr << \"hddm_" << classPrefix << ".istream(\\\"\"\n" - " << *((_istream*)self)->fname << \"\\\")\";\n" - " else\n" - " ostr << \"hddm_" << classPrefix << ".istream(NULL)\";\n" - " return PyUnicode_FromString(ostr.str().c_str());\n" - "}\n" - "\n" - "static PyObject*\n" - "_istream_toRepr(PyObject *self, PyObject *args=0)\n" - "{\n" - " std::stringstream ostr;\n" - " ostr << \"\\\'\";\n" - " if (((_ostream*)self)->fname != 0)\n" - " ostr << \"hddm_" << classPrefix << ".istream(\\\"\"\n" - " << *((_istream*)self)->fname << \"\\\")\";\n" - " else\n" - " ostr << \"hddm_" << classPrefix << ".istream()\";\n" - " ostr << \"\\\'\";\n" - " return PyUnicode_FromString(ostr.str().c_str());\n" - "}\n" - "\n" - "static PyObject*\n" - "_istream_iter(PyObject *self)\n" - "{\n" - " Py_INCREF(self);\n" - " return self;\n" - "}\n" - "static PyObject*\n" - "_istream_next(PyObject *self)\n" - "{\n" - " PyObject *rec = _istream_read(self, 0);\n" - " if (rec == NULL)\n" - " PyErr_SetString(PyExc_StopIteration, \"no more data on input stream\");\n" - " return rec;\n" - "}\n" - "\n" - "static PyGetSetDef _istream_getsetters[] = {\n" - " {(char*)\"compression\", \n" - " (getter)_istream_getCompression, 0,\n" - " (char*)\"istream compression mode (k_no_compression, k_z_compression, ...)\",\n" - " NULL},\n" - " {(char*)\"integrityChecks\", \n" - " (getter)_istream_getIntegrityChecks, 0,\n" - " (char*)\"istream data integrity checking mode (k_no_integrity, ...)\",\n" - " NULL},\n" - " {(char*)\"position\", \n" - " (getter)_istream_getPosition, (setter)_istream_setPosition,\n" - " (char*)\"input stream position\",\n" - " NULL},\n" - " {(char*)\"recordsRead\", \n" - " (getter)_istream_getRecordsRead, 0,\n" - " (char*)\"total records read from istream\",\n" - " NULL},\n" - " {(char*)\"bytesRead\", \n" - " (getter)_istream_getBytesRead, 0,\n" - " (char*)\"total bytes read from istream\",\n" - " NULL},\n" - " {NULL} /* Sentinel */\n" - "};\n" - "\n" - "static PyMemberDef _istream_members[] = {\n" - " {NULL} /* Sentinel */\n" - "};\n" - "\n" - "static PyMethodDef _istream_methods[] = {\n" - " {\"read\", _istream_read, METH_NOARGS,\n" - " \"read a HDDM record from the input stream.\"},\n" - " {\"skip\", _istream_skip, METH_VARARGS,\n" - " \"skip ahead given number of HDDM records in the input stream.\"},\n" - " {NULL} /* Sentinel */\n" - "};\n" - "\n" - "static PyTypeObject _istream_type = {\n" - " PyVarObject_HEAD_INIT(NULL,0)\n" - " \"hddm_" << classPrefix << ".istream\", /*tp_name*/\n" - " sizeof(_istream), /*tp_basicsize*/\n" - " 0, /*tp_itemsize*/\n" - " (destructor)_istream_dealloc, /*tp_dealloc*/\n" - " 0, /*tp_print*/\n" - " 0, /*tp_getattr*/\n" - " 0, /*tp_setattr*/\n" - " 0, /*tp_compare*/\n" - " (reprfunc)_istream_toRepr, /*tp_repr*/\n" - " 0, /*tp_as_number*/\n" - " 0, /*tp_as_sequence*/\n" - " 0, /*tp_as_mapping*/\n" - " 0, /*tp_hash */\n" - " 0, /*tp_call*/\n" - " (reprfunc)_istream_toString, /*tp_str*/\n" - " 0, /*tp_getattro*/\n" - " 0, /*tp_setattro*/\n" - " 0, /*tp_as_buffer*/\n" - " Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/\n" - " \"hddm_" << classPrefix << " output stream\", /* tp_doc */\n" - " 0, /* tp_traverse */\n" - " 0, /* tp_clear */\n" - " 0, /* tp_richcompare */\n" - " 0, /* tp_weaklistoffset */\n" - " _istream_iter, /* tp_iter */\n" - " _istream_next, /* tp_iternext */\n" - " _istream_methods, /* tp_methods */\n" - " _istream_members, /* tp_members */\n" - " _istream_getsetters, /* tp_getset */\n" - " 0, /* tp_base */\n" - " 0, /* tp_dict */\n" - " 0, /* tp_descr_get */\n" - " 0, /* tp_descr_set */\n" - " 0, /* tp_dictoffset */\n" - " (initproc)_istream_init, /* tp_init */\n" - " 0, /* tp_alloc */\n" - " _istream_new, /* tp_new */\n" - "};\n" - ; - - // special module functions providing support for - // reading and writing hddm records to/from hdf5 files - - builder.pyFile << - "\n" - "#ifdef HDF5_SUPPORT\n" - "static PyObject*\n" - "_HDDM_hdf5FileCreate(PyObject *self, PyObject *args)\n" - "{\n" - " char *name;\n" - " int flags = 0;\n" - " if (! PyArg_ParseTuple(args, \"s|I\", &name, &flags)) {\n" - " return NULL;\n" - " }\n" - " flags = (flags == 0)? H5F_ACC_TRUNC : flags;\n" - " hid_t result = hddm_" << classPrefix << - "::HDDM::hdf5FileCreate(std::string(name), flags);\n" - " return PyLong_FromLong(result);\n" - "}\n" - "static PyObject*\n" - "_HDDM_hdf5FileOpen(PyObject *self, PyObject *args)\n" - "{\n" - " char *name;\n" - " int flags = 0;\n" - " if (! PyArg_ParseTuple(args, \"s|I\", &name, &flags)) {\n" - " return NULL;\n" - " }\n" - " flags = (flags == 0)? H5F_ACC_RDONLY : flags;\n" - " hid_t result=0;\n" - " try {\n" - " result = hddm_" << classPrefix << - "::HDDM::hdf5FileOpen(std::string(name), flags);\n" - " }\n" - " catch (...) {\n" - " result = -1;\n" - " }\n" - " return PyLong_FromLong(result);\n" - "}\n" - "static PyObject*\n" - "_HDDM_hdf5FileStamp(PyObject *self, PyObject *args)\n" - "{\n" - " hid_t file_id;\n" - " PyObject *ptags = 0;\n" - " if (! PyArg_ParseTuple(args, \"k|O!\", &file_id, &PyList_Type, &ptags)) {\n" - " PyErr_SetString(PyExc_TypeError, \"invalid argument in hdf5FileStamp\");\n" - " return NULL;\n" - " }\n" - " std::vector tags_unicode;\n" - " std::vector tags_ascii;\n" - " std::vector tags;\n" - " if (ptags != 0) {\n" - " int ntags = PyList_Size(ptags);\n" - " for (int i=0; i < ntags; i++) {\n" - " PyObject *pitem = PyList_GetItem(ptags, i);\n" - " PyObject *pitem_str = PyObject_Str(pitem);\n" - " tags_unicode.push_back(pitem_str);\n" - " PyObject *pitem_ascii = pitem_str;\n" - " if (PyUnicode_Check(pitem_str)) {\n" - " pitem_ascii = PyUnicode_AsEncodedString(pitem_str, \"ASCII\", \"strict\");\n" - " tags_ascii.push_back(pitem_ascii);\n" - " }\n" - "#if PY_MAJOR_VERSION < 3\n" - " tags.push_back(PyString_AsString(pitem_ascii));\n" - "#else\n" - " tags.push_back(PyBytes_AsString(pitem_ascii));\n" - "#endif\n" - " }\n" - " }\n" - " tags.push_back(0);\n" - " herr_t result = hddm_" << classPrefix << - "::HDDM::hdf5FileStamp(file_id, &tags[0]);\n" - " for (auto p : tags_unicode) {\n" - " Py_XDECREF(p);\n" - " }\n" - " for (auto p : tags_ascii) {\n" - " Py_XDECREF(p);\n" - " }\n" - " return PyLong_FromLong(result);\n" - "}\n" - "static PyObject*\n" - "_HDDM_hdf5FileCheck(PyObject *self, PyObject *args)\n" - "{\n" - " hid_t file_id;\n" - " PyObject *ptags = 0;\n" - " if (! PyArg_ParseTuple(args, \"k|O!\", &file_id, &PyList_Type, &ptags)) {\n" - " PyErr_SetString(PyExc_TypeError, \"invalid argument in hdf5FileCheck\");\n" - " return NULL;\n" - " }\n" - " std::vector tags_unicode;\n" - " std::vector tags_ascii;\n" - " std::vector tags;\n" - " if (ptags != 0) {\n" - " int ntags = PyList_Size(ptags);\n" - " for (int i=0; i < ntags; i++) {\n" - " PyObject *pitem = PyList_GetItem(ptags, i);\n" - " PyObject *pitem_str = PyObject_Str(pitem);\n" - " tags_unicode.push_back(pitem_str);\n" - " PyObject *pitem_ascii = pitem_str;\n" - " if (PyUnicode_Check(pitem_str)) {\n" - " pitem_ascii = PyUnicode_AsEncodedString(pitem_str, \"ASCII\", \"strict\");\n" - " tags_ascii.push_back(pitem_ascii);\n" - " }\n" - "#if PY_MAJOR_VERSION < 3\n" - " tags.push_back(PyString_AsString(pitem_ascii));\n" - "#else\n" - " tags.push_back(PyBytes_AsString(pitem_ascii));\n" - "#endif\n" - " }\n" - " }\n" - " tags.push_back(0);\n" - " herr_t result=0;\n" - " try {\n" - " result = hddm_" << classPrefix << - "::HDDM::hdf5FileCheck(file_id, &tags[0]);\n" - " }\n" - " catch (...) {\n" - " result = -1;\n" - " }\n" - " for (auto p : tags_unicode) {\n" - " Py_XDECREF(p);\n" - " }\n" - " for (auto p : tags_ascii) {\n" - " Py_XDECREF(p);\n" - " }\n" - " return PyLong_FromLong(result);\n" - "}\n" - "static PyObject*\n" - "_HDDM_hdf5GetEntries(PyObject *self, PyObject *args)\n" - "{\n" - " hid_t file_id;\n" - " if (! PyArg_ParseTuple(args, \"k\", &file_id)) {\n" - " PyErr_SetString(PyExc_TypeError, \"invalid argument in hdf5GetEntries\");\n" - " return NULL;\n" - " }\n" - " long int entries = hddm_" << classPrefix << - "::HDDM::hdf5GetEntries(file_id);\n" - " return PyLong_FromLong(entries);\n" - "}\n" - "static PyObject*\n" - "_HDDM_hdf5FileClose(PyObject *self, PyObject *args)\n" - "{\n" - " hid_t file_id;\n" - " if (! PyArg_ParseTuple(args, \"k\", &file_id)) {\n" - " PyErr_SetString(PyExc_TypeError, \"invalid argument in hdf5FileClose\");\n" - " return NULL;\n" - " }\n" - " herr_t result = hddm_" << classPrefix << - "::HDDM::hdf5FileClose(file_id);\n" - " return PyLong_FromLong(result);\n" - "}\n" - "static PyObject*\n" - "_HDDM_hdf5DocumentString(PyObject *self, PyObject *args)\n" - "{\n" - " hid_t file_id;\n" - " if (! PyArg_ParseTuple(args, \"k\", &file_id)) {\n" - " PyErr_SetString(PyExc_TypeError, \"invalid argument in hdf5DocumentString\");\n" - " return NULL;\n" - " }\n" - " std::string docstring = hddm_" << classPrefix << - "::HDDM::hdf5DocumentString(file_id);\n" - " return PyUnicode_FromString(docstring.c_str());\n" - "}\n" - "static PyObject*\n" - "_HDDM_hdf5GetChunksize(PyObject *self, PyObject *args)\n" - "{\n" - " hid_t file_id;\n" - " if (! PyArg_ParseTuple(args, \"k\", &file_id)) {\n" - " PyErr_SetString(PyExc_TypeError, \"invalid argument in hdf5GetChunksize\");\n" - " return NULL;\n" - " }\n" - " hsize_t result = hddm_" << classPrefix << - "::HDDM::hdf5GetChunksize(file_id);\n" - " return PyLong_FromLong(result);\n" - "}\n" - "static PyObject*\n" - "_HDDM_hdf5SetChunksize(PyObject *self, PyObject *args)\n" - "{\n" - " hid_t file_id;\n" - " hsize_t chunksize;\n" - " if (! PyArg_ParseTuple(args, \"kk\", &file_id, &chunksize)) {\n" - " PyErr_SetString(PyExc_TypeError, \"invalid argument in hdf5SetChunksize\");\n" - " return NULL;\n" - " }\n" - " herr_t result = hddm_" << classPrefix << - "::HDDM::hdf5SetChunksize(file_id, chunksize);\n" - " return PyLong_FromLong(result);\n" - "}\n" - "static PyObject*\n" - "_HDDM_hdf5GetFilters(PyObject *self, PyObject *args)\n" - "{\n" - " hid_t file_id;\n" - " PyObject *pfilters;\n" - " if (! PyArg_ParseTuple(args, \"kO!\", &file_id, &PyList_Type, &pfilters)) {\n" - " PyErr_SetString(PyExc_TypeError, \"invalid argument in hdf5GetFilters\");\n" - " return NULL;\n" - " }\n" - " std::vector filters;\n" - " herr_t result = hddm_" << classPrefix << - "::HDDM::hdf5GetFilters(file_id, filters);\n" - " PyList_SetSlice(pfilters, 0, PyList_Size(pfilters), 0);\n" - " int nfilters = filters.size();\n" - " for (int i=0; i < nfilters; i++) {\n" - " PyList_Append(pfilters, PyLong_FromLong(filters[i]));\n" - " }\n" - " return PyLong_FromLong(result);\n" - "}\n" - "static PyObject*\n" - "_HDDM_hdf5SetFilters(PyObject *self, PyObject *args)\n" - "{\n" - " hid_t file_id;\n" - " PyObject *pfilters;\n" - " if (! PyArg_ParseTuple(args, \"kO!\", &file_id, &PyList_Type, &pfilters)) {\n" - " PyErr_SetString(PyExc_TypeError, \"invalid argument in hdf5SetFilters\");\n" - " return NULL;\n" - " }\n" - " std::vector filters;\n" - " int nfilters = PyList_Size(pfilters);\n" - " for (int i=0; i < nfilters; i++) {\n" - " PyObject *pitem = PyList_GetItem(pfilters, i);\n" - " filters.push_back(PyLong_AsLong(pitem));\n" - " }\n" - " herr_t result = hddm_" << classPrefix << - "::HDDM::hdf5SetFilters(file_id, filters);\n" - " return PyLong_FromLong(result);\n" - "}\n" - "#endif\n"; - - builder.pyFile << - "\n" - "\n" - "// module declarations\n" - "\n" - "static PyMethodDef hddm_" << classPrefix << "_methods[] = {\n" - "#ifdef HDF5_SUPPORT\n" - " {\"hdf5DocumentString\", _HDDM_hdf5DocumentString, METH_VARARGS,\n" - " \"read the hddm document string from this hdf5 file\"},\n" - " {\"hdf5FileCreate\", _HDDM_hdf5FileCreate, METH_VARARGS,\n" - " \"create a new hdf5 and open for writing hddm records\"},\n" - " {\"hdf5FileOpen\", _HDDM_hdf5FileOpen, METH_VARARGS,\n" - " \"open an existing hdf5 file for reading hddm records\"},\n" - " {\"hdf5FileClose\", _HDDM_hdf5FileClose, METH_VARARGS,\n" - " \"close an open hdf5 file and free its hdf5 resources\"},\n" - " {\"hdf5FileStamp\", _HDDM_hdf5FileStamp, METH_VARARGS,\n" - " \"this is implicitly called by hdf5FileCreate\"},\n" - " {\"hdf5FileCheck\", _HDDM_hdf5FileCheck, METH_VARARGS,\n" - " \"this is implicitly called by hdf5FileOpen\"},\n" - " {\"hdf5GetEntries\", _HDDM_hdf5GetEntries, METH_VARARGS,\n" - " \"returns the number of hddm records in a hdf5 file\"},\n" - " {\"hdf5GetFilters\", _HDDM_hdf5GetFilters, METH_VARARGS,\n" - " \"gets the list of filters active on a hdf5 file\"},\n" - " {\"hdf5SetFilters\", _HDDM_hdf5SetFilters, METH_VARARGS,\n" - " \"sets the list of filters active on a hdf5 file\"},\n" - " {\"hdf5GetChunksize\", _HDDM_hdf5GetChunksize, METH_VARARGS,\n" - " \"gets the hddm dataset chunksize on an open hdf5 file\"},\n" - " {\"hdf5SetChunksize\", _HDDM_hdf5SetChunksize, METH_VARARGS,\n" - " \"sets the hddm dataset chunksize on an open hdf5 file\"},\n" - "#endif\n" - " {NULL} /* Sentinel */\n" - "};\n" - "\n" - "char hddm_" << classPrefix << "_doc[] = \"Python module for " - "hddm_" << classPrefix << " i/o package\";\n" - "\n" - "#if PY_MAJOR_VERSION >= 3\n" - " static struct PyModuleDef moduledef = {\n" - " PyModuleDef_HEAD_INIT,\n" - " \"hddm_" << classPrefix << "\", /* m_name */\n" - " hddm_" << classPrefix << "_doc, /* m_doc */\n" - " -1, /* m_size */\n" - " hddm_" << classPrefix << "_methods, /* m_methods */\n" - " NULL, /* m_reload */\n" - " NULL, /* m_traverse */\n" - " NULL, /* m_clear */\n" - " NULL, /* m_free */\n" - " };\n" - "#endif\n" - "\n" - "static PyObject *\n" - "hddm_" << classPrefix << "_init(void) \n" - "{\n" - " PyObject* m;\n" - "\n" - "#if PY_MAJOR_VERSION >= 3\n" - " m = PyModule_Create(&moduledef);\n" - "#else\n" - " m = Py_InitModule3(\"hddm_" << classPrefix << "\"," - " hddm_" << classPrefix << "_methods," - " hddm_" << classPrefix << "_doc);\n" - "#endif\n" - "\n" - " if (m == NULL)\n" - " return NULL;\n" - "\n" - ; - - std::map::iterator titer; - for (titer = builder.typesList.begin(); - titer != builder.typesList.end(); ++titer) - { - builder.pyFile << - " if (PyType_Ready(&" << titer->second << ") < 0)\n" - " return NULL;\n" - " Py_INCREF(&" << titer->second << ");\n" - " PyModule_AddObject(m, \"" << titer->first << "\"," - " (PyObject*)&" << titer->second << ");\n" - ; - } - - builder.pyFile << - "\n" - " PyModule_AddIntConstant(m, \"k_default_status\", k_default_status);\n" - " PyModule_AddIntConstant(m, \"k_bits_compression\", k_bits_compression);\n" - " PyModule_AddIntConstant(m, \"k_no_compression\", k_no_compression);\n" - " PyModule_AddIntConstant(m, \"k_z_compression\", k_z_compression);\n" - " PyModule_AddIntConstant(m, \"k_bz2_compression\", k_bz2_compression);\n" - " PyModule_AddIntConstant(m, \"k_bits_integrity\", k_bits_integrity);\n" - " PyModule_AddIntConstant(m, \"k_no_integrity\", k_no_integrity);\n" - " PyModule_AddIntConstant(m, \"k_crc32_integrity\", k_crc32_integrity);\n" - " PyModule_AddIntConstant(m, \"k_bits_randomaccess\", k_bits_randomaccess);\n" - " PyModule_AddIntConstant(m, \"k_can_reposition\", k_can_reposition);\n" - " PyModule_AddIntConstant(m, \"k_hddm_unknown\", k_hddm_unknown);\n" - " PyModule_AddIntConstant(m, \"k_hddm_int\", k_hddm_int);\n" - " PyModule_AddIntConstant(m, \"k_hddm_long\", k_hddm_long);\n" - " PyModule_AddIntConstant(m, \"k_hddm_float\", k_hddm_float);\n" - " PyModule_AddIntConstant(m, \"k_hddm_double\", k_hddm_double);\n" - " PyModule_AddIntConstant(m, \"k_hddm_boolean\", k_hddm_boolean);\n" - " PyModule_AddIntConstant(m, \"k_hddm_string\", k_hddm_string);\n" - " PyModule_AddIntConstant(m, \"k_hddm_anyURI\", k_hddm_anyURI);\n" - " PyModule_AddIntConstant(m, \"k_hddm_Particle_t\", k_hddm_Particle_t);\n" - " std::string docstring = HDDM::DocumentString();\n" - " PyModule_AddStringConstant(m, \"DocumentString\", docstring.c_str());\n" - "\n" - "#ifdef HDF5_SUPPORT\n" - " PyModule_AddIntConstant(m, \"k_hdf5_gzip_filter\", k_hdf5_gzip_filter);\n" - " PyModule_AddIntConstant(m, \"k_hdf5_szip_filter\", k_hdf5_szip_filter);\n" - " PyModule_AddIntConstant(m, \"k_hdf5_bzip2_plugin\", k_hdf5_bzip2_plugin);\n" - " PyModule_AddIntConstant(m, \"k_hdf5_blosc_plugin\", k_hdf5_blosc_plugin);\n" - " PyModule_AddIntConstant(m, \"k_hdf5_bshuf_plugin\", k_hdf5_bshuf_plugin);\n" - " PyModule_AddIntConstant(m, \"k_hdf5_jpeg_plugin\", k_hdf5_jpeg_plugin);\n" - " PyModule_AddIntConstant(m, \"k_hdf5_lz4_plugin\", k_hdf5_lz4_plugin);\n" - " PyModule_AddIntConstant(m, \"k_hdf5_lzf_plugin\", k_hdf5_lzf_plugin);\n" - "#endif\n" - "\n" - " return m;\n" - "}\n" - "\n" - "#if PY_MAJOR_VERSION < 3\n" - " PyMODINIT_FUNC\n" - " inithddm_" << classPrefix << "(void)\n" - " {\n" - " hddm_" << classPrefix << "_init();\n" - " }\n" - "#else\n" - " PyMODINIT_FUNC\n" - " PyInit_hddm_" << classPrefix << "(void)\n" - " {\n" - " return hddm_" << classPrefix << "_init();\n" - " }\n" - "#endif\n" - ; - -/* convert cpy filename "/hddm_X.cpy" - * to setup filename "/setup_hddm_X.py" - */ - size_t p1 = pyname.rfind("pyhddm_"); - pyname.erase(p1, 2); - pyname.insert(p1, "setup_"); - size_t p2 = pyname.rfind("cpy"); - pyname.erase(p2, 1); - - std::ofstream pysetup(pyname.c_str()); - pysetup << - "#\n" - "# This file was generated by the hddm-py utility\n" - "# from the project https://github.com/rjones30/HDDM\n" - "#\n" - "import sys\n" - "import os\n" - "from distutils.core import setup, Extension\n" - "from shutil import copyfile, rmtree\n" - "import re\n" - "\n" - "# Remove the \"-Wstrict-prototypes\" compiler options,\n" - "# which isn't valid for C++\n" - "import distutils.sysconfig\n" - "cfg_vars = distutils.sysconfig.get_config_vars()\n" - "for key,value in cfg_vars.items():\n" - " if type(value) == str:\n" - " cfg_vars[key] = value.replace(\"-Wstrict-prototypes\", \"\")\n" - "\n" - "os.environ['CC'] = 'g++' # distutils uses compiler options unique to gcc\n" - "\n" - "build_dir = 'build_hddm_" + classPrefix + "'\n" - "if len(sys.argv) == 1:\n" - " sys.argv += ['build', '-b', build_dir]\n" - "\n" - "source_dir = os.path.realpath(__file__)\n" - "m = re.sub(r'/[^/]*$', '', source_dir)\n" - "if m:\n" - " source_dir = m\n" - "else:\n" - " source_dir = '.'\n" - "os.environ['HDDM_DIR'] = '/'.join([os.environ['HALLD_RECON_HOME'], \n" - " os.environ['BMS_OSNAME']])\n" - "if 'HDDM_DIR' in os.environ:\n" - " hddm_dir = os.environ['HDDM_DIR']\n" - "else:\n" - " print('HDDM_DIR not defined, module creation failed!')\n" - " print('environment is:')\n" - " for key in os.environ:\n" - " print(' {0}: {1}'.format(key, os.environ[key]))\n" - " sys.exit(1)\n" - "source_file = 'pyhddm_" + classPrefix + ".cxx'\n" - "source_files = [source_file, source_dir + '/hddm_" + classPrefix + "++.cpp']\n" - "copyfile(source_dir + '/pyhddm_" + classPrefix + ".cpy', source_file)\n" - "my_include_dirs = [source_dir, hddm_dir + '/include',]\n" - "my_library_dirs = [hddm_dir + '/lib', '/usr/lib64',]\n" - "my_libraries = ['xstream', 'bz2', 'z']\n" - "my_extra_cxxflags = ['-std=c++11']\n" - "if 'HDF5_INCLUDE_DIRS' in os.environ:\n" - " for idir in os.environ['HDF5_INCLUDE_DIRS'].split(':'):\n" - " my_include_dirs += [idir,]\n" - "if 'HDF5_LIBRARIES' in os.environ:\n" - " for lib in os.environ['HDF5_LIBRARIES'].split(':'):\n" - " my_libraries += [lib,]\n" - " my_extra_cxxflags += ['-DHDF5_SUPPORT']\n" - "\n" - "module1 = Extension('hddm_" + classPrefix + "',\n" - " include_dirs = my_include_dirs,\n" - " library_dirs = my_library_dirs,\n" - " libraries = my_libraries,\n" - " extra_compile_args = my_extra_cxxflags,\n" - " sources = source_files)\n" - "\n" - "setup (name = 'hddm_" << classPrefix << "',\n" - " version = '1.0',\n" - " description = 'HDDM data model i/o package',\n" - " ext_modules = [module1])\n" - "\n" - "os.remove(source_file)\n" - "for dname in os.listdir(build_dir):\n" - " for soname in os.listdir(build_dir + '/' + dname):\n" - " if re.match(r'.*\\.so', soname):\n" - " src = build_dir + '/' + dname + '/' + soname\n" - " dest = source_dir + '/' + soname\n" - " copyfile(src, dest)\n" - "rmtree(build_dir)\n" - ; - - XMLPlatformUtils::Terminate(); - return 0; -} - -XtString XtString::plural() -{ - XtString p(*this); - XtString::size_type len = p.size(); - if (len > 3 && p.substr(len-3,3) == "tum") - { - p.replace(len-3,3,"ta"); - } - else if (len > 1 && p.substr(len-3,3) == "ies") - { - p.replace(len-3,3,"iesList"); - } - else if (len > 2 && p.substr(len-2,2) == "ex") - { - p.replace(len-2,2,"ices"); - } - else if (len > 2 && p.substr(len-2,2) == "sh") - { - p.replace(len-2,2,"shes"); - } - else if (len > 1 && p.substr(len-1,1) == "s") - { - p.replace(len-1,1,"ses"); - } - else if (len > 1) - { - p += "s"; - } - return p; -} - -/* Map from tag name to name of the corresponding class - * for the case of simple tags (those that do not repeat) - */ -XtString XtString::simpleType() -{ - XtString p(*this); - p[0] = toupper(p[0]); - return p; -} - -/* Map from tag name to name of the corresponding class - * for the case of list tags (those that may repeat) - */ -XtString XtString::listType() -{ - XtString r(*this); - r[0] = toupper(r[0]); - r = r + "List"; - return r; -} - -/* Map from tag name to name of the corresponding class - * for the case of link tags (those that do not repeat) - */ -XtString XtString::linkType() -{ - XtString r(*this); - r[0] = toupper(r[0]); - r = r + "Link"; - return r; -} - -/* Look for a named element in a list of element pointers - * and return index of first instance in the list if found, - * otherwise return -1; - */ -int CodeBuilder::element_in_list(XtString &name, parentList_t list) -{ - int n=0; - parentList_t::iterator iter; - for (iter = list.begin(); iter != list.end(); ++iter, ++n) - { - DOMElement *el = (DOMElement*)(*iter); - XtString cnameS(el->getTagName()); - if (cnameS == name) { - return n; - } - } - return -1; -} - -/* Verify that the tag group under this element does not collide - * with existing tag group elref, otherwise exit with fatal error - */ -void CodeBuilder::checkConsistency(DOMElement* el, DOMElement* elref) -{ - XtString tagS(el->getTagName()); - if (el->getParentNode() == elref->getParentNode()) - { - std::cerr - << "hddm-py error: tag " << "\"" << tagS - << "\" is duplicated within one context in xml document." - << std::endl; - exit(1); - } - - DOMNamedNodeMap* oldAttr = elref->getAttributes(); - DOMNamedNodeMap* newAttr = el->getAttributes(); - unsigned int listLength = oldAttr->getLength(); - for (unsigned int n = 0; n < listLength; n++) - { - XtString nameS(oldAttr->item(n)->getNodeName()); - XtString oldS(elref->getAttribute(X(nameS))); - XtString newS(el->getAttribute(X(nameS))); - if (nameS == "minOccurs") - { - continue; - } - else if (nameS == "maxOccurs") - { - int maxold = (oldS == "unbounded")? INT_MAX : atoi(S(oldS)); - int maxnew = (newS == "unbounded")? INT_MAX : atoi(S(newS)); - if ((maxold < 2 && maxnew > 1) || (maxold > 1 && maxnew < 2)) - { - std::cerr - << "hddm-py error: inconsistent maxOccurs usage by tag " - << "\"" << tagS << "\" in xml document." << std::endl; - exit(1); - } - } - else if (newS != oldS) - { - std::cerr - << "hddm-py error: inconsistent usage of attribute " - << "\"" << nameS << "\" in tag " - << "\"" << tagS << "\" in xml document." << std::endl; - exit(1); - } - } - listLength = newAttr->getLength(); - for (unsigned int n = 0; n < listLength; n++) - { - XtString nameS(newAttr->item(n)->getNodeName()); - XtString oldS(elref->getAttribute(X(nameS))); - XtString newS(el->getAttribute(X(nameS))); - if (nameS == "minOccurs") - { - continue; - } - else if (nameS == "maxOccurs") - { - int maxold = (oldS == "unbounded")? INT_MAX : atoi(S(oldS)); - int maxnew = (newS == "unbounded")? INT_MAX : atoi(S(newS)); - if ((maxold < 2 && maxnew > 1) || (maxold > 1 && maxnew < 2)) - { - std::cerr - << "hddm-py error: inconsistent maxOccurs usage by tag " - << "\"" << tagS << "\" in xml document." << std::endl; - exit(1); - } - } - else if (newS != oldS) - { - std::cerr - << "hddm-py error: inconsistent usage of attribute " - << "\"" << nameS << "\" in tag " - << "\"" << tagS << "\" in xml document." << std::endl; - exit(1); - } - } - DOMNodeList* oldList = elref->getChildNodes(); - DOMNodeList* newList = el->getChildNodes(); - listLength = oldList->getLength(); - if (newList->getLength() != listLength) - { - std::cerr - << "hddm-py error: inconsistent usage of tag " - << "\"" << tagS << "\" in xml document." << std::endl; - exit(1); - } - for (unsigned int n = 0; n < listLength; n++) - { - DOMNode* cont = oldList->item(n); - XtString nameS(cont->getNodeName()); - short type = cont->getNodeType(); - if (type == DOMNode::ELEMENT_NODE) - { - DOMNodeList* contList = el->getElementsByTagName(X(nameS)); - if (contList->getLength() != 1) - { - std::cerr - << "hddm-py error: inconsistent usage of tag " - << "\"" << tagS << "\" in xml document." << std::endl; - exit(1); - } - } - } -} - -/* Write declaration of the classes for this tag */ - -void CodeBuilder::writeClassdef(DOMElement* el) -{ - XtString tagS(el->getTagName()); - pyFile << - "\n\n" - "// wrap element class hddm_" << classPrefix << "::" << tagS.simpleType() << - " as hddm_" << classPrefix << "." << tagS.simpleType() << "\n" - "\n" - "typedef struct {\n" - " PyObject_HEAD\n" - " " << tagS.simpleType() << " *elem;\n" - " PyObject *host;\n" - "} _" << tagS.simpleType() << ";\n" - "\n" - "static void\n" - "_" << tagS.simpleType() << "_dealloc(_" << tagS.simpleType() << "* self)\n" - "{\n" - " if (self->elem != 0) {\n" - " LOG_DEALLOC(Py_TYPE(self), 0, self->host == (PyObject*)self);\n" - " if (self->host == (PyObject*)self)\n" - " delete self->elem;\n" - " else\n" - " My_DECREF(self->host);\n" - " }\n" - " Py_TYPE(self)->tp_free((PyObject*)self);\n" - "}\n" - "\n" - "static PyObject*\n" - "_" << tagS.simpleType() << - "_new(PyTypeObject *type, PyObject *args, PyObject *kwds)\n" - "{\n" - " _" << tagS.simpleType() << " *self;\n" - " self = (_" << tagS.simpleType() << "*)type->tp_alloc(type, 0);\n" - " if (self != NULL) {\n" - " self->elem = 0;\n" - " self->host = 0;\n" - " }\n" - " return (PyObject*)self;\n" - "}\n" - "\n" - ; - - if (tagS == "HDDM") - { - pyFile << - "static int\n" - "_HDDM_init(_HDDM *self, PyObject *args, PyObject *kwds)\n" - "{\n" - " LOG_NEW(Py_TYPE(self), 0, 1);\n" - " self->elem = new HDDM();\n" - " if (self->elem == 0) {\n" - " PyErr_SetString(PyExc_RuntimeError, \"HDDM new constructor failed\");\n" - " return -1;\n" - " }\n" - " self->host = (PyObject*)self;\n" - " return 0;\n" - "}\n" - "\n" - ; - pyFile << - "#ifdef HDF5_SUPPORT\n" - "static PyObject*\n" - "_HDDM_hdf5FileRead(PyObject *self, PyObject *args)\n" - "{\n" - " hid_t file_id;\n" - " long int entry = -1;\n" - " if (! PyArg_ParseTuple(args, \"k|l\", &file_id, &entry)) {\n" - " return NULL;\n" - " }\n" - " _HDDM *me = (_HDDM*)self;\n" - " herr_t result = me->elem->hdf5FileRead(file_id, entry);\n" - " return PyLong_FromLong(result);\n" - "}\n" - "static PyObject*\n" - "_HDDM_hdf5FileWrite(PyObject *self, PyObject *args)\n" - "{\n" - " hid_t file_id;\n" - " long int entry = -1;\n" - " if (! PyArg_ParseTuple(args, \"k|l\", &file_id, &entry)) {\n" - " return NULL;\n" - " }\n" - " _HDDM *me = (_HDDM*)self;\n" - " herr_t result = me->elem->hdf5FileWrite(file_id, entry);\n" - " return PyLong_FromLong(result);\n" - "}\n" - "#endif\n" - ; - } - else - { - pyFile << - "static int\n" - "_" << tagS.simpleType() << "_init(_" << tagS.simpleType() << - " *self, PyObject *args, PyObject *kwds)\n" - "{\n" - " PyErr_SetString(PyExc_RuntimeError, \"illegal constructor\");\n" - " return -1;\n" - "}\n" - "\n" - ; - } - - std::map attrList; - DOMNamedNodeMap *myAttr = el->getAttributes(); - for (unsigned int n = 0; n < myAttr->getLength(); n++) - { - XtString attrS(myAttr->item(n)->getNodeName()); - XtString typeS(el->getAttribute(X(attrS))); - attrList[attrS] = typeS; - } - parentList_t::iterator iter; - for (iter = parents[tagS].begin(); iter != parents[tagS].end(); ++iter) - { - DOMElement *hostEl = (DOMElement*)(*iter); - XtString hostS(hostEl->getTagName()); - DOMNamedNodeMap *hostAttr = hostEl->getAttributes(); - for (unsigned int n = 0; n < hostAttr->getLength(); n++) - { - XtString attrS(hostAttr->item(n)->getNodeName()); - if (attrList.find(attrS) != attrList.end()) - { - continue; - } - XtString typeS(hostEl->getAttribute(X(attrS))); - attrList[attrS] = typeS; - XtString getS("get" + attrS.simpleType()); - pyFile << "static PyObject*\n" << - "_" << tagS.simpleType() << "_" << getS << - "(_" << tagS.simpleType() << " *self, void *closure)\n" - "{\n"; - if (typeS == "int") - { - pyFile << " return PyLong_FromLong(self->elem->" - << getS << "());\n"; - } - else if (typeS == "long") - { - pyFile << " return PyLong_FromLong(self->elem->" - << getS << "());\n"; - } - else if (typeS == "float") - { - pyFile << " return PyFloat_FromDouble(self->elem->" - << getS << "());\n"; - } - else if (typeS == "double") - { - pyFile << " return PyFloat_FromDouble(self->elem->" - << getS << "());\n"; - } - else if (typeS == "boolean") - { - pyFile << " return PyBool_FromLong(self->elem->" - << getS << "());\n"; - } - else if (typeS == "string") - { - pyFile << " std::string val(self->elem->" - << getS << "());\n" - << " return PyUnicode_FromString(val.c_str());\n"; - attrList[attrS] = "string"; - } - else if (typeS == "anyURI") - { - pyFile << " std::string val(self->elem->" - << getS << "());\n" - << " return PyUnicode_FromString(val.c_str());\n"; - attrList[attrS] = "string"; - } - else if (typeS == "Particle_t") - { - pyFile << " Particle_t p(self->elem->" - << getS << "());\n" - << " std::string val(ParticleType(p));\n" - << " return PyUnicode_FromString(val.c_str());\n"; - } - else if (guessType(typeS) == "int") - { - pyFile << " return PyLong_FromLong(self->elem->" - << getS << "());\n"; - } - else if (guessType(typeS) == "long") - { - pyFile << " return PyLong_FromLong(self->elem->" - << getS << "());\n"; - } - else if (guessType(typeS) == "float") - { - pyFile << " return PyFloat_FromDouble(self->elem->" - << getS << "());\n"; - } - else if (guessType(typeS) == "double") - { - pyFile << " return PyFloat_FromDouble(self->elem->" - << getS << "());\n"; - } - else if (guessType(typeS) == "boolean") - { - pyFile << " return PyBool_FromLong(self->elem->" - << getS << "());\n"; - } - else if (guessType(typeS) == "Particle_t") - { - pyFile << " Particle_t p(self->elem->" - << getS << "());\n" - << " std::string val(ParticleType(p));\n" - << " return PyUnicode_FromString(val.c_str());\n"; - } - else /* any values not matching the above are strings */ - { - pyFile << " std::string val(self->elem->" - << getS << "());\n" - << " return PyUnicode_FromString(val.c_str());\n"; - attrList[attrS] = "string"; - } - pyFile << "}\n\n"; - } - } - - std::map setters; - myAttr = el->getAttributes(); - for (unsigned int n = 0; n < myAttr->getLength(); n++) - { - XtString attrS(myAttr->item(n)->getNodeName()); - XtString typeS(el->getAttribute(X(attrS))); - XtString getS("get" + attrS.simpleType()); - pyFile << "static PyObject*\n" << - "_" << tagS.simpleType() << "_" << getS << - "(_" << tagS.simpleType() << " *self, void *closure)\n" - "{\n"; - if (typeS == "int") - { - pyFile << " return PyLong_FromLong(self->elem->" - << getS << "());\n"; - } - else if (typeS == "long") - { - pyFile << " return PyLong_FromLong(self->elem->" - << getS << "());\n"; - } - else if (typeS == "float") - { - pyFile << " return PyFloat_FromDouble(self->elem->" - << getS << "());\n"; - } - else if (typeS == "double") - { - pyFile << " return PyFloat_FromDouble(self->elem->" - << getS << "());\n"; - } - else if (typeS == "boolean") - { - pyFile << " return PyBool_FromLong(self->elem->" - << getS << "());\n"; - } - else if (typeS == "string") - { - pyFile << " std::string val(self->elem->" - << getS << "());\n" - << " return PyUnicode_FromString(val.c_str());\n"; - } - else if (typeS == "anyURI") - { - pyFile << " std::string val(self->elem->" - << getS << "());\n" - << " return PyUnicode_FromString(val.c_str());\n"; - } - else if (typeS == "Particle_t") - { - pyFile << " Particle_t p(self->elem->" - << getS << "());\n" - << " std::string val(ParticleType(p));\n" - << " return PyUnicode_FromString(val.c_str());\n"; - } - else if (guessType(typeS) == "int") - { - pyFile << " return PyLong_FromLong(self->elem->" - << getS << "());\n"; - } - else if (guessType(typeS) == "long") - { - pyFile << " return PyLong_FromLong(self->elem->" - << getS << "());\n"; - } - else if (guessType(typeS) == "float") - { - pyFile << " return PyFloat_FromDouble(self->elem->" - << getS << "());\n"; - } - else if (guessType(typeS) == "double") - { - pyFile << " return PyFloat_FromDouble(self->elem->" - << getS << "());\n"; - } - else if (guessType(typeS) == "boolean") - { - pyFile << " return PyBool_FromLong(self->elem->" - << getS << "());\n"; - } - else if (guessType(typeS) == "Particle_t") - { - pyFile << " Particle_t p(self->elem->" - << getS << "());\n" - << " std::string val(ParticleType(p));\n" - << " return PyUnicode_FromString(val.c_str());\n"; - } - else /* any values not matching the above are strings */ - { - pyFile << " std::string val(self->elem->" - << getS << "());\n" - << " return PyUnicode_FromString(val.c_str());\n"; - } - pyFile << "}\n\n"; - - XtString setS("set" + attrS.simpleType()); - if (typeS == "int") - { - pyFile << "static int\n" << - "_" << tagS.simpleType() << "_" << setS << - "(_" << tagS.simpleType() << - " *self, PyObject *value, void *closure)\n" - "{\n" - " long var = PyInt_AsLong(value);\n" - " if (var == -1 && PyErr_Occurred()) {\n" - " return -1;\n" - " }\n" - " self->elem->" << setS << "(var);\n" - " return 0;\n" - "}\n\n"; - setters[attrS] = 1; - } - else if (typeS == "long") - { - pyFile << "static int\n" << - "_" << tagS.simpleType() << "_" << setS << - "(_" << tagS.simpleType() << - " *self, PyObject *value, void *closure)\n" - "{\n" - " long var = PyInt_AsLong(value);\n" - " if (var == -1 && PyErr_Occurred()) {\n" - " return -1;\n" - " }\n" - " self->elem->" << setS << "(var);\n" - " return 0;\n" - "}\n\n"; - setters[attrS] = 1; - } - else if (typeS == "float") - { - pyFile << "static int\n" << - "_" << tagS.simpleType() << "_" << setS << - "(_" << tagS.simpleType() << - " *self, PyObject *value, void *closure)\n" - "{\n" - " double var = PyFloat_AsDouble(value);\n" - " if (var == -1 && PyErr_Occurred()) {\n" - " return 1;\n" - " }\n" - " self->elem->" << setS << "(var);\n" - " return 0;\n" - "}\n\n"; - setters[attrS] = 1; - } - else if (typeS == "double") - { - pyFile << "static int\n" << - "_" << tagS.simpleType() << "_" << setS << - "(_" << tagS.simpleType() << - " *self, PyObject *value, void *closure)\n" - "{\n" - " double var = PyFloat_AsDouble(value);\n" - " if (var == -1 && PyErr_Occurred()) {\n" - " return -1;\n" - " }\n" - " self->elem->" << setS << "(var);\n" - " return 0;\n" - "}\n\n"; - setters[attrS] = 1; - } - else if (typeS == "boolean") - { - pyFile << "static int\n" << - "_" << tagS.simpleType() << "_" << setS << - "(_" << tagS.simpleType() << - " *self, PyObject *value, void *closure)\n" - "{\n" - " long var = PyInt_AsLong(value);\n" - " if (var == -1 && PyErr_Occurred()) {\n" - " return -1;\n" - " }\n" - " self->elem->" << setS << "((var==0)? false : true);\n" - " return 0;\n" - "}\n\n"; - setters[attrS] = 1; - } - else if (typeS == "string") - { - pyFile << "static int\n" << - "_" << tagS.simpleType() << "_" << setS << - "(_" << tagS.simpleType() << - " *self, PyObject *value, void *closure)\n" - "{\n" - " PyObject *str=0;\n" - " if (PyUnicode_Check(value))\n" - " str = PyUnicode_AsEncodedString(value, \"ASCII\", \"strict\");\n" - " else\n" - " str = value;\n" - "#if PY_MAJOR_VERSION < 3\n" - " char *var = PyString_AsString(str);\n" - "#else\n" - " char *var = PyBytes_AsString(str);\n" - "#endif\n" - " if (var == 0) {\n" - " return -1;\n" - " }\n" - " self->elem->" << setS << "(std::string(var));\n" - " if (str != value) {\n" - " Py_DECREF(str);\n" - " }\n" - " return 0;\n" - "}\n\n"; - setters[attrS] = 1; - } - else if (typeS == "anyURI") - { - pyFile << "static int\n" << - "_" << tagS.simpleType() << "_" << setS << - "(_" << tagS.simpleType() << - " *self, PyObject *value, void *closure)\n" - "{\n" - " PyObject *str=0;\n" - " if (PyUnicode_Check(value))\n" - " str = PyUnicode_AsEncodedString(value, \"ASCII\", \"strict\");\n" - " else\n" - " str = value;\n" - "#if PY_MAJOR_VERSION < 3\n" - " char *var = PyString_AsString(str);\n" - "#else\n" - " char *var = PyBytes_AsString(str);\n" - "#endif\n" - " if (var == 0) {\n" - " return -1;\n" - " }\n" - " self->elem->" << setS << "(std::string(var));\n" - " if (str != value) {\n" - " Py_DECREF(str);\n" - " }\n" - " return 0;\n" - "}\n\n"; - setters[attrS] = 1; - } - else if (typeS == "Particle_t") - { - pyFile << "static int\n" << - "_" << tagS.simpleType() << "_" << setS << - "(_" << tagS.simpleType() << - " *self, PyObject *value, void *closure)\n" - "{\n" - " long var = PyInt_AsLong(value);\n" - " if (var == -1 && PyErr_Occurred()) {\n" - " return -1;\n" - " }\n" - " self->elem->" << setS << "((Particle_t)var);\n" - " return 0;\n" - "}\n\n"; - setters[attrS] = 1; - } - } - - std::map methods; - - if (tagS == "HDDM") { - parentTable_t::iterator piter; - for (piter = parents.begin(); piter != parents.end(); ++piter) - { - XtString cnameS(piter->first); - if (cnameS != "HDDM" && element_in_list(cnameS,children[tagS]) == -1) - { - XtString getS("_" + tagS.simpleType() + "_get" - + cnameS.plural().simpleType()); - pyFile << "static PyObject*\n" << getS << - "(PyObject *self, PyObject *args)\n" - "{\n" - " _" << tagS.simpleType() << - " *me = (_" << tagS.simpleType() << "*)self;\n" - " if (me->elem == 0) {\n" - " PyErr_SetString(PyExc_RuntimeError, " - "\"lookup attempted on invalid " << tagS << - " element\");\n" - " return NULL;\n" - " }\n" - " PyObject *list = _HDDM_ElementList" - "_new(&_HDDM_ElementList_type, 0, 0);\n" - " ((_HDDM_ElementList*)list)->subtype = " - "&_" << cnameS.simpleType() << "_type;\n" - " ((_HDDM_ElementList*)list)->list = " - "(HDDM_ElementList*)\n" << " " - "new " << cnameS.listType() << "(" - "me->elem->get" << cnameS.plural().simpleType() << "());\n" - " ((_HDDM_ElementList*)list)->borrowed = 0;\n" - " ((_HDDM_ElementList*)list)->host = me->host;\n" - " My_INCREF(me->host);\n" - " LOG_NEW(Py_TYPE(list), " - "((_HDDM_ElementList*)list)->subtype, 1);\n" - " return list;\n" - "}\n\n" - ; - method_descr meth_getS = {"get" + cnameS.plural().simpleType(), - "METH_NOARGS", - "get complete list of " + cnameS + - " objects for this record"}; - methods[getS] = meth_getS; - } - } - } - - parentList_t::iterator citer; - for (citer = children[tagS].begin(); citer != children[tagS].end(); ++citer) - { - DOMElement *childEl = (DOMElement*)(*citer); - XtString cnameS(childEl->getTagName()); - XtString repS(childEl->getAttribute(X("maxOccurs"))); - int rep = (repS == "unbounded")? INT_MAX : atoi(S(repS)); - XtString getS("_" + tagS.simpleType() + "_get" + cnameS.simpleType()); - pyFile << "static PyObject*\n" << getS << - "(PyObject *self, PyObject *args)\n" - "{\n" - " int index=0;\n" - " if (! PyArg_ParseTuple(args, \"|i\", &index)) {\n" - " return NULL;\n" - " }\n" - " _" << tagS.simpleType() << - " *me = (_" << tagS.simpleType() << "*)self;\n" - " if (me->elem == 0) {\n" - " PyErr_SetString(PyExc_RuntimeError, " - "\"lookup attempted on invalid " << tagS << - " element\");\n" - " return NULL;\n" - " }\n" - " PyObject *obj = _" << cnameS.simpleType() << - "_new(&_" << cnameS.simpleType() << "_type, 0, 0);\n" - " ((_" << cnameS.simpleType() << - "*)obj)->elem = &me->elem->get" << cnameS.simpleType() - << ((rep > 1)? "(index)" : "()") << ";\n" - " ((_" << cnameS.simpleType() << "*)obj)->host = me->host;\n" - " My_INCREF(me->host);\n" - " LOG_NEW(Py_TYPE(obj));\n" - " return obj;\n" - "}\n\n" - ; - method_descr meth_getS = {"get" + cnameS.simpleType(), - "METH_VARARGS", - "get an individual " + cnameS + - " object from this " + tagS}; - methods[getS] = meth_getS; - - XtString gelS("_" + tagS.simpleType() - + "_get" + cnameS.plural().simpleType()); - pyFile << "static PyObject*\n" << gelS << - "(PyObject *self, PyObject *args)\n" - "{\n" - " _" << tagS.simpleType() << - " *me = (_" << tagS.simpleType() << "*)self;\n" - " if (me->elem == 0) {\n" - " PyErr_SetString(PyExc_RuntimeError, " - "\"lookup attempted on invalid " << tagS << - " element\");\n" - " return NULL;\n" - " }\n" - " PyObject *list = _HDDM_ElementList_new" - "(&_HDDM_ElementList_type, 0, 0);\n" - " ((_HDDM_ElementList*)list)->subtype =" - " &_" << cnameS.simpleType() << "_type;\n" - " ((_HDDM_ElementList*)list)->list = " - "(HDDM_ElementList*)\n" << " " - "&me->elem->get" << cnameS.plural().simpleType() << "();\n" - " ((_HDDM_ElementList*)list)->borrowed = 1;\n" - " ((_HDDM_ElementList*)list)->host = me->host;\n" - " My_INCREF(me->host);\n" - " LOG_NEW(Py_TYPE(list), " - "((_HDDM_ElementList*)list)->subtype, 0);\n" - " return list;\n" - "}\n\n" - ; - method_descr meth_gelS = {"get" + cnameS.plural().simpleType(), - "METH_NOARGS", - "get list of " + cnameS + - " objects for this " + tagS}; - methods[gelS] = meth_gelS; - - XtString addS("_" + tagS.simpleType() - + "_add" + cnameS.plural().simpleType()); - pyFile << "static PyObject*\n" << addS << - "(PyObject *self, PyObject *args)\n" - "{\n" - " int count=1;\n" - " int start=-1;\n" - " if (! PyArg_ParseTuple(args, \"|ii\", &count, &start)) {\n" - " return NULL;\n" - " }\n" - " _" << tagS.simpleType() << - " *me = (_" << tagS.simpleType() << "*)self;\n" - " if (me->elem == 0) {\n" - " PyErr_SetString(PyExc_RuntimeError, " - "\"add attempted on invalid " << tagS << - " element\");\n" - " return NULL;\n" - " }\n" - " PyObject *list = _HDDM_ElementList_new" - "(&_HDDM_ElementList_type, 0, 0);\n" - " ((_HDDM_ElementList*)list)->subtype =" - " &_" << cnameS.simpleType() << "_type;\n" - " ((_HDDM_ElementList*)list)->list = " - "(HDDM_ElementList*)\n" << " " - "new " << cnameS.listType() << "(" - "me->elem->add" << cnameS.plural().simpleType() << - "(count, start));\n" - " ((_HDDM_ElementList*)list)->borrowed = 0;\n" - " ((_HDDM_ElementList*)list)->host = me->host;\n" - " My_INCREF(me->host);\n" - " LOG_NEW(Py_TYPE(list), " - "((_HDDM_ElementList*)list)->subtype, 1);\n" - " return list;\n" - "}\n\n" - ; - method_descr meth_addS = {"add" + cnameS.plural().simpleType(), - "METH_VARARGS", - "extend (or insert into) the list of " + cnameS + - " objects for this " + tagS}; - methods[addS] = meth_addS; - - XtString delS("_" + tagS.simpleType() - + "_delete" + cnameS.plural().simpleType()); - pyFile << "static PyObject*\n" << delS << - "(PyObject *self, PyObject *args)\n" - "{\n" - " int count=-1;\n" - " int start=0;\n" - " if (! PyArg_ParseTuple(args, \"|ii\", &count, &start)) {\n" - " return NULL;\n" - " }\n" - " _" << tagS.simpleType() << - " *me = (_" << tagS.simpleType() << "*)self;\n" - " if (me->elem == 0) {\n" - " PyErr_SetString(PyExc_RuntimeError, " - "\"delete attempted on invalid " << tagS << - " element\");\n" - " return NULL;\n" - " }\n" - " me->elem->delete" << cnameS.plural().simpleType() << - "(count, start);\n" - " Py_INCREF(Py_None);\n" - " return Py_None;\n" - "}\n\n" - ; - method_descr meth_delS = {"delete" + cnameS.plural().simpleType(), - "METH_VARARGS", - "delete " + cnameS + " objects for this " + tagS}; - methods[delS] = meth_delS; - } - - if (tagS == "HDDM") - { - XtString clrS("_" + tagS.simpleType() + "_clear"); - pyFile << "static PyObject*\n" << clrS << - "(PyObject *self, PyObject *args)\n" - "{\n" - " _" << tagS.simpleType() << - " *me = (_" << tagS.simpleType() << "*)self;\n" - " if (me->elem == 0) {\n" - " PyErr_SetString(PyExc_RuntimeError, " - "\"lookup attempted on invalid " << tagS << - " element\");\n" - " return NULL;\n" - " }\n" - " me->elem->clear();\n" - " Py_INCREF(Py_None);\n" - " return Py_None;\n" - "}\n\n" - ; - method_descr meth_clrS = {"clear", "METH_NOARGS", - "clear all contents from this " + tagS}; - methods[clrS] = meth_clrS; - } - - XtString strS("_" + tagS.simpleType() + "_toString"); - pyFile << "static PyObject*\n" << strS << - "(PyObject *self, PyObject *args=0)\n" - "{\n" - " _" << tagS.simpleType() << - " *me = (_" << tagS.simpleType() << "*)self;\n" - " if (me->elem == 0) {\n" - " PyErr_SetString(PyExc_RuntimeError, " - "\"lookup attempted on invalid " << tagS << - " element\");\n" - " return NULL;\n" - " }\n" - " std::string str(me->elem->toString());\n" - " return PyUnicode_FromString(str.c_str());\n" - "}\n\n" - ; - method_descr str_method = {"toString", "METH_NOARGS", - "show element as a human-readable string"}; - methods[strS] = str_method; - - XtString xmlS("_" + tagS.simpleType() + "_toXML"); - pyFile << "static PyObject*\n" << xmlS << - "(PyObject *self, PyObject *args=0)\n" - "{\n" - " _" << tagS.simpleType() << - " *me = (_" << tagS.simpleType() << "*)self;\n" - " if (me->elem == 0) {\n" - " PyErr_SetString(PyExc_RuntimeError, " - "\"lookup attempted on invalid " << tagS << - " element\");\n" - " return NULL;\n" - " }\n" - " std::string str(me->elem->toXML());\n" - " return PyUnicode_FromString(str.c_str());\n" - "}\n\n" - ; - method_descr xml_method = {"toXML", "METH_NOARGS", - "show element as a XML fragment"}; - methods[xmlS] = xml_method; - - pyFile << "static PyGetSetDef _" << tagS.simpleType() - << "_getsetters[] = {\n"; - std::map::iterator aiter; - for (aiter = attrList.begin(); aiter != attrList.end(); ++aiter) { - XtString attrS = aiter->first; - XtString getterS("_" + tagS.simpleType() + "_" + "get" + attrS.simpleType()); - XtString setterS("_" + tagS.simpleType() + "_" + "set" + attrS.simpleType()); - pyFile << " {(char*)\"" << attrS << "\",\n" - << " (getter)" << getterS << ", "; - if (setters.find(attrS) != setters.end()) { - pyFile << "(setter)" << setterS << ",\n"; - } - else { - pyFile << "0,\n"; - } - if (aiter->second == "string") { - pyFile << " (char*)\"" << attrS << " string\",\n"; - } - else { - pyFile << " (char*)\"" << attrS << " value\",\n"; - } - pyFile << " NULL},\n"; - } - pyFile << " {NULL} /* Sentinel */\n" - "};\n\n"; - - pyFile << "static PyMemberDef _" << tagS.simpleType() - << "_members[] = {\n" - << " {NULL} /* Sentinel */\n" - << "};\n\n"; - - pyFile << "static PyMethodDef _" << tagS.simpleType() - << "_methods[] = {\n"; - std::map::iterator miter; - for (miter = methods.begin(); miter != methods.end(); ++miter) { - pyFile << " {\"" << miter->second.name << "\", " - << miter->first << ", " << miter->second.args << ",\n" - << " \"" << miter->second.docs << "\"},\n"; - } - - // add special methods for read/write to hdf5 files - if (tagS == "HDDM") - { - pyFile << - "#ifdef HDF5_SUPPORT\n" - " {\"hdf5FileWrite\", _HDDM_hdf5FileWrite, METH_VARARGS,\n" - " \"random-access write this hddm record to an output hdf5 file\"},\n" - " {\"hdf5FileRead\", _HDDM_hdf5FileRead, METH_VARARGS,\n" - " \"random-access read this hddm record from an input hdf5 file\"},\n" - "#endif\n"; - } - pyFile << - " {NULL} /* Sentinel */\n" - "};\n\n"; - - typesList[tagS] = "_" + tagS.simpleType() + "_type"; - - pyFile << - "static PyTypeObject _" << tagS.simpleType() << "_type = {\n" - " PyVarObject_HEAD_INIT(NULL,0)\n" - " \"hddm_" << classPrefix << "." << tagS.simpleType() << "\"," - " /*tp_name*/\n" - " sizeof(_" << tagS.simpleType() << - "), /*tp_basicsize*/\n" - " 0, /*tp_itemsize*/\n" - " (destructor)_" << tagS.simpleType() << - "_dealloc, /*tp_dealloc*/\n" - " 0, /*tp_print*/\n" - " 0, /*tp_getattr*/\n" - " 0, /*tp_setattr*/\n" - " 0, /*tp_compare*/\n" - " 0, /*tp_repr*/\n" - " 0, /*tp_as_number*/\n" - " 0, /*tp_as_sequence*/\n" - " 0, /*tp_as_mapping*/\n" - " 0, /*tp_hash */\n" - " 0, /*tp_call*/\n" - " (reprfunc)_" << tagS.simpleType() << "_toString, /*tp_str*/\n" - " 0, /*tp_getattro*/\n" - " 0, /*tp_setattro*/\n" - " 0, /*tp_as_buffer*/\n" - " Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/\n" - " \"hddm_" << classPrefix << " " << tagS << - " element\", /* tp_doc */\n" - " 0, /* tp_traverse */\n" - " 0, /* tp_clear */\n" - " 0, /* tp_richcompare */\n" - " 0, /* tp_weaklistoffset */\n" - " 0, /* tp_iter */\n" - " 0, /* tp_iternext */\n" - " _" << tagS.simpleType() << "_methods, /* tp_methods */\n" - " _" << tagS.simpleType() << "_members, /* tp_members */\n" - " _" << tagS.simpleType() << "_getsetters, /* tp_getset */\n" - " &_HDDM_Element_type, /* tp_base */\n" - " 0, /* tp_dict */\n" - " 0, /* tp_descr_get */\n" - " 0, /* tp_descr_set */\n" - " 0, /* tp_dictoffset */\n" - " (initproc)_" << tagS.simpleType() << "_init, /* tp_init */\n" - " 0, /* tp_alloc */\n" - " _" << tagS.simpleType() << "_new, /* tp_new */\n" - "};\n\n" - ; -} - -/* Generate class declarations for this tag and its descendants; - * this function calls itself recursively - */ - -void CodeBuilder::constructGroup(DOMElement* el) -{ - XtString tagS(el->getTagName()); - parentList_t::iterator piter; - parents[tagS].insert(parents[tagS].begin(), - parentList.begin(),parentList.end()); - std::vector::iterator iter; - for (iter = tagList.begin(); iter != tagList.end(); iter++) - { - DOMElement* targEl = *iter; - XtString targS(targEl->getTagName()); - if (tagS == targS) - { - checkConsistency(el,targEl); - return; - } - } - - parentList.push_back(el); - DOMNodeList* contList = el->getChildNodes(); - int contLength = contList->getLength(); - for (int c = 0; c < contLength; c++) - { - DOMNode* cont = contList->item(c); - short type = cont->getNodeType(); - if (type == DOMNode::ELEMENT_NODE) - { - DOMElement* contEl = (DOMElement*) cont; - XtString contS(contEl->getTagName()); - children[tagS].push_back(contEl); - constructGroup(contEl); - } - } - parentList.pop_back(); - - tagList.push_back(el); - - if (tagS == "HDDM") - { - std::vector::iterator iter; - for (iter = tagList.begin(); iter != tagList.end(); iter++) - { - writeClassdef(*iter); - } - } -} - -/* Write method implementation of the classes for this tag */ - -void CodeBuilder::writeClassimp(DOMElement* el) -{ -} - -/* Generate implementation code for data model classes */ - -void CodeBuilder::constructMethods(DOMElement* el) -{ - std::vector::iterator iter; - for (iter = tagList.begin(); iter != tagList.end(); iter++) - { - writeClassimp(*iter); - } -} - -/* Generate methods for serializing classes to a stream and back again */ - -void CodeBuilder::writeStreamers(DOMElement* el) -{ -} - -void CodeBuilder::constructStreamers(DOMElement* el) -{ - std::vector::iterator iter; - for (iter = tagList.begin(); iter != tagList.end(); ++iter) - { - writeStreamers(*iter); - } -} - -/* Generate methods to read from binary stream into classes */ - -void CodeBuilder::constructIOstreams(DOMElement* el) -{ -} - -/* Generate the xml template in normal form and store in a string */ - -void CodeBuilder::constructDocument(DOMElement* el) -{ - static int indent = 0; - pyFile << "\""; - for (int n = 0; n < indent; n++) - { - pyFile << " "; - } - - XtString tagS(el->getTagName()); - pyFile << "<" << tagS; - DOMNamedNodeMap* attrList = el->getAttributes(); - int attrListLength = attrList->getLength(); - for (int a = 0; a < attrListLength; a++) - { - DOMNode* node = attrList->item(a); - XtString nameS(node->getNodeName()); - XtString valueS(node->getNodeValue()); - pyFile << " " << nameS << "=\\\"" << valueS << "\\\""; - } - - DOMNodeList* contList = el->getChildNodes(); - int contListLength = contList->getLength(); - if (contListLength > 0) - { - pyFile << ">\\n\"" << std::endl; - indent++; - for (int c = 0; c < contListLength; c++) - { - DOMNode* node = contList->item(c); - if (node->getNodeType() == DOMNode::ELEMENT_NODE) - { - DOMElement* contEl = (DOMElement*) node; - constructDocument(contEl); - } - } - indent--; - pyFile << "\""; - for (int n = 0; n < indent; n++) - { - pyFile << " "; - } - pyFile << "\\n\"" << std::endl; - } - else - { - pyFile << " />\\n\"" << std::endl; - } -} - -std::string guessType(const std::string &literal) -{ - const char *str = literal.c_str(); - char *endptr; - errno=0; - long long int llvalue = strtoll(str,&endptr,0); - if (errno == 0 && *endptr == 0) { - errno=0; - int lvalue = strtol(str,&endptr,0); - if (errno == 0 && *endptr == 0 && lvalue == llvalue) { - return "int"; - } - else { - return "long"; - } - } - errno=0; - strtof(str,&endptr); - if (errno == 0 && *endptr == 0) { - return "float"; - } - errno=0; - strtod(str,&endptr); - if (errno == 0 && *endptr == 0) { - return "double"; - } - if (literal == "true" || literal == "false") { - return "boolean"; - } - if ((int)lookupParticle(literal) != 0) { - return "Particle_t"; - } - if (XMLUri::isValidURI(false,X(literal))) { - return "anyURI"; - } - return "string"; -} - -Particle_t lookupParticle(const std::string &name) -{ - for (int p=0; p<100; ++p) { - if (ParticleType((Particle_t)p) == name) { - return (Particle_t)p; - } - } - return Unknown; -} diff --git a/src/programs/Utilities/hddm/hddm-root.cpp b/src/programs/Utilities/hddm/hddm-root.cpp deleted file mode 100644 index aebf3589ca..0000000000 --- a/src/programs/Utilities/hddm/hddm-root.cpp +++ /dev/null @@ -1,1082 +0,0 @@ -/* - * hddm-root : tool that reads in a HDDM document (Hall D Data Model) - * and copies the contents into root trees for easy browsing. - * - * author: richard.t.jones at uconn.edu - * version: january 2, 2017 - * - * Version 1.1 - Richard Jones, February 10, 2021. - * - Modified to be able to read a hddm template (xml data model) as - * a valid hddm file with 0 records. This simplifies the documentation - * by eliminating the false distinction between the hddm template and - * the text header that appears at the top of every hddm file. It also - * gets rid of the unnecessary step of needing to remove binary data - * following the header in a hddm file before it can be used as a - * template in other utilities. - */ - -#include -#include - -#include "VersionConfig.hpp" -#include "XParsers.hpp" -#include "XString.hpp" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -#include -#include - -#include "particleType.h" - - -#define X(str) XString(str).unicode_str() -#define S(str) str.c_str() - -using namespace xercesc; - -int explicit_repeat_count = 1; -int write_xml_output_to_stdout = 0; - -void usage() -{ - std::cerr - << "\nUsage:\n" - << " hddm-root [-x] [-n ] [-o ] [HDDM file]\n\n" - << "Options:\n" - << " -o write to output root file \n" - << " -n limit output to rows\n" - << " -x write xml to stdout" - << " (in addition to root file output)\n" - << "Version: " << HDDM_VERSION_MAJOR << "." << HDDM_VERSION_MINOR - << std::endl; -} - -typedef xstream::xdr::istream ixstream; - -class attribute_t { - protected: - attribute_t() : fName(""), fType("") {} - attribute_t(XString name) : fName(name), fType("") {} - attribute_t(XString name, XString type) : fName(name), fType(type) {} - virtual ~attribute_t() {} - - public: - virtual void reset() = 0; - virtual void *address() = 0; - virtual std::string toString() = 0; - virtual int read(ixstream *ifx) = 0; - virtual XString get_name() { return fName; } - virtual XString get_type() { return fType; } - - private: - attribute_t(const attribute_t &src); - attribute_t &operator=(const attribute_t &src); - - protected: - XString fName; - XString fType; -}; - -class int_attribute_t : public attribute_t { - public: - int_attribute_t() : attribute_t("", "int"), value(0) {} - int_attribute_t(XString name) : attribute_t(name, "int"), value(0) {} - virtual ~int_attribute_t() {} - - int_attribute_t &operator=(const int_attribute_t &src) { - fName = src.fName; - value = src.value; - return *this; - } - - virtual void reset() { - value = 0; - } - virtual void set(int val) { - value = val; - } - virtual void *address() { - return &value; - } - virtual std::string toString() { - std::stringstream str; - str << value; - return str.str(); - } - virtual int read(ixstream *ifx) { - *ifx >> value; - return 4; - } - - int value; -}; - -class boolean_attribute_t : public attribute_t { - public: - boolean_attribute_t() : attribute_t("", "boolean"), value(0) {} - boolean_attribute_t(XString name) : attribute_t(name, "boolean"), value(0) {} - virtual ~boolean_attribute_t() {} - - boolean_attribute_t &operator=(const boolean_attribute_t &src) { - fName = src.fName; - value = src.value; - return *this; - } - - virtual void reset() { - value = 0; - } - virtual void set(int val) { - value = val; - } - virtual void *address() { - return &value; - } - virtual std::string toString() { - std::stringstream str; - str << value; - return str.str(); - } - virtual int read(ixstream *ifx) { - *ifx >> value; - return 4; - } - - int value; -}; - -class Particle_attribute_t : public attribute_t { - public: - Particle_attribute_t() : attribute_t("", "Particle_t"), value(Unknown) {} - Particle_attribute_t(XString name) : attribute_t(name, "Particle_t"), - value(Unknown) {} - virtual ~Particle_attribute_t() {} - - Particle_attribute_t &operator=(const Particle_attribute_t &src) { - fName = src.fName; - value = src.value; - return *this; - } - - virtual void reset() { - value = Unknown; - } - virtual void set(Particle_t val) { - value = val; - } - virtual void *address() { - return &value; - } - virtual std::string toString() { - std::stringstream str; - str << ParticleType(value); - return str.str(); - } - virtual int read(ixstream *ifx) { - int val; - *ifx >> val; - value = (Particle_t)val; - return 4; - } - - Particle_t value; -}; - -class long_attribute_t : public attribute_t { - public: - long_attribute_t() : attribute_t("", "long"), value(0) {} - long_attribute_t(XString name) : attribute_t(name, "long"), value(0) {} - virtual ~long_attribute_t() {} - - long_attribute_t &operator=(const long_attribute_t &src) { - fName = src.fName; - value = src.value; - return *this; - } - - virtual void reset() { - value = 0; - } - virtual void set(long int val) { - value = val; - } - virtual void *address() { - return &value; - } - virtual std::string toString() { - std::stringstream str; - str << value; - return str.str(); - } - virtual int read(ixstream *ifx) { - *ifx >> value; - return 8; - } - -#if __APPLE__ - int64_t value; -#else - long int value; -#endif -}; - -class float_attribute_t : public attribute_t { - public: - float_attribute_t() : attribute_t("", "float"), value(0) {} - float_attribute_t(XString name) : attribute_t(name, "float"), value(0) {} - virtual ~float_attribute_t() {} - - float_attribute_t &operator=(const float_attribute_t &src) { - fName = src.fName; - value = src.value; - return *this; - } - - virtual void reset() { - value = 0; - } - virtual void set(float val) { - value = val; - } - virtual void *address() { - return &value; - } - virtual std::string toString() { - std::stringstream str; - str << value; - return str.str(); - } - virtual int read(ixstream *ifx) { - *ifx >> value; - return 4; - } - - float value; -}; - -class double_attribute_t : public attribute_t { - public: - double_attribute_t() : attribute_t("", "double"), value(0) {} - double_attribute_t(XString name) : attribute_t(name, "double"), value(0) {} - ~double_attribute_t() {} - - double_attribute_t &operator=(const double_attribute_t &src) { - fName = src.fName; - value = src.value; - return *this; - } - - virtual void reset() { - value = 0; - } - virtual void set(double val) { - value = val; - } - virtual void *address() { - return &value; - } - virtual std::string toString() { - std::stringstream str; - str << value; - return str.str(); - } - virtual int read(ixstream *ifx) { - *ifx >> value; - return 8; - } - - double value; -}; - -class string_attribute_t : public attribute_t { - public: - string_attribute_t() : attribute_t("", "string") { reset(); } - string_attribute_t(XString name) : attribute_t(name, "string") { reset(); } - ~string_attribute_t() {} - - string_attribute_t &operator=(const string_attribute_t &src) { - fName = src.fName; - strncpy(value, src.value, 80); - return *this; - } - - virtual void reset() { - strncpy(value, "", 80); - } - virtual void set(char *val) { - strncpy(value, val, 80); - } - virtual void *address() { - return &value; - } - virtual std::string toString() { - return std::string(value); - } - virtual int read(ixstream *ifx) { - std::string val; - *ifx >> val; - strncpy(value, val.c_str(), 80); - return (val.size() + 7) / 4 * 4; - } - - char value[80]; -}; - -class anyURI_attribute_t : public attribute_t { - public: - anyURI_attribute_t() : attribute_t("", "anyURI") { reset(); } - anyURI_attribute_t(XString name) : attribute_t(name, "anyURI") { reset(); } - ~anyURI_attribute_t() {} - - anyURI_attribute_t &operator=(const anyURI_attribute_t &src) { - fName = src.fName; - strncpy(value, src.value, 80); - return *this; - } - - virtual void reset() { - strncpy(value, "", 80); - } - virtual void set(char *val) { - strncpy(value, val, 80); - } - virtual void *address() { - return &value; - } - virtual std::string toString() { - return std::string(value); - } - virtual int read(ixstream *ifx) { - std::string val; - *ifx >> val; - strncpy(value, val.c_str(), 80); - return (val.size() + 7) / 4 * 4; - } - - char value[80]; -}; - -class constant_attribute_t : public attribute_t { - public: - constant_attribute_t() : attribute_t("", "constant"), value(0) - { reset(); } - constant_attribute_t(XString name) : attribute_t(name, "constant"), value(0) - { reset(); } - ~constant_attribute_t() {} - - void reset() { - if (value) - delete value; - value = new char[4]; - strncpy(value, "", 4); - } - void set(const char *str) { - if (value) - delete value; - if (!str) - return; - int size = (strlen(str) + 7) / 4 * 4; - value = new char[size]; - strncpy(value, str, size); - } - - constant_attribute_t &operator=(const constant_attribute_t &src) { - fName = src.fName; - set(src.value); - return *this; - } - - virtual void *address() { - return value; - } - virtual std::string toString() { - return std::string(value); - } - virtual int read(ixstream *ifx) { - return 0; - } - - char *value; -}; - -class element_t { - public: - element_t(TTree *tree) - : fKey(0), fTree(tree), fRepeats(0) {} - element_t(TTree *tree, XString name) - : fKey(0), fTree(tree), fName(name), fRepeats(0) {} - ~element_t() {} - - void add_attribute(attribute_t *attr) { - fAttributes.push_back(attr); - } - void add_element(element_t *elem) { - fElements.push_back(elem); - } - void add_key(int_attribute_t *attr) { - fKey = attr; - } - void set_repeating() { - fRepeats = 1; - } - - int read(ixstream *ifx) { - int size; - *ifx >> size; - if (size == 0) - return 4; - int seen; - int reps=1; - if (fRepeats) { - *ifx >> reps; - seen = 4; - } - else { - seen = 0; - } - - static int indent = 0; - if (write_xml_output_to_stdout) { - if (indent == 0) { - std::cout << "" - << std::endl - << "" - << std::endl; - ++indent; - } - } - while (seen < size) { - if (write_xml_output_to_stdout) { - for (int i=0; i < indent; ++i) - std::cout << " "; - std::cout << "<" << fName; - } - std::list::iterator ater; - for (ater = fAttributes.begin(); ater != fAttributes.end(); ++ater) { - seen += (*ater)->read(ifx); - if (write_xml_output_to_stdout) { - std::cout << " " << (*ater)->get_name() << "=\"" - << (*ater)->toString() << "\""; - } - } - if (fElements.size() == 0) { - if (write_xml_output_to_stdout) { - std::cout << " />" << std::endl; - } - if (fTree) - fTree->Fill(); - if (fKey) - ++fKey->value; - } - else { - if (write_xml_output_to_stdout) { - std::cout << ">" << std::endl; - ++indent; - } - std::list::iterator eter; - for (eter = fElements.begin(); eter != fElements.end(); ++eter) { - seen += (*eter)->read(ifx); - } - if (write_xml_output_to_stdout) { - --indent; - for (int i=0; i < indent; ++i) { - std::cout << " "; - } - std::cout << "" << std::endl; - } - if (fTree) - fTree->Fill(); - } - --reps; - } - assert (seen == size); - if (fRepeats) - assert (reps == 0); - return size + 4; - } - - std::list fAttributes; - std::list fElements; - int_attribute_t *fKey; - TTree *fTree; - XString fName; - int fRepeats; - - private: - element_t(const element_t &src); - element_t &operator=(const element_t &src); -}; - -typedef std::map attribute_list; -typedef std::map attribute_table; - -class TreeMaker -{ - public: - TreeMaker(XString filename) { - fRootFile = new TFile(S(filename), "recreate"); - } - ~TreeMaker() { - delete fRootFile; - } - - void build(const DOMElement* elem, element_t *parent_element, - attribute_list columns); - int filltrees(ixstream *ifx, element_t *parent_element); - int savetrees(element_t *parent_element); - - private: - TreeMaker(const TreeMaker &src) {} - TreeMaker operator=(const TreeMaker &src) { - TreeMaker copy(*this); - return copy; - } - - protected: - TFile *fRootFile; - std::list fElements; - attribute_table fColumns; -}; - -class istreambuffer : public std::streambuf { - public: - istreambuffer(char* buffer, std::streamsize bufferLength) { - setg(buffer, buffer, buffer + bufferLength); - } - - std::streampos tellg() { - return gptr() - eback(); - } - - void seekg(std::streampos pos) { - reset(); - gbump(pos); - } - - int size() { - return egptr() - gptr(); - } - - void reset() { - char *gbegin = eback(); - char *gend = egptr(); - setg(gbegin, gbegin, gend); - } - - char *getbuf() { - return eback(); - } -}; - -int main(int argC, char* argV[]) -{ - XString rootFilename("hddm-root.root"); - - try - { - XMLPlatformUtils::Initialize(); - } - catch (const XMLException* toCatch) - { - XString msg(toCatch->getMessage()); - std::cerr - << "hddm-root: Error during initialization! :\n" - << S(msg) << std::endl; - return 1; - } - - int reqcount=-1; - int argInd; - for (argInd = 1; argInd < argC; argInd++) - { - if (argV[argInd][0] != '-') - { - break; - } - else if (strcmp(argV[argInd],"-x") == 0) - { - write_xml_output_to_stdout = 1; - } - else if (strcmp(argV[argInd],"-o") == 0) - { - rootFilename = argV[++argInd]; - } - else if (strcmp(argV[argInd],"-n") == 0) - { - if (!sscanf(argV[++argInd],"%d",&reqcount)) - { - usage(); - return 1; - } - } - else - { - usage(); - return 1; - } - } - - XString hddmFile; - std::istream* ifs; - if (argInd == argC) - { - ifs = &std::cin; - } - else if (argInd == argC - 1) - { - hddmFile = XString(argV[argInd]); - ifs = new std::ifstream(hddmFile.c_str()); - } - else - { - usage(); - return 1; - } - if (!ifs->good()) - { - std::cerr - << "hddm-root: Error opening input stream " << hddmFile << std::endl; - exit(1); - } - std::ostringstream doc; - std::ostringstream tmpFileStr; - tmpFileStr << "tmp" << getpid(); - std::ofstream ofs(tmpFileStr.str().c_str()); - if (! ofs.is_open()) - { - std::cerr - << "hddm-root: Error opening temp file " << tmpFileStr.str() << std::endl; - exit(2); - } - - XString xmlPreamble("\n"); - doc << std::endl; - XString xmlHeader; - XString line; - if (getline(*ifs,line)) - { - if (line.find("") != line.npos) - { - xmlPreamble += line + "\n"; - } - else if (line.size() == 0) - { - xmlPreamble += "\n"; - } - else if (line.find("") - { - break; - } - } - ofs.close(); - -#if defined OLD_STYLE_XERCES_PARSER - DOMDocument* document = parseInputDocument(tmpFileStr.str().c_str(),false); -#else - DOMDocument* document = buildDOMDocument(tmpFileStr.str().c_str(),false); -#endif - if (document == 0) - { - std::cerr - << "hddm-root : Error parsing HDDM document, " - << "cannot continue" << std::endl; - return 1; - } - unlink(tmpFileStr.str().c_str()); - - DOMElement* rootEl = document->getDocumentElement(); - XString rootS(rootEl->getTagName()); - if (rootS != "HDDM") - { - std::cerr - << "hddm-root error: root element of input document is " - << "\"" << S(rootS) << "\", expected \"HDDM\"" - << std::endl; - return 1; - } - - // open root file for output and initialize the trees for writing - TreeMaker builder(rootFilename); - attribute_list columns; - element_t root_element(0); - builder.build(rootEl, &root_element, columns); - - int event_buffer_size; - char *event_buffer = new char[event_buffer_size = 1000000]; - istreambuffer *isbuf = new istreambuffer(event_buffer,event_buffer_size); - ixstream *ifx = new ixstream(isbuf); - int integrity_check_mode = 0; - int compression_mode = 0; - while (reqcount && ifs->good()) - { - int tsize; - ifs->read(event_buffer,4); - if (ifs->eof()) { - break; - } - isbuf->reset(); - *ifx >> tsize; -#ifdef VERBOSE_HDDM_LOGGING - XString tnameS(rootEl->getTagName()); - std::cerr << "hddm-root : tag " << S(tnameS) - << " found with size " << tsize - << std::endl; -#endif - if (tsize <= 0) - { - break; - } - else if (tsize == 1) { - int size, format, flags; - ifs->read(event_buffer+4,4); - *ifx >> size; - ifs->read(event_buffer+8,size); - *ifx >> format >> flags; - int compression_flags = flags & 0xf0; - int integrity_flags = flags & 0x0f; - std::streambuf *fin_sb = 0; - xstream::z::istreambuf *zin_sb = 0; - xstream::bz::istreambuf *bzin_sb = 0; - int *leftovers = new int[100]; - int sizeof_leftovers = sizeof(int[100]); - leftovers[0] = 0; - if (compression_flags == compression_mode) { - fin_sb = ifs->rdbuf(); - } - else if (size == 8 && format == 0 && compression_flags == 0x10) { - if (compression_mode == 0x20) { - bzin_sb = (xstream::bz::istreambuf*)ifs->rdbuf(); - } - compression_mode = compression_flags; - zin_sb = new xstream::z::istreambuf(ifs->rdbuf(), - leftovers, sizeof_leftovers); - ifs->rdbuf(zin_sb); - if (bzin_sb != 0) - delete bzin_sb; - } - else if (size == 8 && format == 0 && compression_flags == 0x20) { - if (compression_mode == 0x10) { - zin_sb = (xstream::z::istreambuf*)ifs->rdbuf(); - } - compression_mode = compression_flags; - bzin_sb = new xstream::bz::istreambuf(ifs->rdbuf(), - leftovers, sizeof_leftovers); - ifs->rdbuf(bzin_sb); - if (zin_sb != 0) - delete zin_sb; - } - else { - if (compression_mode == 0x20) { - bzin_sb = (xstream::bz::istreambuf*)ifs->rdbuf(); - fin_sb = bzin_sb->get_streambuf(); - } - else if (compression_mode == 0x10) { - zin_sb = (xstream::z::istreambuf*)ifs->rdbuf(); - fin_sb = zin_sb->get_streambuf(); - } - compression_mode = compression_flags; - ifs->rdbuf(fin_sb); - if (zin_sb != 0) - delete zin_sb; - if (bzin_sb != 0) - delete bzin_sb; - } - if (size == 8 && format == 0 && integrity_flags == 0x0) { - integrity_check_mode = 0; - } - else if (size == 8 && format == 0 && integrity_flags == 0x1) { - integrity_check_mode = 1; - } - else { - std::cerr << "hddm-root error: unrecognized stream modifier" - " encountered, this stream is no longer readable." - << std::endl; - break; - } - continue; - } - else if (tsize+4 > event_buffer_size) { - delete ifx; - delete isbuf; - char *new_buffer = new char[event_buffer_size = tsize+1000]; - isbuf = new istreambuffer(new_buffer,event_buffer_size); - ifx = new ixstream(isbuf); - memcpy(new_buffer,event_buffer,4); - *ifx >> tsize; - delete[] event_buffer; - event_buffer = new_buffer; - } - ifs->read(event_buffer+4,tsize); - --reqcount; - - if (integrity_check_mode == 1) { - char crcbuf[10]; - istreambuffer sbuf(crcbuf,10); - ixstream xstr(&sbuf); - unsigned int recorded_crc; - ifs->read(crcbuf,4); - xstr >> recorded_crc; - xstream::digest::crc32 crc; - std::ostream out(&crc); - out.write(event_buffer,tsize+4); - out.flush(); - if (crc.digest() != recorded_crc) { -#if BAD_CRC_IS_ONLY_WARNING - static int bad_crc_warning_needed = true; - char errmsg[] = - "WARNING: data integrity crc check failed on input.\n"; - if (bad_crc_warning_needed) { - std::cerr << errmsg << std::endl; - bad_crc_warning_needed = false; - } -#else - std::cerr << "hddm-root error: crc32 check error on input stream" - " encountered, this stream is no longer readable." - << std::endl; - break; -#endif - } - } - builder.filltrees(ifx, &root_element); - } - if (write_xml_output_to_stdout) { - std::cout << "" << std::endl; - } - builder.savetrees(&root_element); - TNamed docString("document_metadata_XML", doc.str().c_str()); - docString.Write(); - - if (ifs != &std::cin) - { - ((std::ifstream*)ifs)->close(); - } - - XMLPlatformUtils::Terminate(); - return 0; -} - -void TreeMaker::build(const DOMElement* elem, element_t *parent_element, - attribute_list columns) -{ - // Recursively create TTree objects to hold the contents of the hddm model - // in the form of a row/column table, like a relational database model. - - XString elemS(elem->getTagName()); - std::list::iterator eter; - for (eter = fElements.begin(); eter != fElements.end(); ++eter) { - if (elemS == (*eter)->fName) { - elemS = parent_element->fName + "_" + elemS; - } - } - TTree *tree = new TTree(S(elemS), S(XString(elemS + " tree"))); - element_t *this_element = new element_t(tree, elemS); - fElements.push_back(this_element); - - XString repS(elem->getAttribute(X("maxOccurs"))); - int rep = (repS == "unbounded")? INT_MAX : - (repS == "")? 1 : - atoi(S(repS)); - if (explicit_repeat_count && rep > 1) - this_element->set_repeating(); - - // Create a new column called "key" to hold synchronization - // information between rows in different trees, similar to - // the way keys are used in relational databases (eg. JOIN). - - XString keyS("HDDM_MASTER_ORDERING_KEY"); - if (fColumns.find(keyS) == fColumns.end()) { - int_attribute_t *key = new int_attribute_t("key"); - fColumns[keyS] = key; - } - tree->Branch("key", fColumns[keyS]->address(), "key/I"); - this_element->add_key((int_attribute_t*)fColumns[keyS]); - - // Add branches for attributes inherited from parent elements - - attribute_list::iterator iter; - for (iter = columns.begin(); iter != columns.end(); ++iter) { - XString colS = iter->first; - XString nameS = iter->second; - XString typeS = fColumns[colS]->get_type(); - if (typeS == "int" || typeS == "boolean" || typeS == "Particle_t") - tree->Branch(S(nameS), fColumns[colS]->address(), - S(XString(nameS + "/I"))); - else if (typeS == "long") - tree->Branch(S(nameS), fColumns[colS]->address(), - S(XString(nameS + "/L"))); - else if (typeS == "float") - tree->Branch(S(nameS), fColumns[colS]->address(), - S(XString(nameS + "/F"))); - else if (typeS == "double") - tree->Branch(S(nameS), fColumns[colS]->address(), - S(XString(nameS + "/D"))); - else if (typeS == "string" || typeS == "anyURI") - tree->Branch(S(nameS), fColumns[colS]->address(), - S(XString(nameS + "/C"))); - else { - tree->Branch(S(nameS), fColumns[colS]->address(), - S(XString(nameS + "/C"))); - } - } - - // Add branches for the element's own attributes - - DOMNamedNodeMap* attrList = elem->getAttributes(); - int attrListLength = attrList->getLength(); - for (int a = 0; a < attrListLength; a++) { - DOMNode* node = attrList->item(a); - XString nameS(node->getNodeName()); - XString typeS(node->getNodeValue()); - XString colS(elemS + "_" + nameS); - if (columns.find(nameS) != columns.end()) - nameS = colS; - if (typeS == "int") { - fColumns[colS] = new int_attribute_t(nameS); - tree->Branch(S(nameS), fColumns[colS]->address(), - S(XString(nameS + "/I"))); - } - else if (typeS == "boolean") { - fColumns[colS] = new boolean_attribute_t(nameS); - tree->Branch(S(nameS), fColumns[colS]->address(), - S(XString(nameS + "/I"))); - } - else if (typeS == "Particle_t") { - fColumns[colS] = new Particle_attribute_t(nameS); - tree->Branch(S(nameS), fColumns[colS]->address(), - S(XString(nameS + "/I"))); - } - else if (typeS == "long") { - fColumns[colS] = new long_attribute_t(nameS); - tree->Branch(S(nameS), fColumns[colS]->address(), - S(XString(nameS + "/L"))); - } - else if (typeS == "float") { - fColumns[colS] = new float_attribute_t(nameS); - tree->Branch(S(nameS), fColumns[colS]->address(), - S(XString(nameS + "/F"))); - } - else if (typeS == "double") { - fColumns[colS] = new double_attribute_t(nameS); - tree->Branch(S(nameS), fColumns[colS]->address(), - S(XString(nameS + "/D"))); - } - else if (typeS == "string") { - fColumns[colS] = new string_attribute_t(nameS); - tree->Branch(S(nameS), fColumns[colS]->address(), - S(XString(nameS + "/C"))); - } - else if (typeS == "anyURI") { - fColumns[colS] = new anyURI_attribute_t(nameS); - tree->Branch(S(nameS), fColumns[colS]->address(), - S(XString(nameS + "/C"))); - } - else if (nameS == "minOccurs" || nameS == "maxOccurs") { - continue; - } - else { - fColumns[colS] = new constant_attribute_t(nameS); - tree->Branch(S(nameS), fColumns[colS]->address(), - S(XString(nameS + "/C"))); - ((constant_attribute_t*)fColumns[colS])->set(S(typeS)); - } - columns[colS] = nameS; - this_element->add_attribute(fColumns[colS]); - } - - parent_element->add_element(this_element); - - // Recursively build any elements contained within this one - - DOMNodeList* contList = elem->getChildNodes(); - int contLength = contList->getLength(); - for (int c = 0; c < contLength; c++) { - DOMNode* cont = contList->item(c); - short type = cont->getNodeType(); - if (type == DOMNode::ELEMENT_NODE) { - DOMElement* contEl = (DOMElement*) cont; - build(contEl, this_element, columns); - } - } -} - -int TreeMaker::filltrees(ixstream *ifx, element_t *parent_element) -{ - element_t *HDDMelement = *parent_element->fElements.begin(); - std::list::iterator iter; - int size = 0; - for (iter = HDDMelement->fElements.begin(); - iter != HDDMelement->fElements.end(); - ++iter) - { - size += (*iter)->read(ifx); -#ifdef VERBOSE_HDDM_LOGGING - XString cnameS((*iter)->fName); - std::cerr << "hddm-root : top-level tag " << S(cnameS) - << " found with size " << size - << std::endl; -#endif - } - return size; -} - -int TreeMaker::savetrees(element_t *parent_element) -{ - int count = 0; - std::list::iterator iter; - for (iter = parent_element->fElements.begin(); - iter != parent_element->fElements.end(); - ++iter) - { - if ((*iter)->fTree) { - (*iter)->fTree->Write(); - ++count; - } - count += savetrees(*iter); - } - return count; -} diff --git a/src/programs/Utilities/hddm/hddm-schema b/src/programs/Utilities/hddm/hddm-schema deleted file mode 100755 index 9833b22c52..0000000000 --- a/src/programs/Utilities/hddm/hddm-schema +++ /dev/null @@ -1,97 +0,0 @@ -#!/usr/bin/env perl -# -# hddm-schema: create a xml schema based on a hddm template -# -# Both templates and schemas are themselves well-formed xml documents, -# so the transformation can be done automatically using XSLT tools. -# This implementation uses Xalan from xml.apache.org to carry out the -# transformation. The output from the transform is then validated by -# the XercesDOMParser before printing it on standard output. -# -# Richard T. Jones -# September 15, 2003 -# ------------------ - -use XML::Xerces; - -sub Usage() -{ - print <$tmpxml") == 0) { - die "Unable to open temp file $tmpxml\n"; -} -while ($line = ) { - if ($line =~ s/<\/HDDM>.*$/<\/HDDM>/) { - print TMP $line; - last; - } - print TMP $line; -} -close(HDDM); -close(TMP); - -# generate the basic schema using XSL transform: -# -# two translators: xalan-j (java) or xalan-c (c++) -# chose one of the two following, comment the other -#$cmd = "$ENV{XALANCROOT}/bin/Xalan -o $tmpxsd $tmpxml hddm-schema.xsl"; -$cmd = "$ENV{JAVAROOT}/bin/java org.apache.xalan.xslt.Process" . - " -IN $tmpxml -OUT $tmpxsd -XSL hddm-schema.xsl -L"; - -if (system($cmd)) { - if (! -x "$ENV{JAVAROOT}/bin/java") { - die "Please check that $JAVAROOT/bin/java exists and try again.\n"; - } - else { - print "command was:$cmd\n"; - die "hddm-schema: errors returned by Xalan, quitting\n"; - } -} - -# check the result for correctness and pretty-print it - -$parser = XML::Xerces::XercesDOMParser->new(); -$parser->setValidationScheme (0); -$parser->setDoNamespaces (1); -$parser->setCreateEntityReferenceNodes(1); -$parser->setDoSchema (1); - -$ERROR_HANDLER = XML::Xerces::PerlErrorHandler->new(); -$parser->setErrorHandler($ERROR_HANDLER); -eval {$parser->parse ($tmpxsd)}; -XML::Xerces::error($@) if ($@); - -$doc = $parser->getDocument(); - -$impl = XML::Xerces::DOMImplementationRegistry::getDOMImplementation('LS'); -$writer = $impl->createDOMWriter(); -if ($writer->canSetFeature('format-pretty-print',1)) { - $writer->setFeature('format-pretty-print',1); -} -$target = XML::Xerces::StdOutFormatTarget->new(); -$writer->writeNode($target,$doc); - -unlink $tmpxml; -unlink $tmpxsd; -exit 0; diff --git a/src/programs/Utilities/hddm/hddm-schema.xsl b/src/programs/Utilities/hddm/hddm-schema.xsl deleted file mode 100644 index bd64379e41..0000000000 --- a/src/programs/Utilities/hddm/hddm-schema.xsl +++ /dev/null @@ -1,204 +0,0 @@ - - - - - - - - - - - Format error: expected root tag HDDM, found - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - hddm: - - - - - - Format error: negative value not allowed for minOccurs attribute - - - - - - - - - - - Format error: value for maxOccurs must not be less than minOccurs - - - - - Format error: maxOccurs must not be less than one - - - - - - - - - - - - - - - - - - required - - - hddm:int - - - hddm:long - - - hddm:float - - - hddm:double - - - hddm:boolean - - - hddm:string - - - hddm:anyURI - - - hddm:Particle_t - - - - - - xs:string - - - - - - - - - - - - - - - diff --git a/src/programs/Utilities/hddm/hddm-xml.cpp b/src/programs/Utilities/hddm/hddm-xml.cpp deleted file mode 100644 index 63f1e61bdb..0000000000 --- a/src/programs/Utilities/hddm/hddm-xml.cpp +++ /dev/null @@ -1,704 +0,0 @@ -/* - * hddm-xml : tool that reads in a HDDM document (Hall D Data Model) - * and translates it into plain-text xml. - * - * Version 1.4 - Richard Jones, February 10, 2021. - * - Modified to be able to read a hddm template (xml data model) as - * a valid hddm file with 0 records. This simplifies the documentation - * by eliminating the false distinction between the hddm template and - * the text header that appears at the top of every hddm file. It also - * gets rid of the unnecessary step of needing to remove binary data - * following the header in a hddm file before it can be used as a - * template in other utitilies. - * - * Version 1.3 - Richard Jones, July 2014. - * - Added support for input hddm streams with additional features - * provided through the c++ API, including on-the-fly compression with - * zlib and bzlib2, and per-record crc32 integrity checks. - * - * Version 1.2 - Richard Jones, December 2005. - * - Updated code to use STL strings and vectors instead of old c-style - * pre-allocated arrays and strXXX functions. - * - Moved functions into classes grouped by function for better clarity. - * - Introduced the XStream class library instead of the direct interface - * to the rpc/xdr c-library function. This also gives access to a nice - * integrated set of compression/decompression streambuf classes. - * - * Version 1.1 - Richard Jones, September 2003. - * - Updated code to work with the new DOM-2 implementation Xerces-c - * from apache.org. Significant changes have taken place in the API - * since DOM-1. - * - Added support for new types "long" (int64), "string" (char arrays of - * arbitrary length), and "anyURI" (special case of string). - * - Switched from native encoding to the use of the XDR library to make - * hddm files machine-independent. - * - * Original version - Richard Jones, June 4 2001. - * - * - * Programmer's Notes: - * ------------------- - * 1. The output from hddm-xml is a well-formed xml document. - * - * 2. The hddm stream contains a xml header that functions as a prototype - * of the xml output. - * - * 3. This tool can read any hddm stream. No recompilation is required. - * - * 4. The code has been tested with the xerces-c DOM implementation from - * Apache, and is intended to be used with the xerces-c library. - * - * 5. Output is sent by default to stdout and can be changed with the - * -o option. - */ - -// #define VERBOSE_HDDM_LOGGING 1 -#define BAD_CRC_IS_ONLY_WARNING 1 - -#include -#include - -#include "VersionConfig.hpp" -#include "XParsers.hpp" -#include "XString.hpp" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -#include "particleType.h" - - -#define X(str) XString(str).unicode_str() -#define S(str) str.c_str() - -using namespace xercesc; - -int explicit_repeat_count = 1; - -class XMLmaker -{ - public: - std::ofstream xout; - - XMLmaker() {}; - ~XMLmaker() {}; - - void writeXML(const XString& s); - void constructXML(xstream::xdr::istream *ifx, DOMElement* el, - int size, int depth); -}; - -class istreambuffer : public std::streambuf { - public: - istreambuffer(char* buffer, std::streamsize bufferLength) { - setg(buffer, buffer, buffer + bufferLength); - } - - std::streampos tellg() { - return gptr() - eback(); - } - - void seekg(std::streampos pos) { - reset(); - gbump(pos); - } - - int size() { - return egptr() - gptr(); - } - - void reset() { - char *gbegin = eback(); - char *gend = egptr(); - setg(gbegin, gbegin, gend); - } - - char *getbuf() { - return eback(); - } -}; - -class ostreambuffer : public std::streambuf { - public: - ostreambuffer(char* buffer, std::streamsize bufferLength) { - setp(buffer, buffer + bufferLength); - } - - std::streampos tellp() { - return pptr() - pbase(); - } - - void seekp(std::streampos pos) { - reset(); - pbump(pos); - } - - int size() { - return pptr() - pbase(); - } - - void reset() { - char *pbegin = pbase(); - char *pend = epptr(); - setp(pbegin, pend); - } - - char *getbuf() { - return pbase(); - } -}; - -void usage() -{ - std::cerr - << "\nUsage:\n" - << " hddm-xml [-n ] [-o ] [HDDM file]\n\n" - << "Options:\n" - << " -o write to .xml" - << " -n limit output to records" - << "Version: " << HDDM_VERSION_MAJOR << "." << HDDM_VERSION_MINOR - << std::endl; -} - - -int main(int argC, char* argV[]) -{ - XString xFilename; - - try - { - XMLPlatformUtils::Initialize(); - } - catch (const XMLException* toCatch) - { - XString msg(toCatch->getMessage()); - std::cerr - << "hddm-xml: Error during initialization! :\n" - << S(msg) << std::endl; - return 1; - } - - int reqcount=-1; - int argInd; - for (argInd = 1; argInd < argC; argInd++) - { - if (argV[argInd][0] != '-') - { - break; - } - else if (strcmp(argV[argInd],"-o") == 0) - { - xFilename = argV[++argInd]; - } - else if (strcmp(argV[argInd],"-n") == 0) - { - if (!sscanf(argV[++argInd],"%d",&reqcount)) - { - usage(); - return 1; - } - } - else - { - usage(); - return 1; - } - } - - XString hddmFile; - std::istream* ifs; - if (argInd == argC) - { - ifs = &std::cin; - } - else if (argInd == argC - 1) - { - hddmFile = XString(argV[argInd]); - ifs = new std::ifstream(hddmFile.c_str()); - } - else - { - usage(); - return 1; - } - if (!ifs->good()) - { - std::cerr - << "hddm-xml: Error opening input stream " << hddmFile << std::endl; - exit(1); - } - std::ostringstream tmpFileStr; - tmpFileStr << "tmp" << getpid(); - std::ofstream ofs(tmpFileStr.str().c_str()); - if (! ofs.is_open()) - { - std::cerr - << "hddm-xml: Error opening temp file " << tmpFileStr.str() << std::endl; - exit(2); - } - - XString xmlPreamble("\n"); - XString xmlHeader; - XString line; - while (getline(*ifs,line)) - { - if (line.find("") != line.npos) - { - xmlPreamble += line + "\n"; - } - else if (line.size() == 0) - { - xmlPreamble += "\n"; - } - else if (line.find("") - { - break; - } - } - ofs.close(); - -#if defined OLD_STYLE_XERCES_PARSER - DOMDocument* document = parseInputDocument(tmpFileStr.str().c_str(),false); -#else - DOMDocument* document = buildDOMDocument(tmpFileStr.str().c_str(),false); -#endif - if (document == 0) - { - std::cerr - << "hddm-xml : Error parsing HDDM document, " - << "cannot continue" << std::endl; - return 1; - } - unlink(tmpFileStr.str().c_str()); - - DOMElement* rootEl = document->getDocumentElement(); - XString rootS(rootEl->getTagName()); - if (rootS != "HDDM") - { - std::cerr - << "hddm-xml error: root element of input document is " - << "\"" << S(rootS) << "\", expected \"HDDM\"" - << std::endl; - return 1; - } - - XMLmaker builder; - if (xFilename.size()) - { - XString fname(xFilename + ".xml"); - builder.xout.open(fname.c_str()); - } - - builder.writeXML(xmlPreamble); - builder.writeXML(xmlHeader); - - int event_buffer_size; - char *event_buffer = new char[event_buffer_size = 1000000]; - istreambuffer *isbuf = new istreambuffer(event_buffer,event_buffer_size); - xstream::xdr::istream *ifx = new xstream::xdr::istream(isbuf); - int integrity_check_mode = 0; - int compression_mode = 0; - while (reqcount && ifs->good()) - { - DOMNodeList* contList = rootEl->getChildNodes(); - int contLength = contList->getLength(); - int tsize; - ifs->read(event_buffer,4); - if (ifs->eof()) { - break; - } - isbuf->reset(); - *ifx >> tsize; -#ifdef VERBOSE_HDDM_LOGGING - XString tnameS(rootEl->getTagName()); - std::cerr << "hddm-xml : tag " << S(tnameS) - << " found with size " << tsize - << std::endl; -#endif - if (tsize <= 0) - { - break; - } - else if (tsize == 1) { - int size, format, flags; - ifs->read(event_buffer+4,4); - *ifx >> size; - ifs->read(event_buffer+8,size); - *ifx >> format >> flags; - int compression_flags = flags & 0xf0; - int integrity_flags = flags & 0x0f; - std::streambuf *fin_sb = 0; - xstream::z::istreambuf *zin_sb = 0; - xstream::bz::istreambuf *bzin_sb = 0; - int *leftovers = new int[100]; - int sizeof_leftovers = sizeof(int[100]); - leftovers[0] = 0; - if (compression_flags == compression_mode) { - fin_sb = ifs->rdbuf(); - } - else if (size == 8 && format == 0 && compression_flags == 0x10) { - if (compression_mode == 0x20) { - bzin_sb = (xstream::bz::istreambuf*)ifs->rdbuf(); - } - compression_mode = compression_flags; - zin_sb = new xstream::z::istreambuf(ifs->rdbuf(), - leftovers, sizeof_leftovers); - ifs->rdbuf(zin_sb); - if (bzin_sb != 0) - delete bzin_sb; - } - else if (size == 8 && format == 0 && compression_flags == 0x20) { - if (compression_mode == 0x10) { - zin_sb = (xstream::z::istreambuf*)ifs->rdbuf(); - } - compression_mode = compression_flags; - bzin_sb = new xstream::bz::istreambuf(ifs->rdbuf(), - leftovers, sizeof_leftovers); - ifs->rdbuf(bzin_sb); - if (zin_sb != 0) - delete zin_sb; - } - else { - if (compression_mode == 0x20) { - bzin_sb = (xstream::bz::istreambuf*)ifs->rdbuf(); - fin_sb = bzin_sb->get_streambuf(); - } - else if (compression_mode == 0x10) { - zin_sb = (xstream::z::istreambuf*)ifs->rdbuf(); - fin_sb = zin_sb->get_streambuf(); - } - compression_mode = compression_flags; - ifs->rdbuf(fin_sb); - if (zin_sb != 0) - delete zin_sb; - if (bzin_sb != 0) - delete bzin_sb; - } - if (size == 8 && format == 0 && integrity_flags == 0x0) { - integrity_check_mode = 0; - } - else if (size == 8 && format == 0 && integrity_flags == 0x1) { - integrity_check_mode = 1; - } - else { - std::cerr << "hddm-xml error: unrecognized stream modifier" - " encountered, this stream is no longer readable." - << std::endl; - break; - } - continue; - } - else if (tsize+4 > event_buffer_size) { - delete ifx; - delete isbuf; - char *new_buffer = new char[event_buffer_size = tsize+1000]; - isbuf = new istreambuffer(new_buffer,event_buffer_size); - ifx = new xstream::xdr::istream(isbuf); - memcpy(new_buffer,event_buffer,4); - *ifx >> tsize; - delete[] event_buffer; - event_buffer = new_buffer; - } - ifs->read(event_buffer+4,tsize); - --reqcount; - - if (integrity_check_mode == 1) { - char crcbuf[10]; - istreambuffer sbuf(crcbuf,10); - xstream::xdr::istream xstr(&sbuf); - unsigned int recorded_crc; - ifs->read(crcbuf,4); - xstr >> recorded_crc; - xstream::digest::crc32 crc; - std::ostream out(&crc); - out.write(event_buffer,tsize+4); - out.flush(); - if (crc.digest() != recorded_crc) { -#if BAD_CRC_IS_ONLY_WARNING - static int bad_crc_warning_needed = true; - char errmsg[] = - "WARNING: data integrity crc check failed on input.\n"; - if (bad_crc_warning_needed) { - std::cerr << errmsg << std::endl; - bad_crc_warning_needed = false; - } -#else - std::cerr << "hddm-xml error: crc32 check error on input stream" - " encountered, this stream is no longer readable." - << std::endl; - break; -#endif - } - } - - for (int c = 0; c < contLength; c++) - { - DOMNode* cont = contList->item(c); - short type = cont->getNodeType(); - if (type == DOMNode::ELEMENT_NODE) - { - DOMElement* contEl = (DOMElement*) cont; - int size; - *ifx >> size; -#ifdef VERBOSE_HDDM_LOGGING - XString cnameS(contEl->getTagName()); - std::cerr << "hddm-xml : top-level tag " << S(cnameS) - << " found with size " << size - << std::endl; -#endif - if (size > 0) - { - builder.constructXML(ifx,contEl,size,1); - } - else { - XString repS(contEl->getAttribute(X("minOccurs"))); - int rep = (repS == "")? 1 : atoi(S(repS)); - if (rep != 0) { - XString conameS(contEl->getTagName()); - std::cerr << "hddm-xml warning: top-level tag " << S(conameS) - << " found with zero size " - << "inside an event with size " << tsize - << " continue? [y/n] "; - std::string ans; - std::cin >> ans; - if (ans[0] != 'y' && ans[0] != 'Y') { - exit(5); - } - } - } - } - } - } - - builder.writeXML("\n"); - - if (ifs != &std::cin) - { - ((std::ifstream*)ifs)->close(); - } - XMLPlatformUtils::Terminate(); - return 0; -} - -/* write a string to xml output stream, either stdout or a file */ - -void XMLmaker::writeXML(const XString& s) -{ - if (xout.is_open()) - { - xout << s; - } - else - { - std::cout << s; - } -} - -/* Generate the output xml document according the DOM; - * at entry the buffer pointer bp points the the word after the word count - */ - -void XMLmaker::constructXML(xstream::xdr::istream *ifx, - DOMElement* el, int size, int depth) -{ - XString tagS(el->getTagName()); - XString repS(el->getAttribute(X("maxOccurs"))); - int rep = (repS == "unbounded")? INT_MAX : - (repS == "")? 1 : - atoi(S(repS)); - if (explicit_repeat_count && rep > 1) - { - *ifx >> rep; - size -= 4; - } - - int r; - for (r = 0; r < rep && size > 0; r++) - { - for (int d = 0; d < depth; d++) - { - writeXML(" "); - } - writeXML("<"); - writeXML(S(tagS)); - DOMNamedNodeMap* attrList = el->getAttributes(); - int listLength = attrList->getLength(); - for (int a = 0; a < listLength; a++) - { - XString nameS(attrList->item(a)->getNodeName()); - XString typeS(attrList->item(a)->getNodeValue()); - std::ostringstream attrStr; - if (typeS == "int") - { - int32_t value; - *ifx >> value; - size -= 4; - attrStr << " " << nameS << "=\"" << value << "\""; - } - else if (typeS == "long") - { - int64_t value; - *ifx >> value; - size -= 8; - attrStr << " " << nameS << "=\"" << value << "\""; - } - else if (typeS == "float") - { - float value; - *ifx >> value; - size -= 4; - attrStr << " " << nameS << "=\"" << value << "\""; - } - else if (typeS == "double") - { - double value; - *ifx >> value; - size -= 8; - attrStr << " " << nameS << "=\"" << value << "\""; - } - else if (typeS == "boolean") - { - bool_t value; - *ifx >> value; - size -= 4; - attrStr << " " << nameS << "=\"" << value << "\""; - } - else if (typeS == "Particle_t") - { - int32_t value; - *ifx >> value; - size -= 4; - attrStr << " " << nameS << "=\"" << ParticleType((Particle_t)value) << "(" << value << ")" << "\""; - } - else if (typeS == "string" || typeS == "anyURI") - { - std::string value; - *ifx >> value; - int strsize = value.size(); - size -= strsize + 4 + ((strsize % 4)? 4-(strsize % 4) : 0); - attrStr << " " << nameS << "=\"" << value << "\""; - } - else if (nameS == "minOccurs" || nameS == "maxOccurs") - { - ; - } - else - { - attrStr << " " << nameS << "=\"" << typeS << "\""; - } - writeXML(attrStr.str()); - } - - DOMNodeList* contList = el->getChildNodes(); - int contLength = contList->getLength(); - if (contLength > 1) - { - writeXML(">\n"); - } - else - { - writeXML(" />\n"); - } - - for (int c = 0; c < contLength; c++) - { - DOMNode* cont = contList->item(c); - short type = cont->getNodeType(); - if (type == DOMNode::ELEMENT_NODE) - { - DOMElement* contEl = (DOMElement*) cont; - int csize; - *ifx >> csize; - size -= 4; -#ifdef VERBOSE_HDDM_LOGGING - XString cnameS(contEl->getTagName()); - std::cerr << "hddm-xml : tag " << S(cnameS) - << " found with size " << csize - << std::endl; -#endif - if (csize > 0) { - constructXML(ifx,contEl,csize,depth +1); - size -= csize; - } -#ifdef VERBOSE_HDDM_LOGGING - else { - XString irepS(contEl->getAttribute(X("minOccurs"))); - int irep = (irepS == "")? 1 : atoi(S(irepS)); - if (irep != 0) { - XString conameS(contEl->getTagName()); - std::cerr << "hddm-xml warning: tag " << S(conameS) - << " found with zero size, " - << "continue? [y/n] "; - std::string ans; - std::cin >> ans; - if (ans[0] != 'y' && ans[0] != 'Y') { - exit(5); - } - } - } -#endif - } - } - - if (contLength > 1) - { - for (int d = 0; d < depth; d++) - { - writeXML(" "); - } - XString endTag("\n"); - writeXML(endTag); - } - } - if (size != 0) { - std::cerr << "hddm-xml : size mismatch in tag " << S(tagS) - << ", remainder is " << size - << ", cannot continue." << std::endl; - exit(5); - } - else if (explicit_repeat_count && r != rep) { - std::cerr << "hddm-xml : repeat count mismatch in tag " << S(tagS) - << ", expected " << rep << " but saw " << r - << ", cannot continue." << std::endl; - exit(5); - } -} diff --git a/src/programs/Utilities/hddm/hddm_t.c b/src/programs/Utilities/hddm/hddm_t.c deleted file mode 100644 index d8ccdae6b0..0000000000 --- a/src/programs/Utilities/hddm/hddm_t.c +++ /dev/null @@ -1,508 +0,0 @@ -/* - * hddm_t.c - DO NOT EDIT THIS FILE - * - * This file was generated automatically from the file ex1.xml by hddm-c. - * This c file contains the i/o interface to the c structures described - * in the data model (from ex1.xml). Any program that needs access to the - * data described in the model can compile this c source file, and make use - * of the input/output services provided. - * - * The hddm data model tool set was written by - * Richard Jones, University of Connecticut. - * - * For more information see the following web site - * - * http://zeus.phys.uconn.edu/halld/datamodel/doc - */ - -#include "hddm_t.h" - -t_Hits_t* make_t_Hits(int n) -{ - int rep = (n > 1) ? n-1 : 0; - int size = sizeof(t_Hits_t) + rep * sizeof(t_Hit_t); - t_Hits_t* p = malloc(size); - memset(p,0,size); - return p; -} - -t_Sides_t* make_t_Sides(int n) -{ - int rep = (n > 1) ? n-1 : 0; - int size = sizeof(t_Sides_t) + rep * sizeof(t_Side_t); - t_Sides_t* p = malloc(size); - memset(p,0,size); - return p; -} - -t_Slabs_t* make_t_Slabs(int n) -{ - int rep = (n > 1) ? n-1 : 0; - int size = sizeof(t_Slabs_t) + rep * sizeof(t_Slab_t); - t_Slabs_t* p = malloc(size); - memset(p,0,size); - return p; -} - -t_ForwardTOF_t* make_t_ForwardTOF() -{ - int size = sizeof(t_ForwardTOF_t); - t_ForwardTOF_t* p = malloc(size); - memset(p,0,size); - return p; -} - -t_HDDM_t* make_t_HDDM() -{ - int size = sizeof(t_HDDM_t); - t_HDDM_t* p = malloc(size); - memset(p,0,size); - return p; -} - -char HDDM_t_DocumentString[] = -"\n" -" \n" -" \n" -" \n" -" \n" -" \n" -" \n" -" \n" -"\n"; - -int* sp; -int* dp; - -static t_Hits_t* unpack_t_Hits() -{ - int size = *(sp++); - int rep = *(sp++); - t_Hits_t* his = 0; - if (size > 0) - { - int r; - his = make_t_Hits(rep); - his->mult = rep; - for (r = 0; r < rep; r++ ) - { - dp = (int*) his; - *(dp++) = *(sp++); - *(dp++) = *(sp++); - } - } - return his; -} - -static t_Sides_t* unpack_t_Sides() -{ - int size = *(sp++); - int rep = *(sp++); - t_Sides_t* his = 0; - if (size > 0) - { - int r; - his = make_t_Sides(rep); - his->mult = rep; - for (r = 0; r < rep; r++ ) - { - dp = (int*) his; - *(dp++) = *(sp++); - } - } - return his; -} - -static t_Slabs_t* unpack_t_Slabs() -{ - int size = *(sp++); - int rep = *(sp++); - t_Slabs_t* his = 0; - if (size > 0) - { - int r; - his = make_t_Slabs(rep); - his->mult = rep; - for (r = 0; r < rep; r++ ) - { - dp = (int*) his; - *(dp++) = *(sp++); - } - } - return his; -} - -static t_ForwardTOF_t* unpack_t_ForwardTOF() -{ - int size = *(sp++); - t_ForwardTOF_t* his = 0; - if (size > 0) - { - his = make_t_ForwardTOF(); - { - dp = (int*) his; - } - } - return his; -} - -static t_HDDM_t* unpack_t_HDDM() -{ - int size = *(sp++); - t_HDDM_t* his = 0; - if (size > 0) - { - his = make_t_HDDM(); - { - dp = (int*) his; - } - } - return his; -} - -void* unpack_NULL() -{ - int size = *(sp++); - sp += size; - return 0; -} - -t_HDDM_t* read_t_HDDM(t_iostream* fp) -{ - t_HDDM_t* this = 0; - int ret = 0; - int* buff = malloc(1000000); - sp = buff; - - if (fp && (fp->iomode == HDDM_STREAM_INPUT)) - { - ret = fread(buff,sizeof(int),1,fp->fd); - } - if (ret) - { - ret = *buff; - ret -= fread(&sp[1],sizeof(int),ret,fp->fd); - } - else - { - free(buff); - return 0; - } - if (ret == 0) - { - int s; - void* ptrStack[10000]; - void* (*unpacker)() = fp->unpacker[0]; - ptrStack[0] = (*unpacker)(); - for (s = 1; s < fp->sections; s++) - { - int ptrOffset = fp->ptrOffset[s]; - int level = fp->modelLevel[s]; - int* ptr = ptrStack[level - 1]; - if (ptr != 0) - { - void** pp = (void**) &ptr[ptrOffset]; - unpacker = fp->unpacker[s]; - ptrStack[level] = (*unpacker)(); - *pp = ptrStack[level]; - } - else - { - ptrStack[level] = 0; - } - } - } - free(buff); - return this; -} - -static int pack_t_Hits(t_Hits_t* pp, t_iostream* fp) -{ - int* dpp = dp++; - int* spp = (int*) pp; - int* dpm = dp++; - if (spp != 0) - { - int n; - *dpm = *(spp++); - for (n = 0; n < *dpm; n++ ) - { - *(dp++) = *(spp++); - *(dp++) = *(spp++); - } - free(pp); - } - *dpp = dp - dpp - 1; - return *dpp; -} - -static int pack_t_Sides(t_Sides_t* pp, t_iostream* fp) -{ - int* dpp = dp++; - int* spp = (int*) pp; - int* dpm = dp++; - if (spp != 0) - { - int n; - *dpm = *(spp++); - for (n = 0; n < *dpm; n++ ) - { - *(dp++) = *(spp++); - pack_t_Hits(*(t_Hits_t**) spp++, fp); - } - free(pp); - } - *dpp = dp - dpp - 1; - return *dpp; -} - -static int pack_t_Slabs(t_Slabs_t* pp, t_iostream* fp) -{ - int* dpp = dp++; - int* spp = (int*) pp; - int* dpm = dp++; - if (spp != 0) - { - int n; - *dpm = *(spp++); - for (n = 0; n < *dpm; n++ ) - { - *(dp++) = *(spp++); - pack_t_Sides(*(t_Sides_t**) spp++, fp); - } - free(pp); - } - *dpp = dp - dpp - 1; - return *dpp; -} - -static int pack_t_ForwardTOF(t_ForwardTOF_t* pp, t_iostream* fp) -{ - int* dpp = dp++; - int* spp = (int*) pp; - if (spp != 0) - { - { - pack_t_Slabs(*(t_Slabs_t**) spp++, fp); - } - free(pp); - } - *dpp = dp - dpp - 1; - return *dpp; -} - -static int pack_t_HDDM(t_HDDM_t* pp, t_iostream* fp) -{ - int* dpp = dp++; - int* spp = (int*) pp; - if (spp != 0) - { - { - pack_t_ForwardTOF(*(t_ForwardTOF_t**) spp++, fp); - } - free(pp); - } - *dpp = dp - dpp - 1; - return *dpp; -} - -int flush_t_HDDM(t_HDDM_t* p,t_iostream* fp) -{ - int ret = 0; - int* buff = malloc(1000000); - dp = buff; - sp = (int*) p; - - if (p != 0) - { - pack_t_HDDM((t_HDDM_t*) (sp++), fp); - } - if (fp && (fp->iomode == HDDM_STREAM_OUTPUT)) - { - ret = fwrite(buff,sizeof(int),*buff+1,fp->fd); - } - free(buff); - return ret; -} - -static int getTag(char* d, char* tag) -{ - int level; - char line[500]; - strncpy(line,d,500); - line[499] = 0; - level = strlen(strtok(line,"<")); - strncpy(tag,strtok(NULL," >"),500); - return level/2; -} - -static char* getEndTag(char* d, char* tag) -{ - char line[500]; - char endTag[510]; - strncpy(line,d,500); - line[499] = 0; - if (strstr(strtok(line,"\n"),"/>") == 0) - { - sprintf(endTag,"",tag); - } - else - { - strcpy(endTag,"/>"); - } - return strstr(d,endTag); -} - -static int matches(char* d, char* c, t_iostream* fp) -{ - char ctag[500]; - char dtag[500]; - int clevel, dlevel; - dlevel = getTag(d,dtag); - while ((clevel = getTag(c,ctag)) == dlevel) - { - int ptrSeqNo = 0; - if ((clevel == dlevel) && (strcmp(ctag,dtag) == 0)) - { - int len = index(c+1,'\n') - c; - if (strncmp(c,d,len) != 0) - { - return -1; - } - fp->modelLevel[fp->sections] = dlevel; - if (strcmp(dtag,"hit") == 0) - { - fp->unpacker[fp->sections] = (void*) unpack_t_Hits; - fp->ptrOffset[fp->sections] = 2 + ptrSeqNo*sizeof(int*)/sizeof(int); - ++fp->sections; - } - else if (strcmp(dtag,"side") == 0) - { - fp->unpacker[fp->sections] = (void*) unpack_t_Sides; - fp->ptrOffset[fp->sections] = 1 + ptrSeqNo*sizeof(int*)/sizeof(int); - ++fp->sections; - } - else if (strcmp(dtag,"slab") == 0) - { - fp->unpacker[fp->sections] = (void*) unpack_t_Slabs; - fp->ptrOffset[fp->sections] = 1 + ptrSeqNo*sizeof(int*)/sizeof(int); - ++fp->sections; - } - else if (strcmp(dtag,"forwardTOF") == 0) - { - fp->unpacker[fp->sections] = (void*) unpack_t_ForwardTOF; - fp->ptrOffset[fp->sections] = 0 + ptrSeqNo*sizeof(int*)/sizeof(int); - ++fp->sections; - } - else if (strcmp(dtag,"HDDM") == 0) - { - fp->unpacker[fp->sections] = (void*) unpack_t_HDDM; - fp->ptrOffset[fp->sections] = 0 + ptrSeqNo*sizeof(int*)/sizeof(int); - ++fp->sections; - } - else - { - return -1; - } - c = index(c+1,'\n'); - d = index(d+1,'\n'); - while (getTag(d,dtag) > dlevel) - { - if (matches(d,c,fp)) - { - return -1; - } - else - { - d = getEndTag(d,dtag); - } - d = index(d+1,'\n'); - } - return 0; - } - else - { - c = getEndTag(c,ctag); - ++ptrSeqNo; - } - c = index(c+1,'\n'); - } - fp->unpacker[fp->sections++] = unpack_NULL; - return 0; -} - -t_iostream* open_t_HDDM(char* filename) -{ - t_iostream* fp = malloc(sizeof(t_iostream)); - char* p; - fp->fd = fopen(filename,"r"); - if (fp->fd == 0) - { - free(fp); - return 0; - } - fp->iomode = HDDM_STREAM_INPUT; - fp->hddm = malloc(1000000); - p = fp->hddm; - *p = 0; - while (strcmp(p,"\n") != 0) - { - int len = strlen(fp->hddm); - if (len < 990000) - { - p = fp->hddm + len; - fgets(p,10000,fp->fd); - } - else - { - break; - } - } - fp->sections = 0; - if (matches(fp->hddm,HDDM_t_DocumentString,fp) != 0) - { - fprintf(stderr,"HDDM Error: "); - fprintf(stderr,"input file data model "); - fprintf(stderr,"does not match "); - fprintf(stderr,"compiled code.\n"); - fprintf(stderr,"Please recompile.\n"); - exit(9); - } - fp->filename = malloc(strlen(filename) + 1); - strcpy(fp->filename,filename); - return fp; -} - -t_iostream* init_t_HDDM(char* filename) -{ - int len; - t_iostream* fp = malloc(sizeof(t_iostream)); - fp->fd = fopen(filename,"w"); - if (fp->fd == 0) - { - free(fp); - return 0; - } - fp->iomode = HDDM_STREAM_OUTPUT; - len = strlen(HDDM_t_DocumentString); - fp->hddm = malloc(len + 1); - strcpy(fp->hddm,HDDM_t_DocumentString); - if (fwrite(fp->hddm,1,len,fp->fd) != len) - { - fprintf(stderr,"HDDM Error: "); - fprintf(stderr,"error writing to "); - fprintf(stderr,"output file %s",filename); - exit(9); - } - fp->filename = malloc(strlen(filename) + 1); - strcpy(fp->filename,filename); - return fp; -} - -void close_t_HDDM(t_iostream* fp) -{ - fclose(fp->fd); - free(fp->hddm); - free(fp->filename); - free(fp); -} diff --git a/src/programs/Utilities/hddm/hddm_t.h b/src/programs/Utilities/hddm/hddm_t.h deleted file mode 100644 index af8cba357f..0000000000 --- a/src/programs/Utilities/hddm/hddm_t.h +++ /dev/null @@ -1,124 +0,0 @@ -/* - * hddm_t.h - DO NOT EDIT THIS FILE - * - * This file was generated automatically from the file ex1.xml by hddm-c. - * This header file defines the c structures that hold the data described - * in the data model (from ex1.xml). Any program that needs access to the - * data described in the model can include this header file, and make use - * of the input/output services provided inhddm_t.c - * - * The hddm data model tool set was written by - * Richard Jones, University of Connecticut. - * - * For more information see the following web site - * - * http://zeus.phys.uconn.edu/halld/datamodel/doc - * - */ - -#include -#include -#include -#include - -#ifndef SAW_t_Hit_t -#define SAW_t_Hit_t - -typedef struct { - float t; - float dE; -} t_Hit_t; - -typedef struct { - int mult; - t_Hit_t in[1]; -} t_Hits_t; -#endif /* t_Hit_t */ - -#ifndef SAW_t_Side_t -#define SAW_t_Side_t - -typedef struct { - int end; - t_Hits_t* hits; -} t_Side_t; - -typedef struct { - int mult; - t_Side_t in[1]; -} t_Sides_t; -#endif /* t_Side_t */ - -#ifndef SAW_t_Slab_t -#define SAW_t_Slab_t - -typedef struct { - float y; - t_Sides_t* sides; -} t_Slab_t; - -typedef struct { - int mult; - t_Slab_t in[1]; -} t_Slabs_t; -#endif /* t_Slab_t */ - -#ifndef SAW_t_ForwardTOF_t -#define SAW_t_ForwardTOF_t - -typedef struct { - t_Slabs_t* slabs; -} t_ForwardTOF_t; -#endif /* t_ForwardTOF_t */ - -#ifndef SAW_t_HDDM_t -#define SAW_t_HDDM_t - -typedef struct { - t_ForwardTOF_t* forwardTOF; -} t_HDDM_t; -#endif /* t_HDDM_t */ - -t_Hits_t* make_t_Hits(int n); - -t_Sides_t* make_t_Sides(int n); - -t_Slabs_t* make_t_Slabs(int n); - -t_ForwardTOF_t* make_t_ForwardTOF(); - -t_HDDM_t* make_t_HDDM(); - -#ifndef t_DocumentString -#define t_DocumentString - -extern char HDDM_t_DocumentString[]; - -#endif /* t_DocumentString */ - -#ifndef HDDM_STREAM_INPUT -#define HDDM_STREAM_INPUT -91 -#define HDDM_STREAM_OUTPUT -92 - -typedef struct { - FILE* fd; - int iomode; - char* hddm; - char* filename; - int sections; - void* (*unpacker[10000])(); - int modelLevel[10000]; - int ptrOffset[10000]; -} t_iostream; - -#endif /* HDDM_STREAM_INPUT */ - -t_HDDM_t* read_t_HDDM(t_iostream* fp); - -int flush_t_HDDM(t_HDDM_t* p,t_iostream* fp); - -t_iostream* open_t_HDDM(char* filename); - -t_iostream* init_t_HDDM(char* filename); - -void close_t_HDDM(t_iostream* fp); diff --git a/src/programs/Utilities/hddm/hddmcat.cpp b/src/programs/Utilities/hddm/hddmcat.cpp deleted file mode 100644 index 0fc82eb17d..0000000000 --- a/src/programs/Utilities/hddm/hddmcat.cpp +++ /dev/null @@ -1,187 +0,0 @@ -/* - * hddmcat : tool that reads in a sequence of HDDM files - * and catenates them into a single HDDM stream - * - * Version 1.2 - Richard Jones, December 2005. - * - Updated code to use STL strings and vectors instead of old c-style - * pre-allocated arrays and strXXX functions. - * - Moved functions into classes grouped by function for better clarity. - * - * Original version - Richard Jones, February 24 2004. - * - */ - - -#include "VersionConfig.hpp" - -#include -#include -#include -#include -using namespace std; - -#include -#include -#include -#include -#include -#include - - -void usage() -{ - cerr << "\nUsage:\n" - << " hddmcat file1.hddm [file2.hddm] ...\n\n" - << "Version: " << HDDM_VERSION_MAJOR << "." << HDDM_VERSION_MINOR - << endl; -} - -int main(int argC, char* argV[]) -{ - string xFilename; - - int argInd; - for (argInd = 1; argInd < argC; argInd++) - { - if (argV[argInd][0] != '-') - { - break; - } - else - { - usage(); - return 1; - } - } - - string hddmFile; - istream* ifs; - if (argInd == argC) - { - ifs = &cin; - } - else if (argInd < argC) - { - hddmFile = string(argV[argInd++]); - ifs = new ifstream(hddmFile.c_str()); - } - else - { - usage(); - return 1; - } - if (!ifs->good()) - { - cerr << "hddmcat: Error opening input stream " << hddmFile << endl; - exit(1); - } - - list stringList; - stringList.push_back(new string); - list::iterator h; - h = stringList.begin(); - if (std::getline(*ifs,**h)) - { - if ((*h)->substr(0,5) == "substr(0,5) == "") - { - break; - } - stringList.push_back(new string); - } - - const int bufferSize = 65536; - char buffer[bufferSize]; - int count; - while ((count = (ifs->read(buffer,bufferSize), ifs->gcount()))) - { - cout.write(buffer,count); - } - if (ifs != &cin) - { - ((ifstream*)ifs)->close(); - } - - while (argInd < argC) - { - ifstream* ifs; - hddmFile = argV[argInd++]; - ifs = new ifstream(hddmFile.c_str()); - if (!ifs->good()) - { - cerr << "hddmcat: Error opening input stream " << hddmFile << endl; - exit(1); - } - h = stringList.begin(); - string line; - if (getline(*ifs,line)) - { - if (line.substr(0,5) == "") - { - break; - } - } - - while ((count = (ifs->read(buffer,bufferSize), ifs->gcount()))) - { - cout.write(buffer,count); - } - delete ifs; - } -} diff --git a/src/programs/Utilities/hddm/hddmcp.py b/src/programs/Utilities/hddm/hddmcp.py deleted file mode 100644 index 43712f1330..0000000000 --- a/src/programs/Utilities/hddm/hddmcp.py +++ /dev/null @@ -1,50 +0,0 @@ -#!/bin/env python -# -# hddmcp.py - python alternative to the old hddmcp, multithreaded. -# -# author: richard.t.jones at uconn.edu -# version: march 23, 2018 - -import threading -import hddm_s -import sys - -def usage(): - print "Usage: hddmcp.py [-n #threads] ... " - sys.exit(1) - -def copy(fin): - for r in fin: - fout.write(r) - -nthreads = 1 -infiles = [] -iarg = 1 -while iarg < len(sys.argv): - arg = sys.argv[iarg] - iarg += 1 - if arg == '-n': - nthreads = int(sys.argv[iarg]) - iarg += 1 - continue - elif arg[0:2] == '-n': - nthreads = int(arg[2:]) - continue - infiles.append(arg) -outfile = infiles.pop() -if len(infiles) < 1: - usage() -fout = hddm_s.ostream(outfile) -fout.compression = hddm_s.k_bz2_compression - -for infile in infiles: - print "starting", infile - fin = hddm_s.istream(infile) - threads = [] - for i in range(0, nthreads): - t = threading.Thread(target=copy, args=(fin,)) - t.start() - threads.append(t) - for t in threads: - t.join() - print "finished", infile diff --git a/src/programs/Utilities/hddm/hitexam.xml b/src/programs/Utilities/hddm/hitexam.xml deleted file mode 100644 index f2b4076a87..0000000000 --- a/src/programs/Utilities/hddm/hitexam.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - diff --git a/src/programs/Utilities/hddm/index.html b/src/programs/Utilities/hddm/index.html deleted file mode 100644 index 942f9699c8..0000000000 --- a/src/programs/Utilities/hddm/index.html +++ /dev/null @@ -1,642 +0,0 @@ - - - GlueX Data Model - - - -

- -GlueX Internal Note - -

- -

HDDM - GlueX Data Model

-

draft 1.1

-

- -Richard Jones
-September 12, 2003 -
-
(supersedes draft 1.0, September 12, 2003) -

- -

-

-Fig. 1: The conceptual data model for GlueX begins with a physics -event, coming either from the detector or a Monte Carlo program, -which builds up internal structure as it flows through the -analysis pipeline. The data model specifies the elements of information -that are contained in a view of the event at each stage and the -relationships between them. The implementation provides standard -methods for creating, storing and accessing the information. -

- -

- -

General Notes:

-
    -
  1. At each stage (lower-case items in diagram) in the pipeline one has - a unique view of the event. -
  2. -
  3. To each of these is associated a unique data model that expresses - the event in that view. -
  4. -
  5. GlueX policy is to use xml to describe all of our shared data, which - means any data that might be passed as input to a program or produced - as output. This does not mean that all data records are represented - as plain-text files, but that to each data file or i/o port is attached - some metadata that a tool can use to automatically express all of its - contents in the form of a plain-text xml document. -
  6. -
  7. This policy is interpreted to mean that to each data file or i/o port - of a program is associated a xml schema that defines the data structure - that the program expects or produces. The schemas should be either - bundled with the distribution of the program, or published on the web - and indicated by links in the Readme file. -
  8. -
  9. Any xml document should be accepted as input to a program if it is - valid according to the schema associated to that input port. -
  10. -
  11. In practice, this last requirement adds significant of overhead to the - task of writing a simple analysis program, because it must be capable of - parsing general xml documents as input. In addition to this overhead - imposed on the program code itself, the author must also produce schemas - for each input or output port or file accessed by the program. -
  12. -
  13. The purpose of the Hall D Data Model (HDDM) is to simplify the - programmer's task by providing automatic ways to generate schemas - and providing i/o libraries to standardize input and output of data - in the form of xml-described files. -
  14. -
  15. HDDM consists of a specification supported by a - set of tools to assist its implementation. The - specification is a set of rules that a programmer must obey in - constructing schemas in order for them to be supported by the tools. - The tools include an automatic schema generator and an i/o - library builder for c and c++. -
  16. -
  17. The HDDM specification was designed to enable the construction of an - efficient i/o library. It was assumed in the design that users could - not afford a general xml-parsing cycle every time an event is read in - or written out by a program. It was also assumed that serializing data - in plain-text xml is too expensive in terms of bandwidth and storage. - Using the HDDM tools, users can efficiently pass data between programs - in a serialized binary stream, and convert to/from plain-text xml - representations using a translation tool when desired. -
  18. -
  19. Programmers are not obligated to use HDDM tools to work in the GlueX - software framework. If they provide their own schema for each file or - i/o port used by the program and accept any xml that respects their - input schema then they are within the agreed framework. -
  20. -
  21. The HDDM tools are presently implemented in c and c++, so programmers - wishing to work in java have more work to do. However, they will find - it easy to interface to other programs that do use the HDDM libraries - because they provide for the correct reading and writing of valid xml - files and the automatic generation of schemas that describe them. -
  22. -
  23. The hddm-c tool automatically constructs a set of c-structures - based on xml metadata that can be used to express the data in memory. - It also builds an i/o library that can be called by user code to - serialize/deserialize these structures. -
  24. -
  25. The serialized data format supported by hddm-c consists of a - xml header in plain text that describes the structure and contents of - the file, followed by a byte string that is a reasonably compact - serialization of the structured data in binary form. Such hddm - files are inherently self-describing. The overhead of including the - metadata in the stream with the data is negligible. -
  26. -
  27. The hddm-xml tool extracts the xml metadata from a hddm file - header and expresses the data stored in the file in the form of a - plain-text xml document. -
  28. -
  29. The hddm-schema tool extracts the xml metadata from a hddm file - header and generates a schema that describes the structure of the data - in the file. The schema produced by hddm-schema will always - validate the document produced by hddm-xml when both act on the - same hddm file. More significantly, the schema can be used to check - the validity of other xml data that originate from a different source. -
  30. -
  31. The xml-hddm tool reads an xml document and examines its schema - for compliance with the HDDM specification. If successful, it parses - the xml file and converts it into hddm format. -
  32. -
  33. The schema-hddm tool reads a schema and checks it for compliance - with the HDDM specification. If successful, it parses it into the form - of a hddm file consisting of the header only and no data. Such a - data-less hddm file is also called a "template" - (see below). -
  34. -
  35. Note that the hddm-xml, hddm-schema, and hddm-c tools - can act on any hddm data file written by any program, even if the code - that produced the data is no longer available. This is because - sufficient metadata is provided in the schema header to completely - reconstruct the file's contents in xml, or instantiate it in c-structures. -
  36. -
  37. A tool called xml-xml has been included in the tool set as a - simple means to validate an arbitrary xml document against a dtd or - schema, and reformat it with indentation to make it easier to read. -
  38. -
  39. Tools called stdhep2hddm and hddm2stdhep provide - conversion between the hddm data stream and the STDHEP format used by - HDFast. This is an example where a user program achieves xml i/o - by employing translators, in this case a two-stage pipeline. -
  40. -
  41. In spite of the array of tools described above, the programmer still - must do the work of describing the structure and contents of the data - expected or produced by his program. He may do this in one of two - ways: either he constructs an original schema describing his data, or - he creates an original xml template of his data and then generates the - schema using hddm-schema. -
  42. -
  43. Since schemas are rather verbose and repetitive, the suggested method - is to create a template first, use hddm-schema to transform it - into a basic HDDM schema, and then add facets to the schema to enrich the - minimal set of metadata generated from the template. This method has - the advantage that one starts off with a basic schema that is known to - conform to the rules for HDDM schemas (see below) - so it is relatively simple thereafter to stay within the specification. -
  44. -
  45. As a shortcut to creating schemas, it is not necessary to do anything - more than just create the template. The basic schema that is generated - automatically from the template contains sufficient information to - validate most data, so a programmer can get by without ever learning - how to write or modify schemas. -
  46. -
- - -

Rules for constructing HDDM templates:

-
    -
  1. A hddm template is nothing more than a plain-text xml file that mimics - the structure of the xml that the program expects on input or produces - on output. In some ways it is like sample data that the programmer - might provide to a user to demonstrate how to use it, although the - comparison is not perfect. -
  2. -
  3. The top element in the template must be <HDDM> and have - three required attributes: class, version, and xmlns. - The value of the latter must be xmlns="http://www.gluex.org/hddm". - The values of the class and version arguments are user-defined. They - serve to identify a group of schemas that share a basic set of tags. - See below for more details on classes. -
  4. -
  5. The names of elements below the root <HDDM> element are - user-defined, but they must be constructed according to the following - rules. -
  6. -
  7. All values in hddm files are expressed as attributes of elements. - Any text that appears between tags in the template is treated as - a comment and ignored. -
  8. -
  9. An element may have two information attached to it: child elements - which appear as new tags enclosed between the open and close tags of - the parent element, and attributes which appear as key="value" - items inside the open tag. -
  10. -
  11. All quantities in the data model are carried by named attributes of - elements. The rest of the document exists to express the meaning of - the data and the relationships between them. -
  12. -
  13. All elements in the model document either hold attributes, contain other - elements, or both. Empty elements are meaningless, and are not allowed. -
  14. -
  15. One way a template is not like sample data is that it does not - contain actual numerical or symbolic values for the fields in the - structure. In the place of actual values, the types of the fields - are given. For example, instead of showing energy="12.5 as - might be shown for sample data, the template would show in this - position energy="float" or energy="double". -
  16. -
  17. The complete list of allowed types supported by hddm is "int", "long", - "float", "double", "boolean", "string" and "Particle_t". The - Particle_t type is a value from an enumerated list of capitalized - names of physical particles. The int type is a 32-bit signed integer, - and long is a 64-bit signed integer. The other cases are obvious. -
  18. -
  19. Attributes in the template that do not belong to this list are assumed - to be constants. Constants are sometimes useful for annotating the - xml record. The must have the same value for all instances of the - element throughout the template. -
  20. -
  21. Any given attribute may appear more than once throughout the template - hierarchy. Wherever it appears, it must appear with identical - attributes and with content elements of the same order and type. -
  22. -
  23. Another difference between a template sample data is that the - template never shows a given element more than once in a given context, - even if the given tag would normally the repeated more than once for - an actual sample. One obvious example of this is a physics event, - which is represented only once in the template, but repeated multiple - times in a file. -
  24. -
  25. By default, it is assumed that an element appearing in the template - must appear in that position exactly once. If the element is allowed - to appear more than once or not at all then additional attributes - should be inserted in the element of the form minOccurs="N1" - and maxOccurs="N2", where N1 can be zero or any positive - integer and N2 can be any integer no smaller than N1, or - set to the string "unbounded". Each defaults to 1. -
  26. -
  27. Arrays of simple types are represented by a sequence of elements, - each carrying an attribute containing a single value from the array. - This is more verbose than allowing users to include arrays as a simple - space separated string of values, but the chosen method is more apt - for expressing parallelism between related arrays of data. -
  28. -
  29. An element may be used more than once in the model, but it may never - appear as a descendent of itself. Such recursion is complicated to - handle and it is hard to think of a situation where it is necessary. -
  30. -
  31. Examples of valid hddm templates are given in the examples section - below. -
  32. -
  33. Because templates contain new tags that are invented by the programmer, - it is not possible to write a standard template schema against which a - programmer can check his new xml file for use as a template. Instead of - using schema validation, the programmer can use the hddm-schema - tool to check a xml file for correctness as a hddm template. Any errors - that occur in the hddm - schema transformation indicate problems in the - xml file that must be fixed before it can be used as a template. -
  34. -
- - -

Rules for constructing HDDM schemas:

-
    -
  1. HDDM schemas must be valid xml schemas, belonging to the namespace - http://www.w3.org/2001/XMLSchema. Not every valid schema is a valid - HDDM schema, however, because xml allows for several different ways to - express a given data structure. -
  2. -
  3. GlueX programmers are not obligated to write schemas that conform to - the HDDM specification, but if they do, they have the help of the HDDM - tools for efficient file storage and i/o. -
  4. -
  5. In the following specification, a prefix xs: is applied to the - names of elements, attributes or datatypes that belong to the official - schema namespace "http://www.w3.org/2001/XMLSchema", whose meaning is - defined by the xml schema standard. The extensions introduced for the - specific needs of GlueX are assigned to a private namespace called - "http://www.gluex.org/hddm" that is denoted by the prefix hddm:. -
  6. -
  7. The top element defined by the schema must be <hddm:HDDM> and have - three required attributes: class, version, and xmlns. - The value of the latter must be xmlns="http://www.gluex.org/hddm". - The class and version arguments are of type xs:string and are - user-defined. They serve to identify a group of schemas that share a - basic set of tags. See below for more details. -
  8. -
  9. The names of elements below the root <hddm:HDDM> element are - user-defined, but they must be constructed according to the following - rules. -
  10. -
  11. An element may have two kinds of content: child elements and attributes, - and hence must have xs:complexType. Elements represent the - grouping together of related pieces of data in a hierarchy of nodes. - The actual numerical or symbolic values of individual variables appear - as the values of attributes. Examples are shown - below. -
  12. -
  13. All quantities in the data model are carried by named attributes of - elements. The rest of the document exists to express the meaning of - the data and the relationships between them. -
  14. -
  15. All elements in the model document either hold attributes, contain other - elements, or both. Empty nodes are meaningless, and are not allowed. -
  16. -
  17. Text content between open and close tags is allowed in documents - (type="mixed") but it is treated as a comment and stripped on - translation. Basic HDDM schemas do not use type="mixed" - elements. -
  18. -
  19. The datatype of an attribute is restricted to a subset of basic types - to simplify the task of translation. Currently the list is - xs:int, xs:long, xs:float, xs:double, - xs:boolean, xs:string, xs:anyURI and - hddm:Particle_t. User types that are derived from the above - by xs:restriction may also be defined and used in a HDDM schema. -
  20. -
  21. Attributes must always be either "required" or "fixed". Default - attributes, i.e. those that are sometimes present inside their host and - sometimes not are not allowed. This allows a single element to be - treated as a fixed-length binary object on serialization, which has - advantages for efficient i/o. -
  22. -
  23. A datum that is sometimes absent can be expressed in the model by - assigning it as an attribute to its own host element and putting the - host element into its parent with minOccurs="0". -
  24. -
  25. Fixed attributes (with use="fixed") may be attached to - user-defined elements. They may be of any valid schema datatype, not - just those listed above, and may be used as comments to qualify the - information contained in the element. Because they have the same - value for every instance of the element, they do not take up space in - the binary stream, but they are included explicitly in the output - produced by the hddm-xml translator. -
  26. -
  27. All elements must be globally defined in the schema, i.e. declared at - the top level of the xs:schema element. Child elements are - included in the definition of their parents through a ref=tagname - reference. Local definitions of elements inside other elements are not - allowed. This guarantees that a given element has the same meaning and - contents wherever it appears in the hierarchy. -
  28. -
  29. Arrays of simple types are represented by a sequence of elements, - each carrying an attribute containing a single value from the array. - This is more verbose than allowing a simple list type like is defined - by xs:list, but the chosen method is more apt for expressing - parallelism between related arrays of data, such as frequently occurs - in descriptions of physical events. Forbidding the use of simple - xs:list datatypes should encourage programmers to chose the - better model, although of course they could just mimic the habitual use - of lists by filling the data tree with long strings of monads! -
  30. -
  31. Elements are included inside their parent elements within a - xs:sequence schema declaration. Each member of the sequence - must be a reference to another element with a top-level definition. -
  32. -
  33. A given element may occur only once in a given the sequence, but may - have minOccurs and maxOccurs attributes to indicate - possible absence or repetition of the element. -
  34. -
  35. The sequence is the only content organizer allowed by HDDM. - More complex organizers are supported by schema standards, such as - all and choice, but their use would complicate the i/o - i/o interfaces that have to handle them and they add little by way - of flexibility to the model the way it is currently defined. -
  36. -
  37. An element may be used more than once in the model, but it may never - appear as a descendent of itself. Such recursion is complicated to - handle and it is hard to think of a situation where it is necessary. -
  38. -
  39. A user can check whether a given schema conforms to the HDDM rules - by transforming it into a hddm template - document. Any errors that occur during the transformation generate - a message indicating where the specification has been violated. -
  40. -
- - - -

Class relationships between HDDM schemas:

- -
    -
  1. Two HDDM schemas belong to the same class if all tags that are - defined in both have the same set of attributes in both. -
  2. -
  3. This is a fairly weak condition. It is possible that all data files - used in GlueX will belong to the same class, but it is not required. -
  4. -
  5. If two HDDM schemas belong to the same class then it is possible to - form a union schema that will validate documents of either type by - taking the xml union of the two schema documents and changing any - sequence elements in one and not in the other to minOccurs="0". -
  6. -
  7. The translation tools xml-hddm and hddm-xml will work - with any HDDM class. -
  8. -
  9. Any program built using the i/o library created with hddm-c is - dependent on the class of the schema used during the build. Any files - it writes through this interface will be built on this schema, however - it is able to read any file of the same class without recompilation. -
  10. -
  11. A new schema may be derived from an existing HDDM schema by taking the - existing one and adding new elements to the structure. In this case - the version attribute of the HDDM tag should be incremented, while - leaving the class attribute unchanged. -
  12. -
  13. A program that was built using the hddm-c tool for its i/o - interface can read from any from any hddm file of the same class as - the original schema used during the build. If the content of the file - is a superset of the original schema then nothing has changed. If - some elements of the original schema are missing in the file then the - i/o still works transparently, but the c-structures corresponding to - the missing elements will be empty, i.e. zeroed out. -
  14. -
  15. The c/c++ i/o library rejects an attempt to read from a hddm file that - has a schema of a different class from the one for which it was built. -
  16. -
  17. No mandatory rules are enforced on the version attribute of the - hddm file, but it is available to programs and may be used to select - certain actions based on the "vintage" of the data. -
  18. -
  19. Programs that need simultaneous access to multiple classes of hddm - files can be built with more than one i/o library. The structures and - i/o interface are defined in separate header files hddm_X.h and - implementation files hddm_X.c, where X is the class letter. -
  20. -
- - -
-

Implementation Notes:

-
    -
  1. There is a complementarity between xml schemas and the xml templates - that express the metadata in hddm files. Depending on the level of - detail desired, schemas may become arbitrarily sophisticated and - complex. On the other hand, only a small subset of that information - is needed to support the functions of the hddm tool set. Templates - allow that information to be distilled in a compact form that is both - human-readable and valid xml. -
  2. -
  3. In the present implementation, the text layout of the template - (including the whitespace between the tags) is used by the hddm tools - to simplify the encoding and decoding. There is exactly one tag per - line and two leading spaces per level of indent. This may change in - future implementations. This means that hddm file headers should not - be edited by hand. -
  4. -
  5. The XDR library is used to encode the binary values in the hddm - stream. This means that hddm files are machine-independent, and - can be read and written on any machine without any dependence on - whether the machine is little-endian or big-endian. XDR is the network - encoding standard library developed for Sun's rpc and nfs services. - For more info, search for RFC 1014 on the web or do "man xdr" under - linux. -
  6. -
  7. The binary file format will change. The point is not to fix - on some absolute binary format at this early stage. The only - design constraint was that the data model be specified in xml and - that the data be readily converted into plain-text xml, preferably - without needing to look up auxiliary files or loading the libraries - that wrote it. -
  8. -
  9. The design of the i/o library has been optimized for flexibility: - the user can request only the part of the model that is of interest. - The entire model does not even have to be present in the file, in which - case only the parts of the tree that are present in the file are loaded - into memory, and the rest of the requested structure is zeroed out. -
  10. -
  11. The only constraint between the model used in the program and that - of the hddm stream is that there be no collisions, that is tags - found in both but with different attributes. -
  12. -
  13. Two data models with colliding definitions can be used in one program - but they have to have different class Ids. Two streams with - different class Ids cannot feed into each other. In any case the - xml viewing tool hddm-xml can read a hddm stream of any class. -
  14. -
- -
-

Examples:

-
    -
  1. A simple model of an event fragment describing hits in a - time-of-flight wall. It allows for multiple hits per detector - in a single event, with t and dE information for each hit. - The hits are ordered by side (right: end=0, left: end=1) and then by - horizontal slab. The minOccurs and maxOccurs attributes allow those - tags to appear any number of times, or not at all, in the given context. -
    -<forwardTOF>
    -  <slab y="float" minOccurs="0" maxOccurs="unbounded">
    -    <side end="int" minOccurs="0" maxOccurs="unbounded">
    -      <hit t="float" dE="float" maxOccurs="unbounded" />
    -    </side>
    -  </slab>
    -</forwardTOF>
    -
    -
  2. -
  3. A model of the output from an event generator. -An example of actual output from genr8 -converted to xml using hddm-xml. Warning: some browsers have -difficulty displaying plain xml. Mozilla 1.x and Internet Explorer 6 -give a nice view of the document below. -
    -<?xml version="1.0" encoding="UTF-8"?>
    -
    -<HDDM class="s" version="1.0" xmlns="http://www.gluex.org/hddm">
    -  <physicsEvent eventNo="int" runNo="int">
    -    <reaction type="int" weight="float" maxOccurs="unbounded">
    -      <beam type="Particle_t">
    -        <momentum px="float" py="float" pz="float" E="float" />
    -        <properties charge="int" mass="float" />
    -      </beam>
    -      <target type="Particle_t">
    -        <momentum px="float" py="float" pz="float" E="float" />
    -        <properties charge="int" mass="float" />
    -      </target>
    -      <vertex maxOccurs="unbounded">
    -        <product type="Particle_t" decayVertex="int" maxOccurs="unbounded">
    -          <momentum px="float" py="float" pz="float" E="float" />
    -          <properties charge="int" mass="float" />
    -        </product>
    -        <origin vx="float" vy="float" vz="float" t="float" />
    -      </vertex>
    -    </reaction>
    -  </physicsEvent>
    -</HDDM>
    -
    -
  4. -
  5. A more complex example follows, showing a hits tree for the full -detector. -
    -<?xml version="1.0" encoding="UTF-8"?>
    -
    -<HDDM class="s" version="1.0" xmlns="http://www.gluex.org/hddm">
    -  <physicsEvent eventNo="int" runNo="int">
    -
    -    <hitView version="1.0">
    -      <barrelDC>
    -        <cathodeCyl radius="float" minOccurs="0" maxOccurs="unbounded">
    -          <strip sector="int" z="float" minOccurs="0" maxOccurs="unbounded">
    -            <hit t="float" dE="float" maxOccurs="unbounded" />
    -          </strip>
    -        </cathodeCyl>
    -        <ring radius="float" minOccurs="0" maxOccurs="unbounded">
    -          <straw phim="float" minOccurs="0" maxOccurs="unbounded">
    -            <hit t="float" dE="float" minOccurs="0" maxOccurs="unbounded" />
    -            <point z="float" dEdx="float" phi="float"
    -                        dradius="float" maxOccurs="unbounded" />
    -          </straw>
    -        </ring>
    -      </barrelDC>
    -    
    -      <forwardDC>
    -        <package pack="int" minOccurs="0" maxOccurs="unbounded">
    -          <chamber module="int" minOccurs="0" maxOccurs="unbounded">
    -            <cathodePlane layer="int" u="float" minOccurs="0" maxOccurs="unbounded">
    -              <hit t="float" dE="float" minOccurs="0" maxOccurs="unbounded"/>
    -              <cross v="float" z="float" tau="float" maxOccurs="unbounded" />
    -            </cathodePlane>
    -          </chamber>
    -        </package>
    -      </forwardDC>
    -    
    -      <startCntr>
    -        <sector sector="float" minOccurs="0" maxOccurs="unbounded">
    -          <hit t="float" dE="float" maxOccurs="unbounded" />
    -        </sector>
    -      </startCntr>
    -    
    -      <barrelCal>
    -        <module sector="float" minOccurs="0" maxOccurs="unbounded">
    -          <flash t="float" pe="float" maxOccurs="unbounded" />
    -        </module>
    -      </barrelCal>
    -        
    -      <Cerenkov>
    -        <module sector="float" minOccurs="0" maxOccurs="unbounded">
    -          <flash t="float" pe="float" maxOccurs="unbounded" />
    -        </module>
    -      </Cerenkov>
    -    
    -      <forwardTOF>
    -        <slab y="float" minOccurs="0" maxOccurs="unbounded">
    -          <side end="int" minOccurs="0" maxOccurs="unbounded">
    -            <hit t="float" dE="float" maxOccurs="unbounded" />
    -          </side>
    -        </slab>
    -      </forwardTOF>
    -    
    -      <forwardEMcal>
    -        <row row="int" minOccurs="0" maxOccurs="unbounded">
    -          <column col="int" minOccurs="0" maxOccurs="unbounded">
    -            <flash t="float" pe="float" maxOccurs="unbounded" />
    -          </column>
    -        </row>
    -      </forwardEMcal>
    -    </hitView>
    -  </physicsEvent>
    -</HDDM>
    -
    -
  6. -
- -
-
-This material is based upon work supported by the National Science Foundation under Grant No. 0072416. -
- - diff --git a/src/programs/Utilities/hddm/md5.c b/src/programs/Utilities/hddm/md5.c deleted file mode 100644 index c35d96c5ef..0000000000 --- a/src/programs/Utilities/hddm/md5.c +++ /dev/null @@ -1,381 +0,0 @@ -/* - Copyright (C) 1999, 2000, 2002 Aladdin Enterprises. All rights reserved. - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - L. Peter Deutsch - ghost@aladdin.com - - */ -/* $Id: md5.c,v 1.6 2002/04/13 19:20:28 lpd Exp $ */ -/* - Independent implementation of MD5 (RFC 1321). - - This code implements the MD5 Algorithm defined in RFC 1321, whose - text is available at - http://www.ietf.org/rfc/rfc1321.txt - The code is derived from the text of the RFC, including the test suite - (section A.5) but excluding the rest of Appendix A. It does not include - any code or documentation that is identified in the RFC as being - copyrighted. - - The original and principal author of md5.c is L. Peter Deutsch - . Other authors are noted in the change history - that follows (in reverse chronological order): - - 2002-04-13 lpd Clarified derivation from RFC 1321; now handles byte order - either statically or dynamically; added missing #include - in library. - 2002-03-11 lpd Corrected argument list for main(), and added int return - type, in test program and T value program. - 2002-02-21 lpd Added missing #include in test program. - 2000-07-03 lpd Patched to eliminate warnings about "constant is - unsigned in ANSI C, signed in traditional"; made test program - self-checking. - 1999-11-04 lpd Edited comments slightly for automatic TOC extraction. - 1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5). - 1999-05-03 lpd Original version. - */ - -#include "md5.h" -#include - -#undef BYTE_ORDER /* 1 = big-endian, -1 = little-endian, 0 = unknown */ -#ifdef ARCH_IS_BIG_ENDIAN -# define BYTE_ORDER (ARCH_IS_BIG_ENDIAN ? 1 : -1) -#else -# define BYTE_ORDER 0 -#endif - -#define T_MASK ((md5_word_t)~0) -#define T1 /* 0xd76aa478 */ (T_MASK ^ 0x28955b87) -#define T2 /* 0xe8c7b756 */ (T_MASK ^ 0x173848a9) -#define T3 0x242070db -#define T4 /* 0xc1bdceee */ (T_MASK ^ 0x3e423111) -#define T5 /* 0xf57c0faf */ (T_MASK ^ 0x0a83f050) -#define T6 0x4787c62a -#define T7 /* 0xa8304613 */ (T_MASK ^ 0x57cfb9ec) -#define T8 /* 0xfd469501 */ (T_MASK ^ 0x02b96afe) -#define T9 0x698098d8 -#define T10 /* 0x8b44f7af */ (T_MASK ^ 0x74bb0850) -#define T11 /* 0xffff5bb1 */ (T_MASK ^ 0x0000a44e) -#define T12 /* 0x895cd7be */ (T_MASK ^ 0x76a32841) -#define T13 0x6b901122 -#define T14 /* 0xfd987193 */ (T_MASK ^ 0x02678e6c) -#define T15 /* 0xa679438e */ (T_MASK ^ 0x5986bc71) -#define T16 0x49b40821 -#define T17 /* 0xf61e2562 */ (T_MASK ^ 0x09e1da9d) -#define T18 /* 0xc040b340 */ (T_MASK ^ 0x3fbf4cbf) -#define T19 0x265e5a51 -#define T20 /* 0xe9b6c7aa */ (T_MASK ^ 0x16493855) -#define T21 /* 0xd62f105d */ (T_MASK ^ 0x29d0efa2) -#define T22 0x02441453 -#define T23 /* 0xd8a1e681 */ (T_MASK ^ 0x275e197e) -#define T24 /* 0xe7d3fbc8 */ (T_MASK ^ 0x182c0437) -#define T25 0x21e1cde6 -#define T26 /* 0xc33707d6 */ (T_MASK ^ 0x3cc8f829) -#define T27 /* 0xf4d50d87 */ (T_MASK ^ 0x0b2af278) -#define T28 0x455a14ed -#define T29 /* 0xa9e3e905 */ (T_MASK ^ 0x561c16fa) -#define T30 /* 0xfcefa3f8 */ (T_MASK ^ 0x03105c07) -#define T31 0x676f02d9 -#define T32 /* 0x8d2a4c8a */ (T_MASK ^ 0x72d5b375) -#define T33 /* 0xfffa3942 */ (T_MASK ^ 0x0005c6bd) -#define T34 /* 0x8771f681 */ (T_MASK ^ 0x788e097e) -#define T35 0x6d9d6122 -#define T36 /* 0xfde5380c */ (T_MASK ^ 0x021ac7f3) -#define T37 /* 0xa4beea44 */ (T_MASK ^ 0x5b4115bb) -#define T38 0x4bdecfa9 -#define T39 /* 0xf6bb4b60 */ (T_MASK ^ 0x0944b49f) -#define T40 /* 0xbebfbc70 */ (T_MASK ^ 0x4140438f) -#define T41 0x289b7ec6 -#define T42 /* 0xeaa127fa */ (T_MASK ^ 0x155ed805) -#define T43 /* 0xd4ef3085 */ (T_MASK ^ 0x2b10cf7a) -#define T44 0x04881d05 -#define T45 /* 0xd9d4d039 */ (T_MASK ^ 0x262b2fc6) -#define T46 /* 0xe6db99e5 */ (T_MASK ^ 0x1924661a) -#define T47 0x1fa27cf8 -#define T48 /* 0xc4ac5665 */ (T_MASK ^ 0x3b53a99a) -#define T49 /* 0xf4292244 */ (T_MASK ^ 0x0bd6ddbb) -#define T50 0x432aff97 -#define T51 /* 0xab9423a7 */ (T_MASK ^ 0x546bdc58) -#define T52 /* 0xfc93a039 */ (T_MASK ^ 0x036c5fc6) -#define T53 0x655b59c3 -#define T54 /* 0x8f0ccc92 */ (T_MASK ^ 0x70f3336d) -#define T55 /* 0xffeff47d */ (T_MASK ^ 0x00100b82) -#define T56 /* 0x85845dd1 */ (T_MASK ^ 0x7a7ba22e) -#define T57 0x6fa87e4f -#define T58 /* 0xfe2ce6e0 */ (T_MASK ^ 0x01d3191f) -#define T59 /* 0xa3014314 */ (T_MASK ^ 0x5cfebceb) -#define T60 0x4e0811a1 -#define T61 /* 0xf7537e82 */ (T_MASK ^ 0x08ac817d) -#define T62 /* 0xbd3af235 */ (T_MASK ^ 0x42c50dca) -#define T63 0x2ad7d2bb -#define T64 /* 0xeb86d391 */ (T_MASK ^ 0x14792c6e) - - -static void -md5_process(md5_state_t *pms, const md5_byte_t *data /*[64]*/) -{ - md5_word_t - a = pms->abcd[0], b = pms->abcd[1], - c = pms->abcd[2], d = pms->abcd[3]; - md5_word_t t; -#if BYTE_ORDER > 0 - /* Define storage only for big-endian CPUs. */ - md5_word_t X[16]; -#else - /* Define storage for little-endian or both types of CPUs. */ - md5_word_t xbuf[16]; - const md5_word_t *X; -#endif - - { -#if BYTE_ORDER == 0 - /* - * Determine dynamically whether this is a big-endian or - * little-endian machine, since we can use a more efficient - * algorithm on the latter. - */ - static const int w = 1; - - if (*((const md5_byte_t *)&w)) /* dynamic little-endian */ -#endif -#if BYTE_ORDER <= 0 /* little-endian */ - { - /* - * On little-endian machines, we can process properly aligned - * data without copying it. - */ - if (!((data - (const md5_byte_t *)0) & 3)) { - /* data are properly aligned */ - X = (const md5_word_t *)data; - } else { - /* not aligned */ - memcpy(xbuf, data, 64); - X = xbuf; - } - } -#endif -#if BYTE_ORDER == 0 - else /* dynamic big-endian */ -#endif -#if BYTE_ORDER >= 0 /* big-endian */ - { - /* - * On big-endian machines, we must arrange the bytes in the - * right order. - */ - const md5_byte_t *xp = data; - int i; - -# if BYTE_ORDER == 0 - X = xbuf; /* (dynamic only) */ -# else -# define xbuf X /* (static only) */ -# endif - for (i = 0; i < 16; ++i, xp += 4) - xbuf[i] = xp[0] + (xp[1] << 8) + (xp[2] << 16) + (xp[3] << 24); - } -#endif - } - -#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32 - (n)))) - - /* Round 1. */ - /* Let [abcd k s i] denote the operation - a = b + ((a + F(b,c,d) + X[k] + T[i]) <<< s). */ -#define F(x, y, z) (((x) & (y)) | (~(x) & (z))) -#define SET(a, b, c, d, k, s, Ti)\ - t = a + F(b,c,d) + X[k] + Ti;\ - a = ROTATE_LEFT(t, s) + b - /* Do the following 16 operations. */ - SET(a, b, c, d, 0, 7, T1); - SET(d, a, b, c, 1, 12, T2); - SET(c, d, a, b, 2, 17, T3); - SET(b, c, d, a, 3, 22, T4); - SET(a, b, c, d, 4, 7, T5); - SET(d, a, b, c, 5, 12, T6); - SET(c, d, a, b, 6, 17, T7); - SET(b, c, d, a, 7, 22, T8); - SET(a, b, c, d, 8, 7, T9); - SET(d, a, b, c, 9, 12, T10); - SET(c, d, a, b, 10, 17, T11); - SET(b, c, d, a, 11, 22, T12); - SET(a, b, c, d, 12, 7, T13); - SET(d, a, b, c, 13, 12, T14); - SET(c, d, a, b, 14, 17, T15); - SET(b, c, d, a, 15, 22, T16); -#undef SET - - /* Round 2. */ - /* Let [abcd k s i] denote the operation - a = b + ((a + G(b,c,d) + X[k] + T[i]) <<< s). */ -#define G(x, y, z) (((x) & (z)) | ((y) & ~(z))) -#define SET(a, b, c, d, k, s, Ti)\ - t = a + G(b,c,d) + X[k] + Ti;\ - a = ROTATE_LEFT(t, s) + b - /* Do the following 16 operations. */ - SET(a, b, c, d, 1, 5, T17); - SET(d, a, b, c, 6, 9, T18); - SET(c, d, a, b, 11, 14, T19); - SET(b, c, d, a, 0, 20, T20); - SET(a, b, c, d, 5, 5, T21); - SET(d, a, b, c, 10, 9, T22); - SET(c, d, a, b, 15, 14, T23); - SET(b, c, d, a, 4, 20, T24); - SET(a, b, c, d, 9, 5, T25); - SET(d, a, b, c, 14, 9, T26); - SET(c, d, a, b, 3, 14, T27); - SET(b, c, d, a, 8, 20, T28); - SET(a, b, c, d, 13, 5, T29); - SET(d, a, b, c, 2, 9, T30); - SET(c, d, a, b, 7, 14, T31); - SET(b, c, d, a, 12, 20, T32); -#undef SET - - /* Round 3. */ - /* Let [abcd k s t] denote the operation - a = b + ((a + H(b,c,d) + X[k] + T[i]) <<< s). */ -#define H(x, y, z) ((x) ^ (y) ^ (z)) -#define SET(a, b, c, d, k, s, Ti)\ - t = a + H(b,c,d) + X[k] + Ti;\ - a = ROTATE_LEFT(t, s) + b - /* Do the following 16 operations. */ - SET(a, b, c, d, 5, 4, T33); - SET(d, a, b, c, 8, 11, T34); - SET(c, d, a, b, 11, 16, T35); - SET(b, c, d, a, 14, 23, T36); - SET(a, b, c, d, 1, 4, T37); - SET(d, a, b, c, 4, 11, T38); - SET(c, d, a, b, 7, 16, T39); - SET(b, c, d, a, 10, 23, T40); - SET(a, b, c, d, 13, 4, T41); - SET(d, a, b, c, 0, 11, T42); - SET(c, d, a, b, 3, 16, T43); - SET(b, c, d, a, 6, 23, T44); - SET(a, b, c, d, 9, 4, T45); - SET(d, a, b, c, 12, 11, T46); - SET(c, d, a, b, 15, 16, T47); - SET(b, c, d, a, 2, 23, T48); -#undef SET - - /* Round 4. */ - /* Let [abcd k s t] denote the operation - a = b + ((a + I(b,c,d) + X[k] + T[i]) <<< s). */ -#define I(x, y, z) ((y) ^ ((x) | ~(z))) -#define SET(a, b, c, d, k, s, Ti)\ - t = a + I(b,c,d) + X[k] + Ti;\ - a = ROTATE_LEFT(t, s) + b - /* Do the following 16 operations. */ - SET(a, b, c, d, 0, 6, T49); - SET(d, a, b, c, 7, 10, T50); - SET(c, d, a, b, 14, 15, T51); - SET(b, c, d, a, 5, 21, T52); - SET(a, b, c, d, 12, 6, T53); - SET(d, a, b, c, 3, 10, T54); - SET(c, d, a, b, 10, 15, T55); - SET(b, c, d, a, 1, 21, T56); - SET(a, b, c, d, 8, 6, T57); - SET(d, a, b, c, 15, 10, T58); - SET(c, d, a, b, 6, 15, T59); - SET(b, c, d, a, 13, 21, T60); - SET(a, b, c, d, 4, 6, T61); - SET(d, a, b, c, 11, 10, T62); - SET(c, d, a, b, 2, 15, T63); - SET(b, c, d, a, 9, 21, T64); -#undef SET - - /* Then perform the following additions. (That is increment each - of the four registers by the value it had before this block - was started.) */ - pms->abcd[0] += a; - pms->abcd[1] += b; - pms->abcd[2] += c; - pms->abcd[3] += d; -} - -void -md5_init(md5_state_t *pms) -{ - pms->count[0] = pms->count[1] = 0; - pms->abcd[0] = 0x67452301; - pms->abcd[1] = /*0xefcdab89*/ T_MASK ^ 0x10325476; - pms->abcd[2] = /*0x98badcfe*/ T_MASK ^ 0x67452301; - pms->abcd[3] = 0x10325476; -} - -void -md5_append(md5_state_t *pms, const md5_byte_t *data, int nbytes) -{ - const md5_byte_t *p = data; - int left = nbytes; - int offset = (pms->count[0] >> 3) & 63; - md5_word_t nbits = (md5_word_t)(nbytes << 3); - - if (nbytes <= 0) - return; - - /* Update the message length. */ - pms->count[1] += nbytes >> 29; - pms->count[0] += nbits; - if (pms->count[0] < nbits) - pms->count[1]++; - - /* Process an initial partial block. */ - if (offset) { - int copy = (offset + nbytes > 64 ? 64 - offset : nbytes); - - memcpy(pms->buf + offset, p, copy); - if (offset + copy < 64) - return; - p += copy; - left -= copy; - md5_process(pms, pms->buf); - } - - /* Process full blocks. */ - for (; left >= 64; p += 64, left -= 64) - md5_process(pms, p); - - /* Process a final partial block. */ - if (left) - memcpy(pms->buf, p, left); -} - -void -md5_finish(md5_state_t *pms, md5_byte_t digest[16]) -{ - static const md5_byte_t pad[64] = { - 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 - }; - md5_byte_t data[8]; - int i; - - /* Save the length before padding. */ - for (i = 0; i < 8; ++i) - data[i] = (md5_byte_t)(pms->count[i >> 2] >> ((i & 3) << 3)); - /* Pad to 56 bytes mod 64. */ - md5_append(pms, pad, ((55 - (pms->count[0] >> 3)) & 63) + 1); - /* Append the length. */ - md5_append(pms, data, 8); - for (i = 0; i < 16; ++i) - digest[i] = (md5_byte_t)(pms->abcd[i >> 2] >> ((i & 3) << 3)); -} diff --git a/src/programs/Utilities/hddm/md5.h b/src/programs/Utilities/hddm/md5.h deleted file mode 100644 index 698c995d8f..0000000000 --- a/src/programs/Utilities/hddm/md5.h +++ /dev/null @@ -1,91 +0,0 @@ -/* - Copyright (C) 1999, 2002 Aladdin Enterprises. All rights reserved. - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - L. Peter Deutsch - ghost@aladdin.com - - */ -/* $Id: md5.h,v 1.4 2002/04/13 19:20:28 lpd Exp $ */ -/* - Independent implementation of MD5 (RFC 1321). - - This code implements the MD5 Algorithm defined in RFC 1321, whose - text is available at - http://www.ietf.org/rfc/rfc1321.txt - The code is derived from the text of the RFC, including the test suite - (section A.5) but excluding the rest of Appendix A. It does not include - any code or documentation that is identified in the RFC as being - copyrighted. - - The original and principal author of md5.h is L. Peter Deutsch - . Other authors are noted in the change history - that follows (in reverse chronological order): - - 2002-04-13 lpd Removed support for non-ANSI compilers; removed - references to Ghostscript; clarified derivation from RFC 1321; - now handles byte order either statically or dynamically. - 1999-11-04 lpd Edited comments slightly for automatic TOC extraction. - 1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5); - added conditionalization for C++ compilation from Martin - Purschke . - 1999-05-03 lpd Original version. - */ - -#ifndef md5_INCLUDED -# define md5_INCLUDED - -/* - * This package supports both compile-time and run-time determination of CPU - * byte order. If ARCH_IS_BIG_ENDIAN is defined as 0, the code will be - * compiled to run only on little-endian CPUs; if ARCH_IS_BIG_ENDIAN is - * defined as non-zero, the code will be compiled to run only on big-endian - * CPUs; if ARCH_IS_BIG_ENDIAN is not defined, the code will be compiled to - * run on either big- or little-endian CPUs, but will run slightly less - * efficiently on either one than if ARCH_IS_BIG_ENDIAN is defined. - */ - -typedef unsigned char md5_byte_t; /* 8-bit byte */ -typedef unsigned int md5_word_t; /* 32-bit word */ - -/* Define the state of the MD5 Algorithm. */ -typedef struct md5_state_s { - md5_word_t count[2]; /* message length in bits, lsw first */ - md5_word_t abcd[4]; /* digest buffer */ - md5_byte_t buf[64]; /* accumulate block */ -} md5_state_t; - -#ifdef __cplusplus -extern "C" -{ -#endif - -/* Initialize the algorithm. */ -void md5_init(md5_state_t *pms); - -/* Append a string to the message. */ -void md5_append(md5_state_t *pms, const md5_byte_t *data, int nbytes); - -/* Finish the message and return the digest. */ -void md5_finish(md5_state_t *pms, md5_byte_t digest[16]); - -#ifdef __cplusplus -} /* end extern "C" */ -#endif - -#endif /* md5_INCLUDED */ diff --git a/src/programs/Utilities/hddm/mk_xml.pl b/src/programs/Utilities/hddm/mk_xml.pl deleted file mode 100755 index 3033c620ce..0000000000 --- a/src/programs/Utilities/hddm/mk_xml.pl +++ /dev/null @@ -1,68 +0,0 @@ -#!/apps/bin/perl -w -# -# purpose: the schema event.xsd and create the two files hits.xml -# and reaction.xml using schema-hddm -# -# Note: in order for this script to work schema-hddm and schema-hddm.xsl -# are needed. Best run this script in ${HALLD_RECON_HOME}/src/programs/Utilities/hddm -# and copy the two output xml files to ${HALLD_RECON_HOME}/src/libraries/HDDM/ -# -# author: B. Zihlmann -# - - -use strict; -use FileHandle; - -my $schemafile = "$ENV{HALLD_RECON_HOME}/src/libraries/HDDM/event.xsd"; - -if ($#ARGV==0){ - print "Use default schema file: $schemafile\n"; -} - -my $inf = "/tmp/xml.log"; - -my $cmd = "schema-hddm $schemafile > $inf"; -system($cmd); - -my $INF = new FileHandle("<$inf") or - die "Error open file $inf\n"; - -my $ofr = "reaction.xml"; -my $ofh = "hits.xml"; - -my $OF; -my $open = 0; -my $line1 = $INF->getline(); -$line1 = "\<\?xml version=\"1.0\" encoding=\"UTF-8\"\?\>"; - -while (<$INF>){ - - if (/\$ofr") or - die "Error open file $ofr\n"; - print $OF $line1; - print $OF $_; - $open=1; - } elsif (/\<\/reaction/){ - print $OF $_; - $OF->close(); - $open=0; - } elsif (/\$ofh") or - die "Error open file $ofr\n"; - print $OF $line1; - print $OF $_; - $open=1; - } elsif (/\<\/hitView/){ - print $OF $_; - $OF->close(); - $open=0; - } elsif ($open){ - print $OF $_; - } - -} -$INF->close(); -$OF->close(); - diff --git a/src/programs/Utilities/hddm/s2xml.pl b/src/programs/Utilities/hddm/s2xml.pl deleted file mode 100755 index bc0cfeb592..0000000000 --- a/src/programs/Utilities/hddm/s2xml.pl +++ /dev/null @@ -1,83 +0,0 @@ -#!/usr/bin/perl -w - -# purpose: use the perl script schema-hddm to generate from the schema -# file event.xsd the two hddm data format file hits.xml and -# reaction.xml which are needed by file event.xml -# -# Author: B. Zihlmann Sep. 2007 -# - - -use strict; -use FileHandle; - -sub Usage(){ - - printf "\n Usage: ./s2xml.pl\n"; - - printf("\n reads schema file event.xsd and generates the two hddm files\n"); - printf(" reaction.xml and hits.xml that are used as include files in event.xml,\n"); - printf(" which in turn can be used by hddm-c to generate the files hddm_s.c and\n"); - printf(" and hddm_s.h\n"); - -} - -if (($ARGV[0] eq "--help")|| - ($ARGV[0] eq "--h")|| - ($ARGV[0] eq "-help")|| - ($ARGV[0] eq "-h")){ - - Usage(); - exit; -} - -my $sf = "event.xsd"; -my $of1 = "event.out"; - -my $cmd = "/export/home/zihlmann/HallD/src/libraries/HDDM/schema-hddm $sf > $of1"; - -system($cmd); - -if(! (-e $of1)){ - printf "Error generating temporary file $of1 from schema file $sf\n"; - exit; -} - -my $INF = new FileHandle("<$of1") or - die "Error open temporary file $of1\n"; - -my $headerline = ""; -my $ofr = "reaction.xml"; -my $ofh = "hits.xml"; - -my $OUTF = new FileHandle(); -my $FH = 0; -while(<$INF>){ - - if (/\$ofr") or - die "Error open file $ofr\n"; - print $OUTF $headerline; - $FH=1; - } - if (/\$ofh") or - die "Error open file $ofh\n"; - print $OUTF $headerline; - $FH=1; - } - if ($FH){ - print $OUTF $_; - } - if (/\<\/reaction/){ - undef $OUTF; - $FH=0; - } - if (/\<\/hitView/){ - undef $OUTF; - $FH=0; - } - -} -undef $INF; -system("rm -f $of1"); diff --git a/src/programs/Utilities/hddm/schema-hddm b/src/programs/Utilities/hddm/schema-hddm deleted file mode 100755 index 185ae6413c..0000000000 --- a/src/programs/Utilities/hddm/schema-hddm +++ /dev/null @@ -1,80 +0,0 @@ -#!/usr/bin/env perl -# -# schema-hddm: create a hddm template based on a xml schema -# -# Both templates and schemas are themselves well-formed xml documents, -# so the transformation can be done automatically using XSLT tools. -# This implementation uses Xalan from xml.apache.org to carry out the -# transformation. Some result is passed through the XercesDOMParser -# just to check for well-formed xml and improve the readability of the -# of the template. -# -# Richard T. Jones -# September 15, 2003 -# ------------------ - -use XML::Xerces; - -sub Usage() -{ - print <new(); -$parser->setValidationScheme (0); -$parser->setDoNamespaces (1); -$parser->setCreateEntityReferenceNodes(1); -$parser->setDoSchema (1); - -$ERROR_HANDLER = XML::Xerces::PerlErrorHandler->new(); -$parser->setErrorHandler($ERROR_HANDLER); -eval {$parser->parse ($tmpxml)}; -XML::Xerces::error($@) if ($@); - -$doc = $parser->getDocument(); - -$impl = XML::Xerces::DOMImplementationRegistry::getDOMImplementation('LS'); -$writer = $impl->createDOMWriter(); -if ($writer->canSetFeature('format-pretty-print',1)) { - $writer->setFeature('format-pretty-print',1); -} -$target = XML::Xerces::StdOutFormatTarget->new(); -$writer->writeNode($target,$doc); - -unlink $tmpxml; -exit 0; diff --git a/src/programs/Utilities/hddm/schema-hddm.xsl b/src/programs/Utilities/hddm/schema-hddm.xsl deleted file mode 100644 index dbdd921490..0000000000 --- a/src/programs/Utilities/hddm/schema-hddm.xsl +++ /dev/null @@ -1,465 +0,0 @@ - - - - - - - - - - - - - Format error: expected schema, found - - - - - Format error: wrong namespace for schema: - expected "http://www.w3.org/2001/XMLSchema" - found - - - - - - - - - - - - Format error: schema does not describe HDDM document type - - - - - Format error: element HDDM should only appear once in schema - - - - - Format error: target namespace should be "http://www.gluex.org/hddm" - - - - - - - - - - - - - - - - Format error: unable to find HDDM "class" attribute - - - - - - - - Format error: unable to find HDDM "version" attribute - - - - - - - - - Format error: schema defines unknown attribute "" - for HDDM element - - - - - - - - - - - - - - - - - - Format error: elements of type "" - from namespace "" - are not currently supported - - - - - - - - - - - - Format error: element references not allowed in a top-level declaration - - - - - Format error: element references not allowed in a top-level declaration - - - - - Format error: element references not allowed in a top-level declaration - - - - - Format error: substitution groups are not allowed by HDDM - - - - - Format error: fixed elements (as opposed to fixed attributes) - are not allowed by HDDM - - - - - Format error: defaulted elements are not allowed by HDDM - - - - - Format error: element attribute "" - is not currently supported in the element declaration - - - - - - - - - - - - - - - - - - - - - - - - - - Format error: user-defined type "" - assigned to element "" - must be a named complexType to fit the HDDM specification - - - - - - - Format error: element "" - has a type declaration that does not fit the HDDM specification - - - - - - - - - - - - - - - Format error: contents of type "" - from namespace "" - are not currently supported - - - - - - - - - - - - - - - - Format error: sequence contains "" - from namespace "" - not currently supported - - - - - - Format error: sequence contains anonymous "" - all elements must be named and declared at the top level of the schema - - - - - - - - - - - - - - - - - Format error: abstract element not allowed in an element reference - - - - - Format error: type declaration not allowed in an element reference - - - - namespace-uri() = 'http://www.w3.org/2001/XMLSchema'"> - - Format error: substitution groups are not allowed by HDDM - - - - - Format error: fixed elements (as opposed to fixed attributes) - are not allowed by HDDM - - - - - Format error: defaulted elements are not allowed by HDDM - - - - - Format error: element attribute "" - is not currently supported in an element reference - - - - - - - - - - Format error: element "" - must be defined once at the top level of the document - - - - - - - - - - - - Warning: use="" ignored - for attribute " - - - - - - - - - - - Format error: attribute reference "" - should not try to define its own "" - - - - - - - - - - - - - - - - - - - - Format error: attribute descriptor "" - is not currently supported - - - - - - - - - - - - - - - - - - - - int - - - long - - - float - - - double - - - Particle_t - - - string - - - anyURI - - - boolean - - - - - - - - - - - - - - Format error: attribute "" - has unsupported type "" - Did you forget the namespace prefix? - - - - - - - Format error: attribute "" - must either be assigned on of the HDDM types or assigned fixed values - - - - - - - - - - - - Format error: attribute type "" - must derive by restriction from one of the allowed base types - - - - - - - - - - - int - - - long - - - float - - - double - - - string - - - string - - - anyURI - - - boolean - - - - - - - - - - - Format error: attribute "" - has unsupported type "" - Did you forget the namespace prefix? - - - - - - - - - - - - - diff --git a/src/programs/Utilities/hddm/test.xml b/src/programs/Utilities/hddm/test.xml deleted file mode 100644 index 33ea56a6b8..0000000000 --- a/src/programs/Utilities/hddm/test.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - - - - diff --git a/src/programs/Utilities/hddm/testhddm.cpp b/src/programs/Utilities/hddm/testhddm.cpp deleted file mode 100644 index 408dd99be4..0000000000 --- a/src/programs/Utilities/hddm/testhddm.cpp +++ /dev/null @@ -1,84 +0,0 @@ -#include -#include -using namespace std; -#include "hddm_v.h" -#include "hddm_v.hpp" - -void test_hddm_c_interface(char *outfile); -void test_hddm_cpp_interface(char *outfile); - -int main() -{ - // the following two output files should be identical - test_hddm_c_interface("test.hddm"); - test_hddm_cpp_interface("test2.hddm"); - return 0; -} - -void test_hddm_c_interface(char *outfile) -{ - v_iostream_t *outputfp = init_v_HDDM(outfile); - if (!outputfp) { - cerr << "Test failed: error opening output file\n"; - exit(1); - } - - v_HDDM_t *event; - v_GenericTag_t *tag; - event = make_v_HDDM(); - tag = make_v_GenericTag(); - tag->floatTag = make_v_FloatTag(); - tag->doubleTag = make_v_DoubleTag(); - tag->particleTag = make_v_ParticleTag(); - tag->stringTag = make_v_StringTag(); - tag->intTag = make_v_IntTag(); - tag->longTag = make_v_LongTag(); - tag->booleanTag = make_v_BooleanTag(); - tag->anyURITag = make_v_AnyURITag(); - tag->floatTag->pi = 3.141593; - tag->doubleTag->pi = 3.141592592636; - tag->particleTag->pi = PiPlus; - - tag->stringTag->quote = (char*)malloc(100); - strcpy(tag->stringTag->quote,"pass the red quarks, please"); - tag->intTag->magic = 133557799; - tag->longTag->magic = 133557799002244668LL; - tag->booleanTag->truth = 1; - tag->anyURITag->uri = (char*)malloc(100); - strcpy(tag->anyURITag->uri,"http://portal.gluex.org"); - event->genericTag = tag; - - flush_v_HDDM(event,outputfp); - close_v_HDDM(outputfp); -} - -void test_hddm_cpp_interface(char *outfile) -{ - ofstream ofs(outfile); - if (!ofs.is_open()) { - cerr << "Test failed: error opening output file\n"; - exit(1); - } - - hddm_v::HDDM record; - hddm_v::GenericTagList generics = record.addGenericTags(); - hddm_v::FloatTagList floats = generics().addFloatTags(); - hddm_v::DoubleTagList doubles = generics().addDoubleTags(); - hddm_v::ParticleTagList particles = generics().addParticleTags(); - hddm_v::StringTagList strings = generics().addStringTags(); - hddm_v::IntTagList ints = generics().addIntTags(); - hddm_v::LongTagList longs = generics().addLongTags(); - hddm_v::BooleanTagList booleans = generics().addBooleanTags(); - hddm_v::AnyURITagList anyURIs = generics().addAnyURITags(); - floats().setPi(3.141593); - doubles().setPi(3.141592592636); - particles().setPi(PiPlus); - strings().setQuote("pass the red quarks, please"); - ints().setMagic(133557799); - longs().setMagic(133557799002244668LL); - booleans().setTruth(1); - anyURIs().setUri("http://portal.gluex.org"); - - hddm_v::ostream ostr(ofs); - ostr << record; -} diff --git a/src/programs/Utilities/hddm/xml-hddm.cpp b/src/programs/Utilities/hddm/xml-hddm.cpp deleted file mode 100644 index 4ad2a41e7a..0000000000 --- a/src/programs/Utilities/hddm/xml-hddm.cpp +++ /dev/null @@ -1,601 +0,0 @@ -/* - * xml-hddm : tool that reads in a plain-text xml data document - * and writes it out as a hddm (Hall D Data Model) - * following the template provided. - * - * Version 1.2 - Richard Jones, December 2005. - * - Updated code to use STL strings and vectors instead of old c-style - * pre-allocated arrays and strXXX functions. - * - Moved functions into classes grouped by function for better clarity. - * - Introduced the XStream class library instead of the direct interface - * to the rpc/xdr c-library function. This also gives access to a nice - * integrated set of compression/decompression streambuf classes. - * - * Version 1.1 - Richard Jones, September 2003. - * - Updated code to work with the new DOM-2 implementation Xerces-c - * from apache.org. Significant changes have taken place in the API - * since DOM-1. - * - Added support for new types "long" (int64), "string" (char arrays of - * arbitrary length), and "anyURI" (special case of string). - * - Switched from native encoding to the use of the XDR library to make - * hddm files machine-independent. - * - * Original version - Richard Jones, October 1 2001. - * - * - * Programmer's Notes: - * ------------------- - * 1. The output from xml-hddm is a valid hddm data stream. - * - * 2. Two inputs are required: the input xml data document, and a xml - * template describing the structure of the data in the document. - * Both documents must be well-formed. In addition, the data document - * must conform to the hddm specification document. Only if both of - * these requirements are met is it possible to insure that the data - * document can be expressed in a hddm stream. - * - * 3. The code has been tested with the xerces-c DOM implementation from - * Apache, and is intended to be used with the xerces-c library. - * - * 4. Output is sent by default to stdout and can be changed with the - * -o option. - */ - -#include -#include - -#include "VersionConfig.hpp" -#include "XParsers.hpp" -#include "XString.hpp" - -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -#include "particleType.h" - -using namespace xercesc; - -#define X(str) XString(str).unicode_str() -#define S(str) str.c_str() - -int explicit_repeat_count = 1; - -class HDDMmaker -{ - public: - std::ostream* ofs; - - HDDMmaker() {}; - ~HDDMmaker() {}; - - void constructDocument(DOMElement* el); - void outputStream(DOMElement* thisEl, DOMElement* modelEl, - std::ostream& ofs); -}; - -void usage() -{ - std::cerr - << "\nUsage:\n" - << " xml-hddm [-o ] -t