From 4285a6d370b9950a1c0c8d39b6ef9ba96bf524a0 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 27 Jan 2025 23:50:39 +0000 Subject: [PATCH] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- CMakeLists.txt | 350 +- CTestConfig.cmake | 6 +- CTestCustom.cmake | 181 +- TimeDet/CMakeLists.txt | 41 +- TimeDet/TimeDet.cxx | 426 +- TimeDet/TimeDet.h | 110 +- TimeDet/TimeDetHit.cxx | 168 +- TimeDet/TimeDetHit.h | 32 +- TimeDet/TimeDetPoint.cxx | 43 +- TimeDet/TimeDetPoint.h | 31 +- UpstreamTagger/CMakeLists.txt | 41 +- UpstreamTagger/UpstreamTagger.cxx | 1332 +- UpstreamTagger/UpstreamTagger.h | 224 +- UpstreamTagger/UpstreamTaggerHit.cxx | 594 +- UpstreamTagger/UpstreamTaggerHit.h | 74 +- UpstreamTagger/UpstreamTaggerPoint.cxx | 43 +- UpstreamTagger/UpstreamTaggerPoint.h | 33 +- cmake/modules/CppStyleGuideChecks.cmake | 113 +- cmake/modules/FindClangTools.cmake | 45 +- cmake/modules/FindEvtGen.cmake | 73 +- cmake/modules/GenerateVersionInfo.cmake | 47 +- ecal/CMakeLists.txt | 86 +- ecal/ecal.cxx | 2278 +- ecal/ecal.h | 462 +- ecal/ecalAnalysisMaterial.cxx | 203 +- ecal/ecalAnalysisMaterial.h | 89 +- ecal/ecalAnalysisSimple.cxx | 249 +- ecal/ecalAnalysisSimple.h | 83 +- ecal/ecalCell.cxx | 53 +- ecal/ecalCell.h | 201 +- ecal/ecalCellMC.cxx | 77 +- ecal/ecalCellMC.h | 106 +- ecal/ecalCluster.cxx | 182 +- ecal/ecalCluster.h | 168 +- ecal/ecalClusterCalibration.cxx | 62 +- ecal/ecalClusterCalibration.h | 77 +- ecal/ecalClusterFinder.cxx | 368 +- ecal/ecalClusterFinder.h | 126 +- ecal/ecalContFact.cxx | 52 +- ecal/ecalContFact.h | 3 +- ecal/ecalDigi.cxx | 157 +- ecal/ecalDigi.h | 84 +- ecal/ecalDrawer.cxx | 1054 +- ecal/ecalDrawer.h | 324 +- ecal/ecalInf.cxx | 572 +- ecal/ecalInf.h | 311 +- ecal/ecalLightMap.cxx | 258 +- ecal/ecalLightMap.h | 84 +- ecal/ecalMatch.cxx | 289 +- ecal/ecalMatch.h | 75 +- ecal/ecalMaximum.cxx | 56 +- ecal/ecalMaximum.h | 95 +- ecal/ecalMaximumLocator.cxx | 163 +- ecal/ecalMaximumLocator.h | 53 +- ecal/ecalModule.cxx | 123 +- ecal/ecalModule.h | 87 +- ecal/ecalPoint.cxx | 40 +- ecal/ecalPoint.h | 41 +- ecal/ecalPreCluster.h | 91 +- ecal/ecalPrepare.cxx | 147 +- ecal/ecalPrepare.h | 89 +- ecal/ecalReco.cxx | 487 +- ecal/ecalReco.h | 75 +- ecal/ecalReconstructed.h | 80 +- ecal/ecalStructure.cxx | 595 +- ecal/ecalStructure.h | 241 +- ecal/ecalStructureFiller.cxx | 188 +- ecal/ecalStructureFiller.h | 110 +- field/CMakeLists.txt | 61 +- field/FairShipFields.cxx | 56 +- field/FairShipFields.h | 32 +- field/ShipBFieldMap.cxx | 511 +- field/ShipBFieldMap.h | 128 +- field/ShipBellField.cxx | 195 +- field/ShipBellField.h | 98 +- field/ShipCompField.cxx | 54 +- field/ShipCompField.h | 21 +- field/ShipConstField.cxx | 226 +- field/ShipConstField.h | 169 +- field/ShipFieldCreator.cxx | 64 +- field/ShipFieldCreator.h | 26 +- field/ShipFieldMaker.cxx | 1552 +- field/ShipFieldMaker.h | 162 +- field/ShipFieldPar.cxx | 300 +- field/ShipFieldPar.h | 166 +- field/ShipGoliathField.cxx | 259 +- field/ShipGoliathField.h | 105 +- field/add_noise_to_field.py | 95 +- field/convertMap.py | 172 +- field/convertMisisMap.py | 116 +- field/convertNoisyMap.py | 143 +- field/convertRALMap.py | 158 +- gconfig/DecayConfig.C | 5 +- gconfig/DecayConfigNuAge.C | 77 +- gconfig/DecayConfigPy6.C | 154 +- gconfig/DecayConfigPy8.C | 69 +- gconfig/Geane.C | 118 +- gconfig/SetCuts.C | 85 +- gconfig/UserDecay.C | 58 +- gconfig/basiclibs.C | 36 +- gconfig/flConfig.C | 17 +- gconfig/fllibs.C | 8 +- gconfig/g3Config.C | 49 +- gconfig/g3libs.C | 20 +- gconfig/g4Config.C | 92 +- gconfig/g4Config_basic.C | 91 +- gconfig/rootlogon.C | 26 +- geometry/config_tester.py | 26 +- geometry/geometry_config.py | 1399 +- geometry/media.geo | 2 +- geometry/veto_config_helium.yaml | 1 - geometry/veto_config_vacuums.yaml | 3 +- hcal/CMakeLists.txt | 58 +- hcal/hcal.cxx | 2055 +- hcal/hcal.h | 425 +- hcal/hcalAnalysisSimple.cxx | 261 +- hcal/hcalAnalysisSimple.h | 85 +- hcal/hcalContFact.cxx | 52 +- hcal/hcalContFact.h | 3 +- hcal/hcalInf.cxx | 576 +- hcal/hcalInf.h | 317 +- hcal/hcalLightMap.cxx | 258 +- hcal/hcalLightMap.h | 84 +- hcal/hcalModule.cxx | 27 +- hcal/hcalModule.h | 140 +- hcal/hcalModuleMC.cxx | 44 +- hcal/hcalModuleMC.h | 55 +- hcal/hcalPoint.cxx | 40 +- hcal/hcalPoint.h | 41 +- hcal/hcalStructure.cxx | 323 +- hcal/hcalStructure.h | 211 +- hcal/hcalStructureFiller.cxx | 179 +- hcal/hcalStructureFiller.h | 108 +- macro/ShipAna.py | 1927 +- macro/ShipReco.py | 226 +- macro/checkZpositions.py | 35 +- macro/convertEvtCalc.py | 29 +- macro/create_field_perturbation.py | 93 +- macro/dumpEvent.py | 65 +- macro/evd_addParticleFollower.py | 170 +- macro/evd_fillEnergy.py | 155 +- macro/evd_nextEvent.py | 23 +- macro/evd_transparentMode.py | 9 +- macro/eventDisplay.py | 14 +- macro/flux_map.py | 518 +- macro/getGeoInformation.py | 197 +- macro/getInteractionAndRadiationLength.py | 6 +- macro/inspectGeant4Geo.py | 16 +- macro/makeCascade.py | 831 +- macro/makeDecay.py | 349 +- macro/makeGenieEvents.py | 324 +- macro/mergeMbias.py | 1256 +- macro/runPythia8.py | 532 +- macro/run_anaEcal.py | 47 +- macro/run_simEcal.py | 95 +- macro/run_simPgun.py | 134 +- macro/run_simScript.py | 1449 +- muon/CMakeLists.txt | 42 +- muon/muon.cxx | 329 +- muon/muon.h | 100 +- muon/muonContFact.cxx | 68 +- muon/muonContFact.h | 3 +- muon/muonHit.cxx | 247 +- muon/muonHit.h | 33 +- muon/muonPoint.cxx | 39 +- muon/muonPoint.h | 21 +- muonShieldOptimization/CMakeLists.txt | 39 +- muonShieldOptimization/ana_ShipMuon.py | 2608 +- .../compactingBackgroundProduction.py | 785 +- muonShieldOptimization/exitHadronAbsorber.cxx | 463 +- muonShieldOptimization/exitHadronAbsorber.h | 108 +- .../extractMuonsAndUpdateWeight.py | 490 +- .../extractNeutrinosAndUpdateWeight.py | 215 +- muonShieldOptimization/g4Ex.py | 454 +- muonShieldOptimization/g4Ex_args.py | 553 +- muonShieldOptimization/g4Ex_gap.py | 1124 +- muonShieldOptimization/g4Ex_gap_mergeFiles.py | 435 +- muonShieldOptimization/makeMuonDIS.py | 190 +- muonShieldOptimization/makeMuonEM.py | 74 +- muonShieldOptimization/muDIS_mergeFiles.py | 114 +- muonShieldOptimization/pyFairModule.cxx | 26 +- muonShieldOptimization/pyFairModule.h | 19 +- muonShieldOptimization/radio.py | 55 +- muonShieldOptimization/runCharmHadProd.py | 389 +- muonShieldOptimization/run_fixedTarget.py | 652 +- muonShieldOptimization/run_prod.py | 404 +- muonShieldOptimization/run_reco.py | 726 +- muonShieldOptimization/simpleTarget.cxx | 255 +- muonShieldOptimization/simpleTarget.h | 107 +- muonShieldOptimization/study_GammaConv.py | 175 +- muonShieldOptimization/study_muEloss.py | 574 +- muonShieldOptimization/study_muMSC.py | 194 +- muonShieldOptimization/study_thinTarget.py | 153 +- muonShieldOptimization/submitPyG4prod.py | 38 +- nutaudet/CMakeLists.txt | 61 +- nutaudet/EmulsionMagnet.cxx | 1105 +- nutaudet/EmulsionMagnet.h | 98 +- nutaudet/HPT.cxx | 440 +- nutaudet/HPT.h | 111 +- nutaudet/HptPoint.cxx | 39 +- nutaudet/HptPoint.h | 22 +- nutaudet/MagneticSpectrometer.cxx | 969 +- nutaudet/MagneticSpectrometer.h | 116 +- nutaudet/NuTauMudet.cxx | 1677 +- nutaudet/NuTauMudet.h | 146 +- nutaudet/NutaudetContFact.cxx | 59 +- nutaudet/NutaudetContFact.h | 10 +- nutaudet/ShipRpcPoint.cxx | 41 +- nutaudet/ShipRpcPoint.h | 30 +- nutaudet/TTPoint.cxx | 37 +- nutaudet/TTPoint.h | 29 +- nutaudet/Target.cxx | 1233 +- nutaudet/Target.h | 203 +- nutaudet/TargetPoint.cxx | 43 +- nutaudet/TargetPoint.h | 29 +- nutaudet/TargetTracker.cxx | 477 +- nutaudet/TargetTracker.h | 104 +- passive/CMakeLists.txt | 48 +- passive/ShipCave.h | 12 +- passive/ShipChamber.cxx | 93 +- passive/ShipChamber.h | 15 +- passive/ShipGeoCave.cxx | 168 +- passive/ShipGeoCave.h | 22 +- passive/ShipGoliath.cxx | 285 +- passive/ShipGoliath.h | 21 +- passive/ShipMagnet.cxx | 434 +- passive/ShipMagnet.h | 40 +- passive/ShipMuonShield.cxx | 2101 +- passive/ShipMuonShield.h | 229 +- passive/ShipPassiveContFact.cxx | 58 +- passive/ShipPassiveContFact.h | 10 +- passive/ShipTAUMagneticSpectrometer.cxx | 89 +- passive/ShipTAUMagneticSpectrometer.h | 33 +- passive/ShipTargetStation.cxx | 327 +- passive/ShipTargetStation.h | 62 +- pid/CMakeLists.txt | 40 +- pid/pid.cxx | 20 +- pid/pid.h | 40 +- python/AddDiMuonDecayChannelsToG4.py | 45 +- python/CMBG_conf.py | 33 +- python/PythiaList.py | 8 +- python/ShieldUtils.py | 49 +- python/ShipGeo.py | 99 +- python/ShipGeoConfig.py | 25 +- python/ShipStyle.py | 360 +- python/TTCluster.py | 1269 +- python/TrackExtrapolateTool.py | 78 +- python/basiclibs.py | 23 +- python/checkMagFields.py | 227 +- python/configGenieGenerator.py | 106 +- python/darkphoton.py | 194 +- python/decorators.py | 181 +- python/detectArch | 7 +- python/dpProductionRates.py | 205 +- python/experimental/analysis_toolkit.py | 2 +- python/genie_interface.py | 6 +- python/geomGeant4.py | 417 +- python/goliath2root.py | 58 +- python/hepunit.py | 236 +- python/hnl.py | 792 +- python/logger.py | 28 +- python/method_logger.py | 16 +- python/pi0Reco.py | 68 +- python/proton_bremsstrahlung.py | 297 +- python/pythia8_conf.py | 364 +- python/pythia8_conf_utils.py | 210 +- python/pythia8darkphoton_conf.py | 237 +- python/readDecayTable.py | 167 +- python/rootUtils.py | 456 +- python/rootpyPickler.py | 80 +- python/rpvsusy.py | 563 +- python/saveBasicParameters.py | 84 +- python/shipDet_conf.py | 11 +- python/shipDigiReco.py | 2383 +- python/shipMuShield_only.py | 90 +- python/shipPatRec.py | 732 +- python/shipPatRec_prev.py | 23 +- python/shipPid.py | 951 +- python/shipRoot_conf.py | 164 +- python/shipStrawTracking.py | 1192 +- python/shipTarget_only.py | 87 +- python/shipVertex.py | 1014 +- python/shipVeto.py | 365 +- python/shipunit.py | 245 +- python/test_shipGeoConfig.py | 20 +- python/tweakConfig | 4 +- shipdata/CMakeLists.txt | 38 +- shipdata/ShipDetectorList.h | 27 +- shipdata/ShipGlobals.h | 7 +- shipdata/ShipHit.cxx | 24 +- shipdata/ShipHit.h | 32 +- shipdata/ShipMCTrack.cxx | 281 +- shipdata/ShipMCTrack.h | 106 +- shipdata/ShipParticle.cxx | 134 +- shipdata/ShipParticle.h | 78 +- shipdata/ShipStack.cxx | 695 +- shipdata/ShipStack.h | 159 +- shipdata/ShipUnit.h | 633 +- shipdata/TrackInfo.cxx | 50 +- shipdata/TrackInfo.h | 32 +- shipgen/CMakeLists.txt | 65 +- shipgen/CosmicsGenerator.cxx | 270 +- shipgen/CosmicsGenerator.h | 104 +- shipgen/DPPythia8Generator.cxx | 704 +- shipgen/DPPythia8Generator.h | 199 +- shipgen/EvtCalcGenerator.cxx | 135 +- shipgen/EvtCalcGenerator.h | 26 +- shipgen/FixedTargetGenerator.cxx | 758 +- shipgen/FixedTargetGenerator.h | 160 +- shipgen/GenieGenerator.cxx | 1036 +- shipgen/GenieGenerator.h | 98 +- shipgen/HNLPythia8Generator.cxx | 527 +- shipgen/HNLPythia8Generator.h | 159 +- shipgen/MuDISGenerator.cxx | 503 +- shipgen/MuDISGenerator.h | 76 +- shipgen/MuonBackGenerator.cxx | 439 +- shipgen/MuonBackGenerator.h | 86 +- shipgen/NtupleGenerator.cxx | 142 +- shipgen/NtupleGenerator.h | 57 +- shipgen/NuageGenerator.cxx | 1214 +- shipgen/NuageGenerator.h | 73 +- shipgen/Pythia6Generator.cxx | 185 +- shipgen/Pythia6Generator.h | 123 +- shipgen/Pythia8Generator.cxx | 527 +- shipgen/Pythia8Generator.h | 120 +- shipgen/branchingratios.dat | 503846 +++++++-------- shipgen/branchingratiosrpvsusybench1.dat | 12800 +- shipgen/branchingratiosrpvsusybench2.dat | 12800 +- shipgen/branchingratiosrpvsusybench3.dat | 12800 +- shipgen/branchingratiosrpvsusybench4.dat | 12800 +- shipgen/branchingratiosrpvsusybench5.dat | 25600 +- shipgen/tPythia6Generator.cxx | 112 +- shipgen/tPythia6Generator.h | 68 +- splitcal/CMakeLists.txt | 44 +- splitcal/splitcal.cxx | 627 +- splitcal/splitcal.h | 114 +- splitcal/splitcalCluster.cxx | 369 +- splitcal/splitcalCluster.h | 87 +- splitcal/splitcalContFact.cxx | 68 +- splitcal/splitcalContFact.h | 3 +- splitcal/splitcalHit.cxx | 326 +- splitcal/splitcalHit.h | 96 +- splitcal/splitcalPoint.cxx | 39 +- splitcal/splitcalPoint.h | 21 +- strawtubes/CMakeLists.txt | 46 +- strawtubes/Tracklet.cxx | 38 +- strawtubes/Tracklet.h | 39 +- strawtubes/strawtubes.cxx | 1518 +- strawtubes/strawtubes.h | 169 +- strawtubes/strawtubesContFact.cxx | 68 +- strawtubes/strawtubesContFact.h | 3 +- strawtubes/strawtubesHit.cxx | 168 +- strawtubes/strawtubesHit.h | 18 +- strawtubes/strawtubesPoint.cxx | 41 +- strawtubes/strawtubesPoint.h | 22 +- strawtubes/strawtubes_single.cxx | 932 +- utils/logger.hxx | 26 +- veto/CMakeLists.txt | 45 +- veto/veto.cxx | 2 +- veto/vetoHit.cxx | 1 - 360 files changed, 339307 insertions(+), 330277 deletions(-) mode change 100755 => 100644 gconfig/SetCuts.C mode change 100755 => 100644 gconfig/flConfig.C mode change 100755 => 100644 gconfig/fllibs.C mode change 100755 => 100644 gconfig/g3Config.C mode change 100755 => 100644 gconfig/g4Config.C diff --git a/CMakeLists.txt b/CMakeLists.txt index 0f4f82c8be..209c200fb2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,54 +1,57 @@ # The name of our project is "ShipRoot". CMakeLists files in this project can -# refer to the root source directory of the project as ${ShipRoot_SOURCE_DIR} -# or as ${CMAKE_SOURCE_DIR} and to the root binary directory of the project as -# ${ShipRoot_BINARY_DIR} or ${CMAKE_BINARY_DIR}. -# This difference is important for the base classes which are in FAIRROOT -# and ShipRoot. +# refer to the root source directory of the project as ${ShipRoot_SOURCE_DIR} or +# as ${CMAKE_SOURCE_DIR} and to the root binary directory of the project as +# ${ShipRoot_BINARY_DIR} or ${CMAKE_BINARY_DIR}. This difference is important +# for the base classes which are in FAIRROOT and ShipRoot. # Check if cmake has the required version -CMAKE_MINIMUM_REQUIRED(VERSION 3.12.0 FATAL_ERROR) +cmake_minimum_required(VERSION 3.12.0 FATAL_ERROR) -foreach(p - CMP0028 # double colon for imported and alias targets - CMP0074 # use _ROOT env variables - ) +foreach(p CMP0028 # double colon for imported and alias targets + CMP0074 # use _ROOT env variables +) if(POLICY ${p}) - cmake_policy(SET ${p} NEW) + cmake_policy(SET ${p} NEW) endif() endforeach() -# Set name of our project to "ShipRoot". Has to be done -# after check of cmake version since this is a new feature +# Set name of our project to "ShipRoot". Has to be done after check of cmake +# version since this is a new feature project(ShipRoot) -FIND_PATH(FAIRBASE NAMES FairRun.h PATHS - ${CMAKE_SOURCE_DIR}/base/steer - ${FAIRBASE} - NO_DEFAULT_PATH -) - -If (FAIRBASE) - Message(STATUS "Found FAIRBASE") - SET(FAIRBASE ${FAIRBASE}) -Else (FAIRBASE) - Message(STATUS "NOT Found FAIRBASE") - IF(NOT DEFINED ENV{FAIRROOTPATH}) - MESSAGE(FATAL_ERROR "You did not define the environment variable FAIRROOTPATH which is needed to find FairRoot. Please set this variable and execute cmake again.") - ENDIF(NOT DEFINED ENV{FAIRROOTPATH}) - SET(FAIRROOTPATH $ENV{FAIRROOTPATH}) -EndIf (FAIRBASE) - -# where to look first for cmake modules, before ${CMAKE_ROOT}/Modules/ -# is checked +find_path( + FAIRBASE + NAMES FairRun.h + PATHS ${CMAKE_SOURCE_DIR}/base/steer ${FAIRBASE} + NO_DEFAULT_PATH) + +if(FAIRBASE) + message(STATUS "Found FAIRBASE") + set(FAIRBASE ${FAIRBASE}) +else(FAIRBASE) + message(STATUS "NOT Found FAIRBASE") + if(NOT DEFINED ENV{FAIRROOTPATH}) + message( + FATAL_ERROR + "You did not define the environment variable FAIRROOTPATH which is needed to find FairRoot. Please set this variable and execute cmake again." + ) + endif(NOT DEFINED ENV{FAIRROOTPATH}) + set(FAIRROOTPATH $ENV{FAIRROOTPATH}) +endif(FAIRBASE) + +# where to look first for cmake modules, before ${CMAKE_ROOT}/Modules/ is +# checked set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake/modules") -set(CMAKE_MODULE_PATH "${FAIRROOTPATH}/share/fairbase/cmake/modules" ${CMAKE_MODULE_PATH}) -set(CMAKE_MODULE_PATH "${FAIRROOTPATH}/share/fairbase/cmake/modules_old" ${CMAKE_MODULE_PATH}) +set(CMAKE_MODULE_PATH "${FAIRROOTPATH}/share/fairbase/cmake/modules" + ${CMAKE_MODULE_PATH}) +set(CMAKE_MODULE_PATH "${FAIRROOTPATH}/share/fairbase/cmake/modules_old" + ${CMAKE_MODULE_PATH}) -IF(FAIRROOTPATH) - Set(CheckSrcDir "${FAIRROOTPATH}/share/fairbase/cmake/checks") -ELSE(FAIRROOTPATH) - Set(CheckSrcDir "${CMAKE_SOURCE_DIR}/cmake/checks") -ENDIF(FAIRROOTPATH) +if(FAIRROOTPATH) + set(CheckSrcDir "${FAIRROOTPATH}/share/fairbase/cmake/checks") +else(FAIRROOTPATH) + set(CheckSrcDir "${CMAKE_SOURCE_DIR}/cmake/checks") +endif(FAIRROOTPATH) # Load some basic macros which are needed later on include(FairMacros) @@ -56,66 +59,67 @@ include(WriteConfigFile) include(CTest) include(CheckCompiler) -#Check the compiler and set the compile and link flags -# change from DEBUG to RELEASE, don't want to waste CPU time -If(NOT CMAKE_BUILD_TYPE) - Message("Set BuildType RELEASE") +# Check the compiler and set the compile and link flags change from DEBUG to +# RELEASE, don't want to waste CPU time +if(NOT CMAKE_BUILD_TYPE) + message("Set BuildType RELEASE") set(CMAKE_BUILD_TYPE Release) -EndIf(NOT CMAKE_BUILD_TYPE) -Check_Compiler() +endif(NOT CMAKE_BUILD_TYPE) +check_compiler() set(LIBRARY_OUTPUT_PATH "${CMAKE_BINARY_DIR}/lib") set(EXECUTABLE_OUTPUT_PATH "${CMAKE_BINARY_DIR}/bin") set(INCLUDE_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/include") -Set(VMCWORKDIR ${ShipRoot_SOURCE_DIR}) -Option(USE_PATH_INFO "Information from PATH and LD_LIBRARY_PATH are +set(VMCWORKDIR ${ShipRoot_SOURCE_DIR}) +option(USE_PATH_INFO "Information from PATH and LD_LIBRARY_PATH are used." OFF) -Set(LD_LIBRARY_PATH $ENV{LD_LIBRARY_PATH}) -If(USE_PATH_INFO) - Set(PATH "$PATH") - If (APPLE) - Set(LD_LIBRARY_PATH $ENV{DYLD_LIBRARY_PATH}) - Else (APPLE) - Set(LD_LIBRARY_PATH $ENV{LD_LIBRARY_PATH}) - EndIf (APPLE) -Else(USE_PATH_INFO) - STRING(REGEX MATCHALL "[^:]+" PATH $ENV{PATH}) -EndIf(USE_PATH_INFO) - -#--------------------- set rpath options ------------- +set(LD_LIBRARY_PATH $ENV{LD_LIBRARY_PATH}) +if(USE_PATH_INFO) + set(PATH "$PATH") + if(APPLE) + set(LD_LIBRARY_PATH $ENV{DYLD_LIBRARY_PATH}) + else(APPLE) + set(LD_LIBRARY_PATH $ENV{LD_LIBRARY_PATH}) + endif(APPLE) +else(USE_PATH_INFO) + string(REGEX MATCHALL "[^:]+" PATH $ENV{PATH}) +endif(USE_PATH_INFO) + +# --------------------- set rpath options ------------- # When building, use the RPATH -set(CMAKE_SKIP_BUILD_RPATH FALSE) # don't skip the full RPATH for the build tree -set(CMAKE_BUILD_WITH_INSTALL_RPATH FALSE) # use always the build RPATH for the build tree -set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE) # point to directories outside the build tree to the install RPATH +set(CMAKE_SKIP_BUILD_RPATH FALSE) # don't skip the full RPATH for the build tree +set(CMAKE_BUILD_WITH_INSTALL_RPATH FALSE) # use always the build RPATH for the + # build tree +set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE) # point to directories outside the + # build tree to the install RPATH if(APPLE) - set(CMAKE_MACOSX_RPATH TRUE) # use RPATH for MacOSX + set(CMAKE_MACOSX_RPATH TRUE) # use RPATH for MacOSX set(CMAKE_INSTALL_NAME_DIR "@rpath") - set(CMAKE_INSTALL_RPATH "@loader_path/") # self relative LIBDIR + set(CMAKE_INSTALL_RPATH "@loader_path/") # self relative LIBDIR else() set(CMAKE_INSTALL_RPATH ${CMAKE_INSTALL_FULL_LIBDIR}) # install LIBDIR endif() -#------------------- end set rpath options ----------- +# ------------------- end set rpath options ----------- -# Check if the user wants to build the project in the source -# directory -CHECK_OUT_OF_SOURCE_BUILD() +# Check if the user wants to build the project in the source directory +check_out_of_source_build() -# Check if we are on an UNIX system. If not stop with an error -# message -IF(NOT UNIX) - MESSAGE(FATAL_ERROR "You're not on an UNIX system. The project was up to now only tested on UNIX systems, so we break here. If you want to go on please edit the CMakeLists.txt in the source directory.") -ENDIF(NOT UNIX) +# Check if we are on an UNIX system. If not stop with an error message +if(NOT UNIX) + message( + FATAL_ERROR + "You're not on an UNIX system. The project was up to now only tested on UNIX systems, so we break here. If you want to go on please edit the CMakeLists.txt in the source directory." + ) +endif(NOT UNIX) -# Set the build type. Possibilities are None, Debug, Release, -# RelWithDebInfo and MinSizeRel -#SET(CMAKE_BUILD_TYPE Debug) +# Set the build type. Possibilities are None, Debug, Release, RelWithDebInfo and +# MinSizeRel SET(CMAKE_BUILD_TYPE Debug) -# searches for needed packages -# REQUIRED means that cmake will stop if this packages are not found -# For example the framework can run without GEANT4, but ROOT is -# mandatory +# searches for needed packages REQUIRED means that cmake will stop if this +# packages are not found For example the framework can run without GEANT4, but +# ROOT is mandatory find_package(FairCMakeModules 1.0 REQUIRED) include(FairFindPackage2) @@ -134,119 +138,121 @@ find_package2(PUBLIC FairLogger REQUIRED) find_package2(PUBLIC VMC REQUIRED) find_package(genfit2 REQUIRED) -IF(DEFINED ${BOOST_ROOT}) - Set(Boost_NO_SYSTEM_PATHS TRUE) - Set(Boost_NO_BOOST_CMAKE TRUE) -ENDIF(DEFINED ${BOOST_ROOT}) -# set(Boost_DEBUG TRUE) -IF(DEFINED ${BOOST_ROOT}) - set(BOOST_ROOT $ENV{BOOST_ROOT}) -ENDIF(DEFINED ${BOOST_ROOT}) -IF(DEFINED $ENV{GSL_ROOT}) - set(GSL_DIR $ENV{GSL_ROOT}) -ENDIF(DEFINED $ENV{GSL_ROOT}) +if(DEFINED ${BOOST_ROOT}) + set(Boost_NO_SYSTEM_PATHS TRUE) + set(Boost_NO_BOOST_CMAKE TRUE) +endif(DEFINED ${BOOST_ROOT}) +# set(Boost_DEBUG TRUE) +if(DEFINED ${BOOST_ROOT}) + set(BOOST_ROOT $ENV{BOOST_ROOT}) +endif(DEFINED ${BOOST_ROOT}) +if(DEFINED $ENV{GSL_ROOT}) + set(GSL_DIR $ENV{GSL_ROOT}) +endif(DEFINED $ENV{GSL_ROOT}) find_package(Boost 1.70 REQUIRED) -# set a variable which should be used in all CMakeLists.txt -# Defines all basic include directories from fairbase - Message("-- Setting basic variables ...") -SetBasicVariables() +# set a variable which should be used in all CMakeLists.txt Defines all basic +# include directories from fairbase +message("-- Setting basic variables ...") +setbasicvariables() # Add the FairRoot include directories to the list of libraries which are # external to the Ship project. For include directories in this list the # compiler will not generate any warnings. This is usefull since one is only -# interested about warnings from the own project. SYSTEM_INCLUDE_DIRECTORIES -# is defined in FairMacros.cmake. In the moment the defined directories are -# the root and boost include directories. -Set(SYSTEM_INCLUDE_DIRECTORIES - ${SYSTEM_INCLUDE_DIRECTORIES} - ${BASE_INCLUDE_DIRECTORIES} -) +# interested about warnings from the own project. SYSTEM_INCLUDE_DIRECTORIES is +# defined in FairMacros.cmake. In the moment the defined directories are the +# root and boost include directories. +set(SYSTEM_INCLUDE_DIRECTORIES ${SYSTEM_INCLUDE_DIRECTORIES} + ${BASE_INCLUDE_DIRECTORIES}) # Set the library version in the main CMakeLists.txt -SET(FAIRROOT_MAJOR_VERSION 0) -SET(FAIRROOT_MINOR_VERSION 0) -SET(FAIRROOT_PATCH_VERSION 0) -SET(FAIRROOT_VERSION "${FAIRROOT_MAJOR_VERSION}.${FAIRROOT_MINOR_VERSION}.${FAIRROOT_PATCH_VERSION}") - -set(FAIRROOT_LIBRARY_PROPERTIES ${FAIRROOT_LIBRARY_PROPERTIES} - VERSION "${FAIRROOT_VERSION}" - SOVERSION "${FAIRROOT_MAJOR_VERSION}" +set(FAIRROOT_MAJOR_VERSION 0) +set(FAIRROOT_MINOR_VERSION 0) +set(FAIRROOT_PATCH_VERSION 0) +set(FAIRROOT_VERSION + "${FAIRROOT_MAJOR_VERSION}.${FAIRROOT_MINOR_VERSION}.${FAIRROOT_PATCH_VERSION}" ) + +set(FAIRROOT_LIBRARY_PROPERTIES + ${FAIRROOT_LIBRARY_PROPERTIES} VERSION "${FAIRROOT_VERSION}" SOVERSION + "${FAIRROOT_MAJOR_VERSION}") set(CMAKE_SHARED_LIBRARY_SUFFIX .so) -SET(CBMLIBDIR ${CMAKE_BINARY_DIR}/lib) -SET(LD_LIBRARY_PATH ${CBMLIBDIR} ${LD_LIBRARY_PATH}) +set(CBMLIBDIR ${CMAKE_BINARY_DIR}/lib) +set(LD_LIBRARY_PATH ${CBMLIBDIR} ${LD_LIBRARY_PATH}) -#IF(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) -# SET(CMAKE_INSTALL_PREFIX "./install" CACHE PATH "FOO install prefix" FORCE) -# Message("Set default install path ...") -#ENDIF(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) +# IF(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) SET(CMAKE_INSTALL_PREFIX +# "./install" CACHE PATH "FOO install prefix" FORCE) Message("Set default +# install path ...") ENDIF(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) -install(DIRECTORY geometry DESTINATION pnd_install - PATTERN ".svn" EXCLUDE - ) +install( + DIRECTORY geometry + DESTINATION pnd_install + PATTERN ".svn" EXCLUDE) -Message("-- Set check directory to FairRoot...") -Set(CheckSrcDir "${FAIRROOTPATH}/share/fairbase/cmake/checks") +message("-- Set check directory to FairRoot...") +set(CheckSrcDir "${FAIRROOTPATH}/share/fairbase/cmake/checks") # Set(CheckSrcDir "${CMAKE_SOURCE_DIR}/cmake/checks") # --------------- add targets for code style and submission checks ------------- find_package(Git) find_package(ClangTools) -if ("$ENV{CMAKE_EXPORT_COMPILE_COMMANDS}" STREQUAL "1" OR CLANG_TIDY_FOUND) +if("$ENV{CMAKE_EXPORT_COMPILE_COMMANDS}" STREQUAL "1" OR CLANG_TIDY_FOUND) # Generate a Clang compile_commands.json "compilation database" file for use - # with various development tools, such as Vim's YouCompleteMe plugin. - # See http://clang.llvm.org/docs/JSONCompilationDatabase.html + # with various development tools, such as Vim's YouCompleteMe plugin. See + # http://clang.llvm.org/docs/JSONCompilationDatabase.html set(CMAKE_EXPORT_COMPILE_COMMANDS 1) endif() include(CppStyleGuideChecks) -# Recurse into the given subdirectories. This does not actually -# cause another cmake executable to run. The same process will walk through -# the project's entire directory structure. - -IF(NOT FairRoot_FOUND) -Message("--- FairRoot not found ...") -ENDIF (NOT FairRoot_FOUND) - -add_subdirectory (shipdata) -add_subdirectory (passive) -add_subdirectory (nutaudet) -add_subdirectory (ecal) -add_subdirectory (splitcal) -add_subdirectory (hcal) -add_subdirectory (veto) -add_subdirectory (TimeDet) -add_subdirectory (UpstreamTagger) -add_subdirectory (strawtubes) -add_subdirectory (muon) -add_subdirectory (shipgen) -add_subdirectory (field) -add_subdirectory (pid) -add_subdirectory (muonShieldOptimization) - -FIND_PATH(TEvePath NAMES TEveEventManager.h PATHS - ${SIMPATH}/tools/root/include - ${SIMPATH}/include/root - $ENV{ROOTSYS}/include/root - NO_DEFAULT_PATH -) - -If(TEvePath) -#find_package(OpenGL) -#If (OPENGL_FOUND AND OPENGL_GLU_FOUND) - Message("Found TEve, so the eventdisplay will be compiled.") - - IF(NOT FAIRROOT_FOUND) - add_subdirectory (eventdisplay) - ENDIF(NOT FAIRROOT_FOUND) - -EndIf(TEvePath) - -add_custom_target( # make relative links to folders - geometry.link ALL - COMMAND [ -e geometry ] || python -c \"import os.path as p, os\; os.symlink(p.join(p.relpath('${CMAKE_SOURCE_DIR}', '${CMAKE_BINARY_DIR}') , 'geometry') , 'geometry') \" - COMMAND [ -e macro ] || python -c \"import os.path as p, os\; os.symlink(p.join(p.relpath('${CMAKE_SOURCE_DIR}', '${CMAKE_BINARY_DIR}') , 'macro') , 'macro') \" -) +# Recurse into the given subdirectories. This does not actually cause another +# cmake executable to run. The same process will walk through the project's +# entire directory structure. + +if(NOT FairRoot_FOUND) + message("--- FairRoot not found ...") +endif(NOT FairRoot_FOUND) + +add_subdirectory(shipdata) +add_subdirectory(passive) +add_subdirectory(nutaudet) +add_subdirectory(ecal) +add_subdirectory(splitcal) +add_subdirectory(hcal) +add_subdirectory(veto) +add_subdirectory(TimeDet) +add_subdirectory(UpstreamTagger) +add_subdirectory(strawtubes) +add_subdirectory(muon) +add_subdirectory(shipgen) +add_subdirectory(field) +add_subdirectory(pid) +add_subdirectory(muonShieldOptimization) + +find_path( + TEvePath + NAMES TEveEventManager.h + PATHS ${SIMPATH}/tools/root/include ${SIMPATH}/include/root + $ENV{ROOTSYS}/include/root + NO_DEFAULT_PATH) + +if(TEvePath) + # find_package(OpenGL) If (OPENGL_FOUND AND OPENGL_GLU_FOUND) + message("Found TEve, so the eventdisplay will be compiled.") + + if(NOT FAIRROOT_FOUND) + add_subdirectory(eventdisplay) + endif(NOT FAIRROOT_FOUND) + +endif(TEvePath) + +add_custom_target( + # make relative links to folders + geometry.link ALL + COMMAND [ -e geometry ] || python -c \"import os.path as p, os\; os.symlink + (p.join (p.relpath ('${CMAKE_SOURCE_DIR}', '${CMAKE_BINARY_DIR}') , + 'geometry') , 'geometry') \" + COMMAND [ -e macro ] || python -c \"import os.path as p, os\; os.symlink + (p.join (p.relpath ('${CMAKE_SOURCE_DIR}', '${CMAKE_BINARY_DIR}') , + 'macro') , 'macro') \") diff --git a/CTestConfig.cmake b/CTestConfig.cmake index fa22a30847..986b1bc132 100644 --- a/CTestConfig.cmake +++ b/CTestConfig.cmake @@ -1,5 +1,5 @@ -# Dashboard is opened for submissions for a 24 hour period starting at -# the specified NIGHLY_START_TIME. Time is specified in 24 hour format. +# Dashboard is opened for submissions for a 24 hour period starting at the +# specified NIGHLY_START_TIME. Time is specified in 24 hour format. set(CTEST_PROJECT_NAME "PandaRoot") set(CTEST_NIGHTLY_START_TIME "00:00:00 CEST") @@ -7,6 +7,6 @@ set(CTEST_DROP_METHOD "http") set(CTEST_DROP_SITE "cdash.gsi.de") set(CTEST_DROP_LOCATION "/CDash/submit.php?project=PandaRoot") set(CTEST_DROP_SITE_CDASH TRUE) -#set(CTEST_TRIGGER_SITE "") +# set(CTEST_TRIGGER_SITE "") set(CTEST_TESTING_TIMEOUT 300) diff --git a/CTestCustom.cmake b/CTestCustom.cmake index 8df6f3f691..c14d7d2ee0 100644 --- a/CTestCustom.cmake +++ b/CTestCustom.cmake @@ -1,124 +1,105 @@ # -*- mode: cmake -*- -#message(" -- Read CTestCustom.cmake --") +# message(" -- Read CTestCustom.cmake --") # ----------------------------------------------------------- # -- Number of warnings to display # ----------------------------------------------------------- -set(CTEST_CUSTOM_MAXIMUM_NUMBER_OF_WARNINGS "500" ) +set(CTEST_CUSTOM_MAXIMUM_NUMBER_OF_WARNINGS "500") # ----------------------------------------------------------- # -- Number of errors to display # ----------------------------------------------------------- -set(CTEST_CUSTOM_MAXIMUM_NUMBER_OF_ERRORS "50" ) +set(CTEST_CUSTOM_MAXIMUM_NUMBER_OF_ERRORS "50") -set(CTEST_CUSTOM_ERROR_EXCEPTION - ${CTEST_CUSTOM_ERROR_EXCEPTION} - "Warnung: " - "Anmerkung: " -) +set(CTEST_CUSTOM_ERROR_EXCEPTION ${CTEST_CUSTOM_ERROR_EXCEPTION} "Warnung: " + "Anmerkung: ") # ----------------------------------------------------------- # -- Warning execptions # ----------------------------------------------------------- set(CTEST_CUSTOM_WARNING_EXCEPTION - ${CTEST_CUSTOM_WARNING_EXCEPTION} - - # -- doxygen warnings -# "of command \@param is not found in the argument list of" -# "for \\link command" -# "for \\ref command" -# "\\class statement" -# "\\file statement" -# "are not documented:" -# "Skipping documentation" -# "has a brief description" - - # -- CLHEP and Pluto warnings - "/include/CLHEP/" - "PParticle.h" - "PDataBase.h" - "PMesh.h" - "PStaticData.h" - "PUtils.h" - - # -- warnings from ubuntu systems which are a little to much - # -- probably defined warn-unused-result. ignoring the result - # -- of fgets is common practice. A work around would be to - # -- store the return value in a dummy variable - "ignoring return value of 'char* fgets(char*, int, FILE*)'" - "ignoring return value of 'char* fscanf(char*, int, FILE*)'" - - # -- boost warnings - "/include/boost/exception/exception.hpp:" - "/include/boost/smart_ptr/detail/sp_convertible.hpp:" - "/include/boost/smart_ptr/shared_ptr.hpp:" - - # -- Root warnings when installed in installation dir - "/include/root/" - # -- Root warnings which should not show up in the test setup - "/include/G__ci.h:" - "/include/TAttImage.h:" - "/include/TBuffer.h" - "/include/TChainElement.h" - "/include/TCollectionProxyInfo.h" - "/include/TCut.h:" - "/include/TEveBoxSet.h:" - "/include/TEveTrackPropagator.h:" - "/include/TEveTrackPropagator.h:" - "/include/TEveVector.h:" - "/include/TFcnAdapter.h:" - "/include/TFitterMinuit.h:" - "/include/TGeoMatrix.h:" - "/include/TGeoPainter.h:" - "/include/TGDMLParse.h" - "/include/TList.h:" - "/include/TMap.h:" - "/include/TMatrixT.h:" - "/include/TMatrixTSym.h:" - "/include/TMemberInspector.h:" - "/include/TObjArray.h:" - "/include/TRefArray.h:" - "/include/TString.h" - "/include/Minuit2/BasicFunctionGradient.h:" - "/include/Minuit2/MnUserParameterState.h:" - "/include/Minuit2/StackAllocator.h:" - "/include/TMVA/ClassInfo.h:" - "/include/TMVA/Config.h:" - "/include/TMVA/Configurable.h:" - "/include/TMVA/DataInputHandler.h:" - "/include/TMVA/DataSet.h:" - "/include/TMVA/DataSetInfo.h:" - "/include/TMVA/DataSetManager.h:" - "/include/TMVA/Event.h:" - "/include/TMVA/Factory.h:" - "/include/TMVA/KDEKernel.h:" - "/include/TMVA/Option.h:" - "/include/TMVA/PDF.h:" - "/include/TMVA/Reader.h:" - "/include/TMVA/Types.h:" - - # -- Geant3 warnings - "TGeant3/TGeant3.h:" - "TGeant3/TGeant3TGeo.h:" - - # -- Errors which are filtered for the time being - # -- MbsAPI is only a copy from elsewhere so don't know what to do - # -- FairTSBufferFunctional.h has to be fixed by Tobias - "MbsAPI" -# "FairTSBufferFunctional.h" - ) + ${CTEST_CUSTOM_WARNING_EXCEPTION} + # -- doxygen warnings + # "of command \@param is not found in the argument list of" "for \\link + # command" "for \\ref command" "\\class statement" "\\file statement" "are + # not documented:" "Skipping documentation" "has a brief description" + # -- CLHEP and Pluto warnings + "/include/CLHEP/" + "PParticle.h" + "PDataBase.h" + "PMesh.h" + "PStaticData.h" + "PUtils.h" + # -- warnings from ubuntu systems which are a little to much -- probably + # defined warn-unused-result. ignoring the result -- of fgets is common + # practice. A work around would be to -- store the return value in a dummy + # variable + "ignoring return value of 'char* fgets(char*, int, FILE*)'" + "ignoring return value of 'char* fscanf(char*, int, FILE*)'" + # -- boost warnings + "/include/boost/exception/exception.hpp:" + "/include/boost/smart_ptr/detail/sp_convertible.hpp:" + "/include/boost/smart_ptr/shared_ptr.hpp:" + # -- Root warnings when installed in installation dir + "/include/root/" + # -- Root warnings which should not show up in the test setup + "/include/G__ci.h:" + "/include/TAttImage.h:" + "/include/TBuffer.h" + "/include/TChainElement.h" + "/include/TCollectionProxyInfo.h" + "/include/TCut.h:" + "/include/TEveBoxSet.h:" + "/include/TEveTrackPropagator.h:" + "/include/TEveTrackPropagator.h:" + "/include/TEveVector.h:" + "/include/TFcnAdapter.h:" + "/include/TFitterMinuit.h:" + "/include/TGeoMatrix.h:" + "/include/TGeoPainter.h:" + "/include/TGDMLParse.h" + "/include/TList.h:" + "/include/TMap.h:" + "/include/TMatrixT.h:" + "/include/TMatrixTSym.h:" + "/include/TMemberInspector.h:" + "/include/TObjArray.h:" + "/include/TRefArray.h:" + "/include/TString.h" + "/include/Minuit2/BasicFunctionGradient.h:" + "/include/Minuit2/MnUserParameterState.h:" + "/include/Minuit2/StackAllocator.h:" + "/include/TMVA/ClassInfo.h:" + "/include/TMVA/Config.h:" + "/include/TMVA/Configurable.h:" + "/include/TMVA/DataInputHandler.h:" + "/include/TMVA/DataSet.h:" + "/include/TMVA/DataSetInfo.h:" + "/include/TMVA/DataSetManager.h:" + "/include/TMVA/Event.h:" + "/include/TMVA/Factory.h:" + "/include/TMVA/KDEKernel.h:" + "/include/TMVA/Option.h:" + "/include/TMVA/PDF.h:" + "/include/TMVA/Reader.h:" + "/include/TMVA/Types.h:" + # -- Geant3 warnings + "TGeant3/TGeant3.h:" + "TGeant3/TGeant3TGeo.h:" + # -- Errors which are filtered for the time being -- MbsAPI is only a copy + # from elsewhere so don't know what to do -- FairTSBufferFunctional.h has to + # be fixed by Tobias + "MbsAPI" + # "FairTSBufferFunctional.h" +) # ----------------------------------------------------------- # -- Warning addon's # ----------------------------------------------------------- -set(CTEST_CUSTOM_WARNING_MATCH ${CTEST_CUSTOM_WARNING_MATCH} - ) +set(CTEST_CUSTOM_WARNING_MATCH ${CTEST_CUSTOM_WARNING_MATCH}) -Set (CTEST_CUSTOM_COVERAGE_EXCLUDE - "Dict.h" - "Dict.cxx" - ) +set(CTEST_CUSTOM_COVERAGE_EXCLUDE "Dict.h" "Dict.cxx") diff --git a/TimeDet/CMakeLists.txt b/TimeDet/CMakeLists.txt index 35bc70f1aa..f2a176bc3a 100644 --- a/TimeDet/CMakeLists.txt +++ b/TimeDet/CMakeLists.txt @@ -1,35 +1,24 @@ # Create a library called "libTimeDet" which includes the source files given in -# the array . -# The extension is already found. Any number of sources could be listed here. +# the array . The extension is already found. Any number of sources could be +# listed here. -set(INCLUDE_DIRECTORIES -${CMAKE_SOURCE_DIR}/shipdata -${CMAKE_SOURCE_DIR}/TimeDet -${genfit2_INCDIR} -) +set(INCLUDE_DIRECTORIES ${CMAKE_SOURCE_DIR}/shipdata + ${CMAKE_SOURCE_DIR}/TimeDet ${genfit2_INCDIR}) -include_directories(${INCLUDE_DIRECTORIES} ${VMC_INCLUDE_DIRS} ${FAIRROOT_INCLUDE_DIR}) +include_directories(${INCLUDE_DIRECTORIES} ${VMC_INCLUDE_DIRS} + ${FAIRROOT_INCLUDE_DIR}) include_directories(SYSTEM ${SYSTEM_INCLUDE_DIRECTORIES}) -set(LINK_DIRECTORIES -${ROOT_LIBRARY_DIR} -${FAIRROOT_LIBRARY_DIR} -${genfit2_LIBDIR} -) +set(LINK_DIRECTORIES ${ROOT_LIBRARY_DIR} ${FAIRROOT_LIBRARY_DIR} + ${genfit2_LIBDIR}) -link_directories( ${LINK_DIRECTORIES}) +link_directories(${LINK_DIRECTORIES}) -set(SRCS -#Put here your sourcefiles -TimeDetPoint.cxx -TimeDetHit.cxx -TimeDet.cxx -) +set(SRCS # Put here your sourcefiles + TimeDetPoint.cxx TimeDetHit.cxx TimeDet.cxx) -Set(LINKDEF TimeDetLinkDef.h) -Set(LIBRARY_NAME TimeDet) -Set(DEPENDENCIES - Base ShipData FairLogger::FairLogger -) +set(LINKDEF TimeDetLinkDef.h) +set(LIBRARY_NAME TimeDet) +set(DEPENDENCIES Base ShipData FairLogger::FairLogger) -GENERATE_LIBRARY() +generate_library() diff --git a/TimeDet/TimeDet.cxx b/TimeDet/TimeDet.cxx index 91de280db5..b9863fde1f 100644 --- a/TimeDet/TimeDet.cxx +++ b/TimeDet/TimeDet.cxx @@ -3,322 +3,328 @@ // Alexander.Korzenev@cern.ch #include "TimeDet.h" -#include "TimeDetPoint.h" -#include "FairVolume.h" -#include "FairGeoVolume.h" -#include "FairGeoNode.h" -#include "FairRootManager.h" -#include "FairGeoLoader.h" +#include "FairGeoBuilder.h" #include "FairGeoInterface.h" +#include "FairGeoLoader.h" #include "FairGeoMedia.h" -#include "FairGeoBuilder.h" +#include "FairGeoNode.h" +#include "FairGeoVolume.h" +#include "FairRootManager.h" #include "FairRun.h" #include "FairRuntimeDb.h" +#include "FairVolume.h" #include "ShipDetectorList.h" #include "ShipStack.h" - #include "TClonesArray.h" -#include "TVirtualMC.h" -#include "TGeoManager.h" #include "TGeoBBox.h" #include "TGeoCompositeShape.h" -#include "TGeoTube.h" +#include "TGeoManager.h" #include "TGeoMaterial.h" #include "TGeoMedium.h" +#include "TGeoTube.h" #include "TMath.h" #include "TParticle.h" #include "TVector3.h" +#include "TVirtualMC.h" +#include "TimeDetPoint.h" #include #include using std::cout; using std::endl; - TimeDet::TimeDet() - : FairDetector("TimeDet", kTRUE, kTimeDet), - fTrackID(-1), - fVolumeID(-1), - fPos(), - fMom(), - fTime(-1.), - fLength(-1.), - fELoss(-1), + : FairDetector("TimeDet", kTRUE, kTimeDet) + , fTrackID(-1) + , fVolumeID(-1) + , fPos() + , fMom() + , fTime(-1.) + , fLength(-1.) + , fELoss(-1) + , // - fzPos(0), - fxSize(450), - fySize(650), - fxBar(168), - fyBar(6), - fzBar(1), - fdzBarCol(2.4), - fdzBarRow(1.2), - fNCol(3), - fNRow(148), - fxCenter(0), - fyCenter(0), + fzPos(0) + , fxSize(450) + , fySize(650) + , fxBar(168) + , fyBar(6) + , fzBar(1) + , fdzBarCol(2.4) + , fdzBarRow(1.2) + , fNCol(3) + , fNRow(148) + , fxCenter(0) + , fyCenter(0) + , // - fDetector(0), + fDetector(0) + , // fTimeDetPointCollection(new TClonesArray("TimeDetPoint")) { - fNBars = fNCol * fNRow; - if(fNCol>1) fxOv = (fxBar*fNCol - fxSize) / (double)(fNCol-1); else fxOv = 0; - if(fNRow>1) fyOv = (fyBar*fNRow - fySize) / (double)(fNRow-1); else fyOv = 0; + fNBars = fNCol * fNRow; + if (fNCol > 1) + fxOv = (fxBar * fNCol - fxSize) / (double)(fNCol - 1); + else + fxOv = 0; + if (fNRow > 1) + fyOv = (fyBar * fNRow - fySize) / (double)(fNRow - 1); + else + fyOv = 0; } - - TimeDet::TimeDet(const char* name, Bool_t active) - : FairDetector(name, active, kTimeDet), - fTrackID(-1), - fVolumeID(-1), - fPos(), - fMom(), - fTime(-1.), - fLength(-1.), - fELoss(-1), + : FairDetector(name, active, kTimeDet) + , fTrackID(-1) + , fVolumeID(-1) + , fPos() + , fMom() + , fTime(-1.) + , fLength(-1.) + , fELoss(-1) + , // - fzPos(0), - fxSize(450), - fySize(650), - fxBar(168), - fyBar(6), - fzBar(1), - fdzBarCol(2.4), - fdzBarRow(1.2), - fNCol(3), - fNRow(148), - fxCenter(0), - fyCenter(0), + fzPos(0) + , fxSize(450) + , fySize(650) + , fxBar(168) + , fyBar(6) + , fzBar(1) + , fdzBarCol(2.4) + , fdzBarRow(1.2) + , fNCol(3) + , fNRow(148) + , fxCenter(0) + , fyCenter(0) + , // - fDetector(0), + fDetector(0) + , // fTimeDetPointCollection(new TClonesArray("TimeDetPoint")) { - fNBars = fNCol * fNRow; - if(fNCol>1) fxOv = (fxBar*fNCol - fxSize) / (double)(fNCol-1); else fxOv = 0; - if(fNRow>1) fyOv = (fyBar*fNRow - fySize) / (double)(fNRow-1); else fyOv = 0; - + fNBars = fNCol * fNRow; + if (fNCol > 1) + fxOv = (fxBar * fNCol - fxSize) / (double)(fNCol - 1); + else + fxOv = 0; + if (fNRow > 1) + fyOv = (fyBar * fNRow - fySize) / (double)(fNRow - 1); + else + fyOv = 0; } void TimeDet::Initialize() { - FairDetector::Initialize(); + FairDetector::Initialize(); } - TimeDet::~TimeDet() { - if (fTimeDetPointCollection) { - fTimeDetPointCollection->Delete(); - delete fTimeDetPointCollection; - } + if (fTimeDetPointCollection) { + fTimeDetPointCollection->Delete(); + delete fTimeDetPointCollection; + } } - - Int_t TimeDet::InitMedium(const char* name) { - static FairGeoLoader *geoLoad=FairGeoLoader::Instance(); - static FairGeoInterface *geoFace=geoLoad->getGeoInterface(); - static FairGeoMedia *media=geoFace->getMedia(); - static FairGeoBuilder *geoBuild=geoLoad->getGeoBuilder(); + static FairGeoLoader* geoLoad = FairGeoLoader::Instance(); + static FairGeoInterface* geoFace = geoLoad->getGeoInterface(); + static FairGeoMedia* media = geoFace->getMedia(); + static FairGeoBuilder* geoBuild = geoLoad->getGeoBuilder(); - FairGeoMedium *ShipMedium=media->getMedium(name); + FairGeoMedium* ShipMedium = media->getMedium(name); - if (!ShipMedium) - { - Fatal("InitMedium","Material %s not defined in media file.", name); - return -1111; - } - TGeoMedium* medium=gGeoManager->GetMedium(name); - if (medium!=NULL) - return ShipMedium->getMediumIndex(); + if (!ShipMedium) { + Fatal("InitMedium", "Material %s not defined in media file.", name); + return -1111; + } + TGeoMedium* medium = gGeoManager->GetMedium(name); + if (medium != NULL) + return ShipMedium->getMediumIndex(); - return geoBuild->createMedium(ShipMedium); + return geoBuild->createMedium(ShipMedium); - return 0; + return 0; } - - -Bool_t TimeDet::ProcessHits(FairVolume* vol) +Bool_t TimeDet::ProcessHits(FairVolume* vol) { - /** This method is called from the MC stepping */ - //Set parameters at entrance of volume. Reset ELoss. - if ( gMC->IsTrackEntering() ) { - fELoss = 0.; - fTime = gMC->TrackTime() * 1.0e09; - fLength = gMC->TrackLength(); - gMC->TrackPosition(fPos); - gMC->TrackMomentum(fMom); - } - - // Sum energy loss for all steps in the active volume - fELoss += gMC->Edep(); - - // Create vetoPoint at exit of active volume - if ( gMC->IsTrackExiting() || - gMC->IsTrackStop() || - gMC->IsTrackDisappeared() ) { - if (fELoss == 0. ) { return kFALSE; } - - fTrackID = gMC->GetStack()->GetCurrentTrackNumber(); - - Int_t uniqueId; - gMC->CurrentVolID(uniqueId); - if (uniqueId>1000000) //Solid scintillator case - { - Int_t vcpy; - gMC->CurrentVolOffID(1, vcpy); - if (vcpy==5) uniqueId+=4; //Copy of half + /** This method is called from the MC stepping */ + // Set parameters at entrance of volume. Reset ELoss. + if (gMC->IsTrackEntering()) { + fELoss = 0.; + fTime = gMC->TrackTime() * 1.0e09; + fLength = gMC->TrackLength(); + gMC->TrackPosition(fPos); + gMC->TrackMomentum(fMom); } - TParticle* p = gMC->GetStack()->GetCurrentTrack(); - Int_t pdgCode = p->GetPdgCode(); - TLorentzVector Pos; - gMC->TrackPosition(Pos); - TLorentzVector Mom; - gMC->TrackMomentum(Mom); - Double_t xmean = (fPos.X()+Pos.X())/2. ; - Double_t ymean = (fPos.Y()+Pos.Y())/2. ; - Double_t zmean = (fPos.Z()+Pos.Z())/2. ; - - //cout << uniqueId << " :(" << xmean << ", " << ymean << ", " << zmean << "): " << gMC->CurrentVolName() << endl; - - AddHit(fTrackID, uniqueId, TVector3(xmean, ymean, zmean), - TVector3(fMom.Px(), fMom.Py(), fMom.Pz()), fTime, fLength, - fELoss,pdgCode,TVector3(Pos.X(), Pos.Y(), Pos.Z()), - TVector3(Mom.Px(), Mom.Py(), Mom.Pz()) ); - - // Increment number of veto det points in TParticle - ShipStack* stack = (ShipStack*) gMC->GetStack(); - stack->AddPoint(kTimeDet); - } - - return kTRUE; -} - + // Sum energy loss for all steps in the active volume + fELoss += gMC->Edep(); + + // Create vetoPoint at exit of active volume + if (gMC->IsTrackExiting() || gMC->IsTrackStop() || gMC->IsTrackDisappeared()) { + if (fELoss == 0.) { + return kFALSE; + } + + fTrackID = gMC->GetStack()->GetCurrentTrackNumber(); + + Int_t uniqueId; + gMC->CurrentVolID(uniqueId); + if (uniqueId > 1000000) // Solid scintillator case + { + Int_t vcpy; + gMC->CurrentVolOffID(1, vcpy); + if (vcpy == 5) + uniqueId += 4; // Copy of half + } + + TParticle* p = gMC->GetStack()->GetCurrentTrack(); + Int_t pdgCode = p->GetPdgCode(); + TLorentzVector Pos; + gMC->TrackPosition(Pos); + TLorentzVector Mom; + gMC->TrackMomentum(Mom); + Double_t xmean = (fPos.X() + Pos.X()) / 2.; + Double_t ymean = (fPos.Y() + Pos.Y()) / 2.; + Double_t zmean = (fPos.Z() + Pos.Z()) / 2.; + + // cout << uniqueId << " :(" << xmean << ", " << ymean << ", " << zmean << "): " << gMC->CurrentVolName() << + // endl; + + AddHit(fTrackID, + uniqueId, + TVector3(xmean, ymean, zmean), + TVector3(fMom.Px(), fMom.Py(), fMom.Pz()), + fTime, + fLength, + fELoss, + pdgCode, + TVector3(Pos.X(), Pos.Y(), Pos.Z()), + TVector3(Mom.Px(), Mom.Py(), Mom.Pz())); + + // Increment number of veto det points in TParticle + ShipStack* stack = (ShipStack*)gMC->GetStack(); + stack->AddPoint(kTimeDet); + } + return kTRUE; +} void TimeDet::EndOfEvent() { - fTimeDetPointCollection->Clear(); + fTimeDetPointCollection->Clear(); } - - void TimeDet::Register() { - /** This will create a branch in the output tree called - TimeDetPoint, setting the last parameter to kFALSE means: - this collection will not be written to the file, it will exist - only during the simulation. - */ + /** This will create a branch in the output tree called + TimeDetPoint, setting the last parameter to kFALSE means: + this collection will not be written to the file, it will exist + only during the simulation. + */ - FairRootManager::Instance()->Register("TimeDetPoint", "TimeDet", - fTimeDetPointCollection, kTRUE); + FairRootManager::Instance()->Register("TimeDetPoint", "TimeDet", fTimeDetPointCollection, kTRUE); } - - TClonesArray* TimeDet::GetCollection(Int_t iColl) const { - if (iColl == 0) { return fTimeDetPointCollection; } - else { return NULL; } + if (iColl == 0) { + return fTimeDetPointCollection; + } else { + return NULL; + } } - - void TimeDet::Reset() { - fTimeDetPointCollection->Clear(); + fTimeDetPointCollection->Clear(); } - - void TimeDet::ConstructGeometry() { - TGeoVolume *top = gGeoManager->GetTopVolume(); + TGeoVolume* top = gGeoManager->GetTopVolume(); - InitMedium("polyvinyltoluene"); - TGeoMedium *Scint =gGeoManager->GetMedium("polyvinyltoluene"); + InitMedium("polyvinyltoluene"); + TGeoMedium* Scint = gGeoManager->GetMedium("polyvinyltoluene"); - /////////////////////////////////////////////////////// + /////////////////////////////////////////////////////// - fDetector = new TGeoVolumeAssembly("Timing Detector"); + fDetector = new TGeoVolumeAssembly("Timing Detector"); - TGeoVolume *plate = gGeoManager->MakeBox("TimeDet", Scint, fxBar/2,fyBar/2,fzBar/2); - plate->SetLineColor(kBlue); - AddSensitiveVolume(plate); + TGeoVolume* plate = gGeoManager->MakeBox("TimeDet", Scint, fxBar / 2, fyBar / 2, fzBar / 2); + plate->SetLineColor(kBlue); + AddSensitiveVolume(plate); - for(int ib=0; ibAddNode(plate, ib, new TGeoTranslation( xbar,ybar,zbar) ); + fDetector->AddNode(plate, ib, new TGeoTranslation(xbar, ybar, zbar)); - // printf("%3i %3i %2i %8.3f %8.3f %8.3f\n",ib, irow,icol, xbar,ybar,zbar); - } + // printf("%3i %3i %2i %8.3f %8.3f %8.3f\n",ib, irow,icol, xbar,ybar,zbar); + } - top->AddNode(fDetector, 1, new TGeoTranslation(0,0,fzPos)); + top->AddNode(fDetector, 1, new TGeoTranslation(0, 0, fzPos)); - /////////////////////////////////////////////////////// + /////////////////////////////////////////////////////// - return; + return; } - - -TimeDetPoint* TimeDet::AddHit(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t time, Double_t length, - Double_t eLoss, Int_t pdgCode,TVector3 Lpos, TVector3 Lmom) +TimeDetPoint* TimeDet::AddHit(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t time, + Double_t length, + Double_t eLoss, + Int_t pdgCode, + TVector3 Lpos, + TVector3 Lmom) { - TClonesArray& clref = *fTimeDetPointCollection; - Int_t size = clref.GetEntriesFast(); - // cout << "veto hit called "<< pos.z()< #include +#include using std::cout; using std::endl; -Double_t speedOfLight = TMath::C() *100./1000000000.0 ; // from m/sec to cm/ns - +Double_t speedOfLight = TMath::C() * 100. / 1000000000.0; // from m/sec to cm/ns // ----- Default constructor -------------- TimeDetHit::TimeDetHit() - : ShipHit() + : ShipHit() { - flag = true; + flag = true; } - // ----- constructor from TimeDetPoint from TimeDetHit------------------------------- TimeDetHit::TimeDetHit(TimeDetPoint* p, Double_t t0) - : ShipHit() + : ShipHit() { - fDetectorID = p->GetDetectorID(); - Float_t lpos, lneg; - Dist(p->GetX(), lpos, lneg); - Double_t sigma = Resol(lneg); // in ns - t_1 = gRandom->Gaus( 0, sigma ) + lneg/v_drift + t0 + p->GetTime(); - sigma = Resol(lpos); // in ns - t_2 = gRandom->Gaus( 0, sigma ) + lpos/v_drift + t0 + p->GetTime(); - flag = true; + fDetectorID = p->GetDetectorID(); + Float_t lpos, lneg; + Dist(p->GetX(), lpos, lneg); + Double_t sigma = Resol(lneg); // in ns + t_1 = gRandom->Gaus(0, sigma) + lneg / v_drift + t0 + p->GetTime(); + sigma = Resol(lpos); // in ns + t_2 = gRandom->Gaus(0, sigma) + lpos / v_drift + t0 + p->GetTime(); + flag = true; } - // ----- Destructor ------------------------- -TimeDetHit::~TimeDetHit() { } +TimeDetHit::~TimeDetHit() {} // ---- return time information for a given track extrapolation -std::vector TimeDetHit::GetTime(Double_t x){ - // calculate distance to left and right end - Float_t lpos, lneg; - Dist(x, lpos, lneg); - Double_t r = Resol(lneg); - Double_t w1 = 1./(r*r); - r = Resol(lpos); - Double_t w2 = 1./(r*r); - Double_t dt = 1./TMath::Sqrt(w1+w2); - Double_t t = ( (t_1-lneg/v_drift)*w1+(t_2-lpos/v_drift)*w2 )/(w1+w2); - std::vector m; - m.push_back(t); - m.push_back(dt); - return m; +std::vector TimeDetHit::GetTime(Double_t x) +{ + // calculate distance to left and right end + Float_t lpos, lneg; + Dist(x, lpos, lneg); + Double_t r = Resol(lneg); + Double_t w1 = 1. / (r * r); + r = Resol(lpos); + Double_t w2 = 1. / (r * r); + Double_t dt = 1. / TMath::Sqrt(w1 + w2); + Double_t t = ((t_1 - lneg / v_drift) * w1 + (t_2 - lpos / v_drift) * w2) / (w1 + w2); + std::vector m; + m.push_back(t); + m.push_back(dt); + return m; } // ---- return mean time information -std::vector TimeDetHit::GetTime(){ - TGeoBBox* shape = (TGeoBBox*)gGeoManager->GetVolume("TimeDet")->GetShape(); - Double_t t0 = (t_1+t_2)/2.-shape->GetDX()/v_drift; - Float_t lpos, lneg; - lneg = (t_1-t0)*v_drift; - lpos = (t_2-t0)*v_drift; - Float_t r1 = Resol(lneg); - Float_t r2 = Resol(lpos); - Double_t dt = TMath::Sqrt(r1*r1+r2*r2); - std::vector m; - m.push_back(t0); - m.push_back(dt); - return m; +std::vector TimeDetHit::GetTime() +{ + TGeoBBox* shape = (TGeoBBox*)gGeoManager->GetVolume("TimeDet")->GetShape(); + Double_t t0 = (t_1 + t_2) / 2. - shape->GetDX() / v_drift; + Float_t lpos, lneg; + lneg = (t_1 - t0) * v_drift; + lpos = (t_2 - t0) * v_drift; + Float_t r1 = Resol(lneg); + Float_t r2 = Resol(lpos); + Double_t dt = TMath::Sqrt(r1 * r1 + r2 * r2); + std::vector m; + m.push_back(t0); + m.push_back(dt); + return m; } // ----- resolution function------------------- Double_t TimeDetHit::Resol(Double_t x) { - return par[0]*TMath::Exp( (x-par[2])/par[1] )+par[3]; + return par[0] * TMath::Exp((x - par[2]) / par[1]) + par[3]; } -std::vector TimeDetHit::GetMeasurements(){ - std::vector m; - m.push_back( t_1); - m.push_back( t_2); - return m; +std::vector TimeDetHit::GetMeasurements() +{ + std::vector m; + m.push_back(t_1); + m.push_back(t_2); + return m; } // distance to edges -void TimeDetHit::Dist(Float_t x, Float_t& lpos, Float_t& lneg){ - TGeoNode* node = GetNode(); - auto shape = dynamic_cast(node->GetVolume()->GetShape()); - TVector3 pos = GetXYZ(); - lpos = TMath::Abs( pos.X() + shape->GetDX() - x ); - lneg = TMath::Abs( pos.X() - shape->GetDX() - x ); +void TimeDetHit::Dist(Float_t x, Float_t& lpos, Float_t& lneg) +{ + TGeoNode* node = GetNode(); + auto shape = dynamic_cast(node->GetVolume()->GetShape()); + TVector3 pos = GetXYZ(); + lpos = TMath::Abs(pos.X() + shape->GetDX() - x); + lneg = TMath::Abs(pos.X() - shape->GetDX() - x); } // ---------------------------------------------- TVector3 TimeDetHit::GetXYZ() { TGeoNavigator* nav = gGeoManager->GetCurrentNavigator(); TGeoNode* node = GetNode(); - auto shape = dynamic_cast(node->GetVolume()->GetShape()); - Double_t origin[3] = {shape->GetOrigin()[0],shape->GetOrigin()[1],shape->GetOrigin()[2]}; - Double_t master[3] = {0,0,0}; - nav->LocalToMaster(origin,master); - TVector3 pos = TVector3(master[0],master[1],master[2]); + auto shape = dynamic_cast(node->GetVolume()->GetShape()); + Double_t origin[3] = {shape->GetOrigin()[0], shape->GetOrigin()[1], shape->GetOrigin()[2]}; + Double_t master[3] = {0, 0, 0}; + nav->LocalToMaster(origin, master); + TVector3 pos = TVector3(master[0], master[1], master[2]); return pos; } - Double_t TimeDetHit::GetX() -{ TVector3 pos = GetXYZ(); - return pos.X(); +{ + TVector3 pos = GetXYZ(); + return pos.X(); } - Double_t TimeDetHit::GetY() -{ TVector3 pos = GetXYZ(); - return pos.Y(); +{ + TVector3 pos = GetXYZ(); + return pos.Y(); } - Double_t TimeDetHit::GetZ() -{ TVector3 pos = GetXYZ(); - return pos.Z(); +{ + TVector3 pos = GetXYZ(); + return pos.Z(); } - TGeoNode* TimeDetHit::GetNode() { - TGeoNavigator* nav = gGeoManager->GetCurrentNavigator(); - TString path = "/Timing Detector_1/TimeDet_";path+=fDetectorID; - Bool_t rc = nav->cd(path); - return nav->GetCurrentNode(); + TGeoNavigator* nav = gGeoManager->GetCurrentNavigator(); + TString path = "/Timing Detector_1/TimeDet_"; + path += fDetectorID; + Bool_t rc = nav->cd(path); + return nav->GetCurrentNode(); } - // ----- Public method Print ----------------------- void TimeDetHit::Print() const { - cout << "-I- TimeDetHit: TimeDet hit " << " in detector " << fDetectorID << endl; - cout << " TDC left " << t_1 << " ns TDC right " << t_2 << " ns" << endl; + cout << "-I- TimeDetHit: TimeDet hit " << " in detector " << fDetectorID << endl; + cout << " TDC left " << t_1 << " ns TDC right " << t_2 << " ns" << endl; } - // ----------------------------------------------------- diff --git a/TimeDet/TimeDetHit.h b/TimeDet/TimeDetHit.h index ed0b758271..7ada224746 100644 --- a/TimeDet/TimeDetHit.h +++ b/TimeDet/TimeDetHit.h @@ -2,16 +2,14 @@ #define TimeDetHIT_H 1 #include "FairVolume.h" #include "ShipHit.h" -#include "TimeDetPoint.h" -#include "TObject.h" -#include "TGeoShape.h" #include "TGeoPhysicalNode.h" - +#include "TGeoShape.h" +#include "TObject.h" +#include "TimeDetPoint.h" class TimeDetHit : public ShipHit { public: - /** Default constructor **/ TimeDetHit(); @@ -35,27 +33,31 @@ class TimeDetHit : public ShipHit std::vector GetTime(); std::vector GetMeasurements(); /** Modifier **/ - void SetTDC(Float_t val1, Float_t val2){t_1=val1;t_2=val2;} + void SetTDC(Float_t val1, Float_t val2) + { + t_1 = val1; + t_2 = val2; + } /** Output to screen **/ virtual void Print() const; void Dist(Float_t x, Float_t& lpos, Float_t& lneg); Double_t Resol(Double_t x); - void setInvalid() {flag = false;} - void setIsValid() {flag = true;} - bool isValid() const {return flag;} + void setInvalid() { flag = false; } + void setIsValid() { flag = true; } + bool isValid() const { return flag; } + private: TimeDetHit(const TimeDetHit& point); TimeDetHit operator=(const TimeDetHit& point); - Double_t v_drift = 15.; // cm/ns - Double_t par[4] = { 0.0272814, 109.303, 0, 0.0539487 }; - - Float_t flag; ///< flag - Float_t t_1,t_2; ///< TDC on both sides + Double_t v_drift = 15.; // cm/ns + Double_t par[4] = {0.0272814, 109.303, 0, 0.0539487}; - ClassDef(TimeDetHit,1); + Float_t flag; ///< flag + Float_t t_1, t_2; ///< TDC on both sides + ClassDef(TimeDetHit, 1); }; #endif diff --git a/TimeDet/TimeDetPoint.cxx b/TimeDet/TimeDetPoint.cxx index 38f7346da9..16d6298933 100644 --- a/TimeDet/TimeDetPoint.cxx +++ b/TimeDet/TimeDetPoint.cxx @@ -4,38 +4,41 @@ using std::cout; using std::endl; - // ----- Default constructor ------------------------------------------- TimeDetPoint::TimeDetPoint() - : FairMCPoint() -{ -} + : FairMCPoint() +{} // ------------------------------------------------------------------------- // ----- Standard constructor ------------------------------------------ -TimeDetPoint::TimeDetPoint(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t tof, Double_t length, - Double_t eLoss, Int_t pdgcode,TVector3 Lpos, TVector3 Lmom) - : FairMCPoint(trackID, detID, pos, mom, tof, length, eLoss), fPdgCode(pdgcode),fLpos(Lpos),fLmom(Lmom) -{ -} +TimeDetPoint::TimeDetPoint(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t tof, + Double_t length, + Double_t eLoss, + Int_t pdgcode, + TVector3 Lpos, + TVector3 Lmom) + : FairMCPoint(trackID, detID, pos, mom, tof, length, eLoss) + , fPdgCode(pdgcode) + , fLpos(Lpos) + , fLmom(Lmom) +{} // ------------------------------------------------------------------------- // ----- Destructor ---------------------------------------------------- -TimeDetPoint::~TimeDetPoint() { } +TimeDetPoint::~TimeDetPoint() {} // ------------------------------------------------------------------------- // ----- Public method Print ------------------------------------------- void TimeDetPoint::Print() const { - cout << "-I- TimeDetPoint: veto point for track " << fTrackID - << " in detector " << fDetectorID << endl; - cout << " Position (" << fX << ", " << fY << ", " << fZ - << ") cm" << endl; - cout << " Momentum (" << fPx << ", " << fPy << ", " << fPz - << ") GeV" << endl; - cout << " Time " << fTime << " ns, Length " << fLength - << " cm, Energy loss " << fELoss*1.0e06 << " keV" << endl; + cout << "-I- TimeDetPoint: veto point for track " << fTrackID << " in detector " << fDetectorID << endl; + cout << " Position (" << fX << ", " << fY << ", " << fZ << ") cm" << endl; + cout << " Momentum (" << fPx << ", " << fPy << ", " << fPz << ") GeV" << endl; + cout << " Time " << fTime << " ns, Length " << fLength << " cm, Energy loss " << fELoss * 1.0e06 << " keV" + << endl; } // ------------------------------------------------------------------------- diff --git a/TimeDet/TimeDetPoint.h b/TimeDet/TimeDetPoint.h index b6fc6ac712..59c2f84a40 100644 --- a/TimeDet/TimeDetPoint.h +++ b/TimeDet/TimeDetPoint.h @@ -1,26 +1,22 @@ #ifndef TIMEDETPOINT_H #define TIMEDETPOINT_H 1 - #include "FairMCPoint.h" - #include "TObject.h" #include "TVector3.h" - class TimeDetPoint : public FairMCPoint { public: - /** Default constructor **/ TimeDetPoint(); - /** Constructor with arguments *@param trackID Index of MCTrack *@param detID Detector ID - // for LiSc: segment T1 (seg=1), segment T2 (seg=2), normal detector (c=0) and corner detector (c=1), sequential number + // for LiSc: segment T1 (seg=1), segment T2 (seg=2), normal detector (c=0) and corner detector + (c=1), sequential number // nr + 100000*seg + 10000*c; *@param pos Ccoordinates at entrance to active volume [cm] *@param mom Momentum of track at entrance [GeV] @@ -28,27 +24,34 @@ class TimeDetPoint : public FairMCPoint *@param length Track length since creation [cm] *@param eLoss Energy deposit [GeV] **/ - TimeDetPoint(Int_t trackID, Int_t detID, TVector3 pos, TVector3 mom, - Double_t tof, Double_t length, Double_t eLoss, Int_t pdgCode, TVector3 Lpos, TVector3 Lmom); + TimeDetPoint(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t tof, + Double_t length, + Double_t eLoss, + Int_t pdgCode, + TVector3 Lpos, + TVector3 Lmom); /** Destructor **/ virtual ~TimeDetPoint(); /** Output to screen **/ virtual void Print() const; - Int_t PdgCode() const {return fPdgCode;} - TVector3 LastPoint() const {return fLpos;} - TVector3 LastMom() const {return fLmom;} + Int_t PdgCode() const { return fPdgCode; } + TVector3 LastPoint() const { return fLpos; } + TVector3 LastMom() const { return fLmom; } private: /** Copy constructor **/ Int_t fPdgCode; - TVector3 fLpos,fLmom; + TVector3 fLpos, fLmom; TimeDetPoint(const TimeDetPoint& point); TimeDetPoint operator=(const TimeDetPoint& point); - ClassDef(TimeDetPoint,1) - + ClassDef(TimeDetPoint, 1) }; #endif diff --git a/UpstreamTagger/CMakeLists.txt b/UpstreamTagger/CMakeLists.txt index c4f0cfd912..a653c4c771 100644 --- a/UpstreamTagger/CMakeLists.txt +++ b/UpstreamTagger/CMakeLists.txt @@ -1,35 +1,24 @@ # Create a library called "libnutaudet” which includes the source files given in -# the array . -# The extension is already found. Any number of sources could be listed here. +# the array . The extension is already found. Any number of sources could be +# listed here. -set(INCLUDE_DIRECTORIES -${CMAKE_SOURCE_DIR}/shipdata -${CMAKE_SOURCE_DIR}/UpstreamTagger -${genfit2_INCDIR} -) +set(INCLUDE_DIRECTORIES ${CMAKE_SOURCE_DIR}/shipdata + ${CMAKE_SOURCE_DIR}/UpstreamTagger ${genfit2_INCDIR}) -include_directories(${INCLUDE_DIRECTORIES} ${VMC_INCLUDE_DIRS} ${FAIRROOT_INCLUDE_DIR}) +include_directories(${INCLUDE_DIRECTORIES} ${VMC_INCLUDE_DIRS} + ${FAIRROOT_INCLUDE_DIR}) include_directories(SYSTEM ${SYSTEM_INCLUDE_DIRECTORIES}) -set(LINK_DIRECTORIES -${ROOT_LIBRARY_DIR} -${genfit2_LIBDIR} -${FAIRROOT_LIBRARY_DIR} -) +set(LINK_DIRECTORIES ${ROOT_LIBRARY_DIR} ${genfit2_LIBDIR} + ${FAIRROOT_LIBRARY_DIR}) -link_directories( ${LINK_DIRECTORIES}) +link_directories(${LINK_DIRECTORIES}) -set(SRCS -UpstreamTagger.cxx -UpstreamTaggerPoint.cxx -UpstreamTaggerHit.cxx -) +set(SRCS UpstreamTagger.cxx UpstreamTaggerPoint.cxx UpstreamTaggerHit.cxx) -Set(HEADERS ) -Set(LINKDEF UpstreamTaggerLinkDef.h) -Set(LIBRARY_NAME UpstreamTagger) -Set(DEPENDENCIES - Base ShipData FairLogger::FairLogger -) +set(HEADERS) +set(LINKDEF UpstreamTaggerLinkDef.h) +set(LIBRARY_NAME UpstreamTagger) +set(DEPENDENCIES Base ShipData FairLogger::FairLogger) -GENERATE_LIBRARY() +generate_library() diff --git a/UpstreamTagger/UpstreamTagger.cxx b/UpstreamTagger/UpstreamTagger.cxx index 9de648c8a7..ef3e0659b7 100644 --- a/UpstreamTagger/UpstreamTagger.cxx +++ b/UpstreamTagger/UpstreamTagger.cxx @@ -3,595 +3,929 @@ // celso.franco@cern.ch #include "UpstreamTagger.h" -#include "UpstreamTaggerPoint.h" -#include "UpstreamTaggerHit.h" -#include "FairVolume.h" -#include "FairGeoVolume.h" -#include "FairGeoNode.h" -#include "FairRootManager.h" -#include "FairGeoLoader.h" +#include "FairGeoBuilder.h" #include "FairGeoInterface.h" +#include "FairGeoLoader.h" #include "FairGeoMedia.h" -#include "FairGeoBuilder.h" +#include "FairGeoNode.h" +#include "FairGeoVolume.h" +#include "FairRootManager.h" #include "FairRun.h" #include "FairRuntimeDb.h" +#include "FairVolume.h" #include "ShipDetectorList.h" #include "ShipStack.h" - #include "TClonesArray.h" -#include "TVirtualMC.h" -#include "TGeoManager.h" #include "TGeoBBox.h" #include "TGeoCompositeShape.h" -#include "TGeoTube.h" +#include "TGeoManager.h" #include "TGeoMaterial.h" #include "TGeoMedium.h" +#include "TGeoTube.h" #include "TMath.h" #include "TParticle.h" #include "TVector3.h" +#include "TVirtualMC.h" +#include "UpstreamTaggerHit.h" +#include "UpstreamTaggerPoint.h" #include #include #include -using std::cout; -using std::endl; using ROOT::TSeq; -using ShipUnit::m; using ShipUnit::cm; - +using ShipUnit::m; +using std::cout; +using std::endl; UpstreamTagger::UpstreamTagger() - : FairDetector("UpstreamTagger", kTRUE, kUpstreamTagger), - fTrackID(-1), - fVolumeID(-1), - fPos(), - fMom(), - fTime(-1.), - fLength(-1.), - fELoss(-1), + : FairDetector("UpstreamTagger", kTRUE, kUpstreamTagger) + , fTrackID(-1) + , fVolumeID(-1) + , fPos() + , fMom() + , fTime(-1.) + , fLength(-1.) + , fELoss(-1) + , // - det_zPos(0), - - det_xGlassPos(0), - det_yGlassPos(0), - det_zGlassPos(0), - - det_xGlassBorderPos(0), - det_yGlassBorderPos(0), - det_zGlassBorderPos(0), - - det_xPMMAPos(0), - det_yPMMAPos(0), - det_zPMMAPos(0), - - det_dxPMMAPos(0), - det_dyPMMAPos(0), - det_dzPMMAPos(0), - - det_xFreonSF6Pos(0), - det_yFreonSF6Pos(0), - det_zFreonSF6Pos(0), - - det_xFR4Pos(0), - det_yFR4Pos(0), - det_zFR4Pos(0), - - det_xAlPos(0), - det_yAlPos(0), - det_zAlPos(0), - - det_dxAlPos(0), - det_dyAlPos(0), - det_dzAlPos(0), - - det_xAirPos(0), - det_yAirPos(0), - det_zAirPos(0), - - det_xStripPos64(0), - det_yStripPos64(0), - det_xStripPos(0), - det_yStripPos(0), - det_zStripPos(0), + det_zPos(0) + , + + det_xGlassPos(0) + , det_yGlassPos(0) + , det_zGlassPos(0) + , + + det_xGlassBorderPos(0) + , det_yGlassBorderPos(0) + , det_zGlassBorderPos(0) + , + + det_xPMMAPos(0) + , det_yPMMAPos(0) + , det_zPMMAPos(0) + , + + det_dxPMMAPos(0) + , det_dyPMMAPos(0) + , det_dzPMMAPos(0) + , + + det_xFreonSF6Pos(0) + , det_yFreonSF6Pos(0) + , det_zFreonSF6Pos(0) + , + + det_xFR4Pos(0) + , det_yFR4Pos(0) + , det_zFR4Pos(0) + , + + det_xAlPos(0) + , det_yAlPos(0) + , det_zAlPos(0) + , + + det_dxAlPos(0) + , det_dyAlPos(0) + , det_dzAlPos(0) + , + + det_xAirPos(0) + , det_yAirPos(0) + , det_zAirPos(0) + , + + det_xStripPos64(0) + , det_yStripPos64(0) + , det_xStripPos(0) + , det_yStripPos(0) + , det_zStripPos(0) + , // - UpstreamTagger_fulldet(0), - // + UpstreamTagger_fulldet(0) + , + // fUpstreamTaggerPointCollection(new TClonesArray("UpstreamTaggerPoint")) -{ -} +{} UpstreamTagger::UpstreamTagger(const char* name, Bool_t active) - : FairDetector(name, active, kUpstreamTagger), - fTrackID(-1), - fVolumeID(-1), - fPos(), - fMom(), - fTime(-1.), - fLength(-1.), - fELoss(-1), + : FairDetector(name, active, kUpstreamTagger) + , fTrackID(-1) + , fVolumeID(-1) + , fPos() + , fMom() + , fTime(-1.) + , fLength(-1.) + , fELoss(-1) + , // - det_zPos(0), - - det_xGlassPos(0), - det_yGlassPos(0), - det_zGlassPos(0), - - det_xGlassBorderPos(0), - det_yGlassBorderPos(0), - det_zGlassBorderPos(0), - - det_xPMMAPos(0), - det_yPMMAPos(0), - det_zPMMAPos(0), - - det_dxPMMAPos(0), - det_dyPMMAPos(0), - det_dzPMMAPos(0), - - det_xFreonSF6Pos(0), - det_yFreonSF6Pos(0), - det_zFreonSF6Pos(0), - - det_xFR4Pos(0), - det_yFR4Pos(0), - det_zFR4Pos(0), - - det_xAlPos(0), - det_yAlPos(0), - det_zAlPos(0), - - det_dxAlPos(0), - det_dyAlPos(0), - det_dzAlPos(0), - - det_xAirPos(0), - det_yAirPos(0), - det_zAirPos(0), - - det_xStripPos64(0), - det_yStripPos64(0), - det_xStripPos(0), - det_yStripPos(0), - det_zStripPos(0), + det_zPos(0) + , + + det_xGlassPos(0) + , det_yGlassPos(0) + , det_zGlassPos(0) + , + + det_xGlassBorderPos(0) + , det_yGlassBorderPos(0) + , det_zGlassBorderPos(0) + , + + det_xPMMAPos(0) + , det_yPMMAPos(0) + , det_zPMMAPos(0) + , + + det_dxPMMAPos(0) + , det_dyPMMAPos(0) + , det_dzPMMAPos(0) + , + + det_xFreonSF6Pos(0) + , det_yFreonSF6Pos(0) + , det_zFreonSF6Pos(0) + , + + det_xFR4Pos(0) + , det_yFR4Pos(0) + , det_zFR4Pos(0) + , + + det_xAlPos(0) + , det_yAlPos(0) + , det_zAlPos(0) + , + + det_dxAlPos(0) + , det_dyAlPos(0) + , det_dzAlPos(0) + , + + det_xAirPos(0) + , det_yAirPos(0) + , det_zAirPos(0) + , + + det_xStripPos64(0) + , det_yStripPos64(0) + , det_xStripPos(0) + , det_yStripPos(0) + , det_zStripPos(0) + , // - UpstreamTagger_fulldet(0), - // + UpstreamTagger_fulldet(0) + , + // fUpstreamTaggerPointCollection(new TClonesArray("UpstreamTaggerPoint")) -{ -} - +{} void UpstreamTagger::Initialize() { - FairDetector::Initialize(); + FairDetector::Initialize(); } - UpstreamTagger::~UpstreamTagger() { - if (fUpstreamTaggerPointCollection) { - fUpstreamTaggerPointCollection->Delete(); - delete fUpstreamTaggerPointCollection; - } + if (fUpstreamTaggerPointCollection) { + fUpstreamTaggerPointCollection->Delete(); + delete fUpstreamTaggerPointCollection; + } } - - Int_t UpstreamTagger::InitMedium(const char* name) { - static FairGeoLoader *geoLoad=FairGeoLoader::Instance(); - static FairGeoInterface *geoFace=geoLoad->getGeoInterface(); - static FairGeoMedia *media=geoFace->getMedia(); - static FairGeoBuilder *geoBuild=geoLoad->getGeoBuilder(); + static FairGeoLoader* geoLoad = FairGeoLoader::Instance(); + static FairGeoInterface* geoFace = geoLoad->getGeoInterface(); + static FairGeoMedia* media = geoFace->getMedia(); + static FairGeoBuilder* geoBuild = geoLoad->getGeoBuilder(); - FairGeoMedium *ShipMedium=media->getMedium(name); + FairGeoMedium* ShipMedium = media->getMedium(name); - if (!ShipMedium) - { - Fatal("InitMedium","Material %s not defined in media file.", name); - return -1111; - } - TGeoMedium* medium=gGeoManager->GetMedium(name); - if (medium!=NULL) - return ShipMedium->getMediumIndex(); + if (!ShipMedium) { + Fatal("InitMedium", "Material %s not defined in media file.", name); + return -1111; + } + TGeoMedium* medium = gGeoManager->GetMedium(name); + if (medium != NULL) + return ShipMedium->getMediumIndex(); - return geoBuild->createMedium(ShipMedium); + return geoBuild->createMedium(ShipMedium); - return 0; + return 0; } - - -Bool_t UpstreamTagger::ProcessHits(FairVolume* vol) +Bool_t UpstreamTagger::ProcessHits(FairVolume* vol) { - /** This method is called from the MC stepping */ - //Set parameters at entrance of volume. Reset ELoss. - if ( gMC->IsTrackEntering() ) { - fELoss = 0.; - fTime = gMC->TrackTime() * 1.0e09; - fLength = gMC->TrackLength(); - gMC->TrackPosition(fPos); - gMC->TrackMomentum(fMom); - } - - // Sum energy loss for all steps in the active volume - fELoss += gMC->Edep(); - - // Create vetoPoint at exit of active volume - if ( gMC->IsTrackExiting() || - gMC->IsTrackStop() || - gMC->IsTrackDisappeared() ) { - if (fELoss == 0. ) { return kFALSE; } - - fTrackID = gMC->GetStack()->GetCurrentTrackNumber(); - - Int_t uniqueId; - gMC->CurrentVolID(uniqueId); - if (uniqueId>1000000) //Solid scintillator case - { - Int_t vcpy; - gMC->CurrentVolOffID(1, vcpy); - if (vcpy==5) uniqueId+=4; //Copy of half + /** This method is called from the MC stepping */ + // Set parameters at entrance of volume. Reset ELoss. + if (gMC->IsTrackEntering()) { + fELoss = 0.; + fTime = gMC->TrackTime() * 1.0e09; + fLength = gMC->TrackLength(); + gMC->TrackPosition(fPos); + gMC->TrackMomentum(fMom); } - TParticle* p = gMC->GetStack()->GetCurrentTrack(); - Int_t pdgCode = p->GetPdgCode(); - TLorentzVector Pos; - gMC->TrackPosition(Pos); - TLorentzVector Mom; - gMC->TrackMomentum(Mom); - Double_t xmean = (fPos.X()+Pos.X())/2. ; - Double_t ymean = (fPos.Y()+Pos.Y())/2. ; - Double_t zmean = (fPos.Z()+Pos.Z())/2. ; - - AddHit(fTrackID, uniqueId, TVector3(xmean, ymean, zmean), - TVector3(fMom.Px(), fMom.Py(), fMom.Pz()), fTime, fLength, - fELoss,pdgCode,TVector3(Pos.X(), Pos.Y(), Pos.Z()), - TVector3(Mom.Px(), Mom.Py(), Mom.Pz()) ); - - // Increment number of veto det points in TParticle - ShipStack* stack = (ShipStack*) gMC->GetStack(); - stack->AddPoint(kUpstreamTagger); - } - - return kTRUE; -} - + // Sum energy loss for all steps in the active volume + fELoss += gMC->Edep(); + + // Create vetoPoint at exit of active volume + if (gMC->IsTrackExiting() || gMC->IsTrackStop() || gMC->IsTrackDisappeared()) { + if (fELoss == 0.) { + return kFALSE; + } + + fTrackID = gMC->GetStack()->GetCurrentTrackNumber(); + + Int_t uniqueId; + gMC->CurrentVolID(uniqueId); + if (uniqueId > 1000000) // Solid scintillator case + { + Int_t vcpy; + gMC->CurrentVolOffID(1, vcpy); + if (vcpy == 5) + uniqueId += 4; // Copy of half + } + + TParticle* p = gMC->GetStack()->GetCurrentTrack(); + Int_t pdgCode = p->GetPdgCode(); + TLorentzVector Pos; + gMC->TrackPosition(Pos); + TLorentzVector Mom; + gMC->TrackMomentum(Mom); + Double_t xmean = (fPos.X() + Pos.X()) / 2.; + Double_t ymean = (fPos.Y() + Pos.Y()) / 2.; + Double_t zmean = (fPos.Z() + Pos.Z()) / 2.; + + AddHit(fTrackID, + uniqueId, + TVector3(xmean, ymean, zmean), + TVector3(fMom.Px(), fMom.Py(), fMom.Pz()), + fTime, + fLength, + fELoss, + pdgCode, + TVector3(Pos.X(), Pos.Y(), Pos.Z()), + TVector3(Mom.Px(), Mom.Py(), Mom.Pz())); + + // Increment number of veto det points in TParticle + ShipStack* stack = (ShipStack*)gMC->GetStack(); + stack->AddPoint(kUpstreamTagger); + } + return kTRUE; +} void UpstreamTagger::EndOfEvent() { - fUpstreamTaggerPointCollection->Clear(); + fUpstreamTaggerPointCollection->Clear(); } - - void UpstreamTagger::Register() { - /** This will create a branch in the output tree called - UpstreamTaggerPoint, setting the last parameter to kFALSE means: - this collection will not be written to the file, it will exist - only during the simulation. - */ + /** This will create a branch in the output tree called + UpstreamTaggerPoint, setting the last parameter to kFALSE means: + this collection will not be written to the file, it will exist + only during the simulation. + */ - FairRootManager::Instance()->Register("UpstreamTaggerPoint", "UpstreamTagger", - fUpstreamTaggerPointCollection, kTRUE); + FairRootManager::Instance()->Register( + "UpstreamTaggerPoint", "UpstreamTagger", fUpstreamTaggerPointCollection, kTRUE); } - - TClonesArray* UpstreamTagger::GetCollection(Int_t iColl) const { - if (iColl == 0) { return fUpstreamTaggerPointCollection; } - else { return NULL; } + if (iColl == 0) { + return fUpstreamTaggerPointCollection; + } else { + return NULL; + } } - - void UpstreamTagger::Reset() { - fUpstreamTaggerPointCollection->Clear(); + fUpstreamTaggerPointCollection->Clear(); } - - void UpstreamTagger::ConstructGeometry() { - TGeoVolume *top = gGeoManager->GetTopVolume(); - - ////////////////////////////////////////////////////// - - InitMedium("aluminium"); - TGeoMedium *rpc_al =gGeoManager->GetMedium("aluminium"); - - InitMedium("TimeRpc_gas"); - TGeoMedium *rpc_gas =gGeoManager->GetMedium("TimeRpc_gas"); - - InitMedium("air"); - TGeoMedium *rpc_air =gGeoManager->GetMedium("air"); - - InitMedium("copper"); - TGeoMedium *rpc_strip =gGeoManager->GetMedium("copper"); - - InitMedium("TimeRpc_glass"); - TGeoMedium *rpc_glass =gGeoManager->GetMedium("TimeRpc_glass"); - - InitMedium("TimeRpc_pmma"); - TGeoMedium *rpc_pmma =gGeoManager->GetMedium("TimeRpc_pmma"); - - InitMedium("TimeRpc_FR4"); - TGeoMedium *rpc_FR4 =gGeoManager->GetMedium("TimeRpc_FR4"); - - /////////////////////////////////////////////////////// - - TGeoVolume *vol_al1 = gGeoManager->MakeBox("Al1", rpc_al, (det_xAlPos + (2*det_dxAlPos))/2.0, (det_yAlPos + (2*det_dyAlPos))/2.0, det_dzAlPos/2.0); - vol_al1->SetLineColor(kBlue);//Gray); + TGeoVolume* top = gGeoManager->GetTopVolume(); - TGeoVolume *vol_al2 = gGeoManager->MakeBox("Al2", rpc_al, (det_xAlPos + (2*det_dxAlPos))/2.0, det_dyAlPos/2.0, det_zAlPos/2.0); - vol_al2->SetLineColor(kRed);//Gray); + ////////////////////////////////////////////////////// - TGeoVolume *vol_al3 = gGeoManager->MakeBox("Al3", rpc_al, (det_dxAlPos)/2.0, (det_yAlPos + (2*det_dyAlPos))/2.0, det_zAlPos/2.0); - vol_al3->SetLineColor(kRed);//); + InitMedium("aluminium"); + TGeoMedium* rpc_al = gGeoManager->GetMedium("aluminium"); - TGeoVolume *vol_strip = gGeoManager->MakeBox("strip", rpc_strip, (det_xStripPos)/2.0, (det_yStripPos)/2.0, det_zStripPos/2.0); - vol_strip->SetLineColor(42); + InitMedium("TimeRpc_gas"); + TGeoMedium* rpc_gas = gGeoManager->GetMedium("TimeRpc_gas"); - TGeoVolume *vol_strip64 = gGeoManager->MakeBox("strip64", rpc_strip, (det_xStripPos64)/2.0, (det_yStripPos64)/2.0, det_zStripPos/2.0); - vol_strip->SetLineColor(42); + InitMedium("air"); + TGeoMedium* rpc_air = gGeoManager->GetMedium("air"); - TGeoVolume *vol_pmma1 = gGeoManager->MakeBox("pmma1", rpc_pmma, (det_xPMMAPos+(2*det_dxPMMAPos))/2.0, (det_yPMMAPos + (2*det_dyPMMAPos))/2.0, det_dzPMMAPos/2.0); - vol_pmma1->SetLineColor(kYellow); + InitMedium("copper"); + TGeoMedium* rpc_strip = gGeoManager->GetMedium("copper"); + + InitMedium("TimeRpc_glass"); + TGeoMedium* rpc_glass = gGeoManager->GetMedium("TimeRpc_glass"); - TGeoVolume *vol_pmma2 = gGeoManager->MakeBox("pmma2", rpc_pmma, (det_xPMMAPos+(2*det_dxPMMAPos))/2.0, (det_dyPMMAPos)/2.0, det_zPMMAPos/2.0); - vol_pmma2->SetLineColor(kYellow); - - TGeoVolume *vol_pmma3 = gGeoManager->MakeBox("pmma3", rpc_pmma, (det_dxPMMAPos)/2.0, (det_yPMMAPos + (2*det_dyPMMAPos))/2.0, det_zPMMAPos/2.0); - vol_pmma3->SetLineColor(kYellow); - - TGeoVolume *vol_glass = gGeoManager->MakeBox("glass_upstreamtagger", rpc_glass, det_xGlassPos/2.0, det_yGlassPos/2.0, det_zGlassPos/2.0); - vol_glass->SetLineColor(kBlue); - AddSensitiveVolume(vol_glass); - - TGeoVolume *vol_glass_border = gGeoManager->MakeBox("glassB", rpc_glass, (det_xGlassPos + (det_xGlassBorderPos*2.0))/2.0, det_yGlassBorderPos/2.0, det_zGlassBorderPos/2.0); - vol_glass_border->SetLineColor(kRed); - - TGeoVolume *vol_glass_border1 = gGeoManager->MakeBox("glassB1", rpc_glass, det_xGlassBorderPos/2.0, det_yGlassPos/2.0, det_zGlassBorderPos/2.0); - vol_glass_border1->SetLineColor(kRed); - - TGeoVolume *vol_FR4 = gGeoManager->MakeBox("FR4", rpc_FR4, det_xFR4Pos/2.0, det_yFR4Pos/2.0, det_zFR4Pos/2.0); - vol_FR4->SetLineColor(kBlack); - - TGeoVolume *vol_air = gGeoManager->MakeBox("air", rpc_air, (det_xPMMAPos + (2*det_dxPMMAPos))/2.0, det_yAirPos/2.0, det_zAirPos/2.0); - vol_air->SetLineColor(kWhite); - - TGeoVolume *vol_FrSF6 = gGeoManager->MakeBox("gas1", rpc_gas, det_xFreonSF6Pos/2.0, det_yFreonSF6Pos/2.0, det_zFreonSF6Pos/2.0); - vol_FrSF6->SetLineColor(kGreen); - - TGeoVolume *vol_FrSF6_2 = gGeoManager->MakeBox("gas2", rpc_gas, det_xPMMAPos/2.0, det_yFreonSF6Pos_2/2.0, det_zFreonSF6Pos_2/2.0); - vol_FrSF6_2->SetLineColor(kGreen); - - TGeoVolume *vol_FrSF6_3 = gGeoManager->MakeBox("gas3", rpc_gas, det_xFreonSF6Pos_2/2.0, (det_yPMMAPos/2.0 - (2*det_yFreonSF6Pos_2)/2.0), det_zFreonSF6Pos_2/2.0); - vol_FrSF6_2->SetLineColor(kGreen); - - - //////////////////////////////////////////////////////////////////// - - InitMedium("vacuum"); - TGeoMedium *Vacuum_box =gGeoManager->GetMedium("vacuum"); - double xbox=xbox_fulldet; double ybox = 113; double zbox = 1.3503; - - //RPC Module with 32 horizontal strips - // TODO Make construction easier to understand (GeoAssemblies!) - TGeoVolume *Rpc_module_upstream = gGeoManager->MakeBox("UpstreamTagger",Vacuum_box, xbox/2.0, ybox/2.0, zbox/2.0); - Rpc_module_upstream->SetLineColor(kRed); - - Rpc_module_upstream->AddNode(vol_al1, 145, new TGeoTranslation(0, 0, (-(det_zAlPos/2.0) - (det_dzAlPos/2.0)) )); - Rpc_module_upstream->AddNode(vol_al2, 146, new TGeoTranslation(0, ((-det_yAlPos/2.0) - (det_dyAlPos/2.0)), 0)); - Rpc_module_upstream->AddNode(vol_al2, 147, new TGeoTranslation(0, ((det_yAlPos/2.0) + (det_dyAlPos/2.0)), 0)); - Rpc_module_upstream->AddNode(vol_al3, 148, new TGeoTranslation(((-det_xAlPos/2.0) - (det_dxAlPos/2.0)), 0, 0)); - Rpc_module_upstream->AddNode(vol_al3, 149, new TGeoTranslation(((det_xAlPos/2.0) + (det_dxAlPos/2.0)), 0, 0)); - Rpc_module_upstream->AddNode(vol_al1, 150, new TGeoTranslation(0, 0, ((det_zAlPos/2.0) + (det_dzAlPos/2.0)) )); - - Rpc_module_upstream->AddNode(vol_pmma1, 151, new TGeoTranslation(0, 0, -((det_zAlPos/2.0) - (det_dzPMMAPos/2.0)))); - Rpc_module_upstream->AddNode(vol_pmma2, 152, new TGeoTranslation(0, ((-det_yPMMAPos/2.0) - (det_dyPMMAPos/2.0)), 0 - (det_zFR4Pos + det_zStripPos)/2.0 )); - Rpc_module_upstream->AddNode(vol_pmma2, 153, new TGeoTranslation(0, ((det_yPMMAPos/2.0) + (det_dyPMMAPos/2.0)),0 - (det_zFR4Pos + det_zStripPos)/2.0 )); - Rpc_module_upstream->AddNode(vol_pmma3, 154, new TGeoTranslation(((-det_xPMMAPos/2.0) - (det_dxPMMAPos/2.0)), 0, 0 - (det_zFR4Pos + det_zStripPos)/2.0 )); - Rpc_module_upstream->AddNode(vol_pmma3, 155, new TGeoTranslation(((det_xPMMAPos/2.0) + (det_dxPMMAPos/2.0)), 0, 0 - (det_zFR4Pos + det_zStripPos)/2.0 )); - Rpc_module_upstream->AddNode(vol_pmma1, 156, new TGeoTranslation(0, 0, -(det_zAlPos/2.0) + det_dzPMMAPos + det_zPMMAPos + (det_dzPMMAPos/2.0) )); - - Rpc_module_upstream->AddNode(vol_glass_border, 157, new TGeoTranslation(0, ((det_yGlassPos/2.0) + (det_yGlassBorderPos/2.0)), ((det_zAlPos/2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos - (det_zGlassPos/2.0)))); - Rpc_module_upstream->AddNode(vol_glass_border, 158, new TGeoTranslation(0, (-(det_yGlassPos/2.0) - (det_yGlassBorderPos/2.0)), ((det_zAlPos/2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos - (det_zGlassPos/2.0)))); - Rpc_module_upstream->AddNode(vol_glass_border1, 159, new TGeoTranslation(((det_xGlassPos/2.0) + (det_xGlassBorderPos/2.0)), 0, ((det_zAlPos/2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos - (det_zGlassPos/2.0)))); - Rpc_module_upstream->AddNode(vol_glass_border1, 160, new TGeoTranslation((-(det_xGlassPos/2.0) - (det_xGlassBorderPos/2.0)), 0, ((det_zAlPos/2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos - (det_zGlassPos/2.0)))); - - Rpc_module_upstream->AddNode(vol_glass_border, 161, new TGeoTranslation(0, ((det_yGlassPos/2.0) + (det_yGlassBorderPos/2.0)), ((det_zAlPos/2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos - det_zGlassPos - det_zFreonSF6Pos - (det_zGlassPos/2.0)))); - Rpc_module_upstream->AddNode(vol_glass_border, 162, new TGeoTranslation(0, (-(det_yGlassPos/2.0) - (det_yGlassBorderPos/2.0)), ((det_zAlPos/2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos - det_zGlassPos - det_zFreonSF6Pos - (det_zGlassPos/2.0)))); - Rpc_module_upstream->AddNode(vol_glass_border1, 163, new TGeoTranslation(((det_xGlassPos/2.0) + (det_xGlassBorderPos/2.0)), 0, ((det_zAlPos/2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos - det_zGlassPos - det_zFreonSF6Pos - (det_zGlassPos/2.0)))); - Rpc_module_upstream->AddNode(vol_glass_border1, 164, new TGeoTranslation((-(det_xGlassPos/2.0) - (det_xGlassBorderPos/2.0)), 0, ((det_zAlPos/2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos - det_zGlassPos - det_zFreonSF6Pos - (det_zGlassPos/2.0)))); - - Rpc_module_upstream->AddNode(vol_glass_border, 165, new TGeoTranslation(0, ((det_yGlassPos/2.0) + (det_yGlassBorderPos/2.0)), ((det_zAlPos/2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos - (det_zGlassPos*2.0) - (det_zFreonSF6Pos*2.0) - (det_zGlassPos/2.0)))); - Rpc_module_upstream->AddNode(vol_glass_border, 166, new TGeoTranslation(0, (-(det_yGlassPos/2.0) - (det_yGlassBorderPos/2.0)), ((det_zAlPos/2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos - (det_zGlassPos*2.0) - (det_zFreonSF6Pos*2.0) - (det_zGlassPos/2.0)))); - Rpc_module_upstream->AddNode(vol_glass_border1, 167, new TGeoTranslation(((det_xGlassPos/2.0) + (det_xGlassBorderPos/2.0)), 0, ((det_zAlPos/2.0 - det_zFR4Pos - det_zStripPos) - det_dzPMMAPos - (det_zGlassPos*2.0) - (det_zFreonSF6Pos*2.0) - (det_zGlassPos/2.0)))); - Rpc_module_upstream->AddNode(vol_glass_border1, 168, new TGeoTranslation((-(det_xGlassPos/2.0) - (det_xGlassBorderPos/2.0)), 0, ((det_zAlPos/2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos - (det_zGlassPos*2.0) - (det_zFreonSF6Pos*2.0) - (det_zGlassPos/2.0)))); - - Rpc_module_upstream->AddNode(vol_glass, 169, new TGeoTranslation(0, 0, ((det_zAlPos/2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos - (det_zGlassPos/2.0)))); - Rpc_module_upstream->AddNode(vol_glass, 170, new TGeoTranslation(0, 0, ((det_zAlPos/2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos - det_zGlassPos - det_zFreonSF6Pos - (det_zGlassPos/2.0)))); - Rpc_module_upstream->AddNode(vol_glass, 171, new TGeoTranslation(0, 0, ((det_zAlPos/2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos - (det_zGlassPos*2.0) - (det_zFreonSF6Pos*2.0) - (det_zGlassPos/2.0)))); - - Rpc_module_upstream->AddNode(vol_FrSF6, 172, new TGeoTranslation(0, 0, ((det_zAlPos/2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos - (det_zGlassPos*1.0) - (det_zFreonSF6Pos/2.0)))); - Rpc_module_upstream->AddNode(vol_FrSF6, 173, new TGeoTranslation(0, 0, ((det_zAlPos/2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos - (det_zGlassPos*2.0) - (det_zFreonSF6Pos*1.0) - (det_zFreonSF6Pos/2.0)))); - - Rpc_module_upstream->AddNode(vol_FrSF6_2, 174, new TGeoTranslation(0, ((-det_yGlassPos/2.0) - det_yGlassBorderPos - (det_yFreonSF6Pos_2/2.0)), (-(det_zAlPos/2.0) + (det_dzPMMAPos) + (det_zFreonSF6Pos_2/2.0)))); - Rpc_module_upstream->AddNode(vol_FrSF6_2, 175, new TGeoTranslation(0, ((det_yGlassPos/2.0) + det_yGlassBorderPos + (det_yFreonSF6Pos_2/2.0)), (-(det_zAlPos/2.0) + (det_dzPMMAPos) + (det_zFreonSF6Pos_2/2.0)))); - Rpc_module_upstream->AddNode(vol_FrSF6_3, 176, new TGeoTranslation(((det_xGlassPos/2.0) + det_xGlassBorderPos + (det_xFreonSF6Pos_2/2.0)), 0, (-(det_zAlPos/2.0) + (det_dzPMMAPos) + (det_zFreonSF6Pos_2/2.0)))); - Rpc_module_upstream->AddNode(vol_FrSF6_3, 177, new TGeoTranslation(((-det_xGlassPos/2.0) - det_xGlassBorderPos - (det_xFreonSF6Pos_2/2.0)), 0, (-(det_zAlPos/2.0) + (det_dzPMMAPos) + (det_zFreonSF6Pos_2/2.0)))); - - Rpc_module_upstream->AddNode(vol_FR4, 178, new TGeoTranslation(0, 0, -(det_zAlPos/2.0) + det_dzPMMAPos + det_zPMMAPos + det_dzPMMAPos + det_zFR4Pos/2.0)); - - Rpc_module_upstream->AddNode(vol_air, 179, new TGeoTranslation(0, ((-det_yAlPos/2.0) + (det_yAirPos/2.0)), 0)); - Rpc_module_upstream->AddNode(vol_air, 180, new TGeoTranslation(0, ((det_yAlPos/2.0) - (det_yAirPos/2.0)), 0)); - - Int_t interval = 0; - - //Add 32 copper strips to the Rpc module - for(int i = 181; i < 213; i++){ + InitMedium("TimeRpc_pmma"); + TGeoMedium* rpc_pmma = gGeoManager->GetMedium("TimeRpc_pmma"); + + InitMedium("TimeRpc_FR4"); + TGeoMedium* rpc_FR4 = gGeoManager->GetMedium("TimeRpc_FR4"); + + /////////////////////////////////////////////////////// + + TGeoVolume* vol_al1 = gGeoManager->MakeBox("Al1", + rpc_al, + (det_xAlPos + (2 * det_dxAlPos)) / 2.0, + (det_yAlPos + (2 * det_dyAlPos)) / 2.0, + det_dzAlPos / 2.0); + vol_al1->SetLineColor(kBlue); // Gray); + + TGeoVolume* vol_al2 = gGeoManager->MakeBox( + "Al2", rpc_al, (det_xAlPos + (2 * det_dxAlPos)) / 2.0, det_dyAlPos / 2.0, det_zAlPos / 2.0); + vol_al2->SetLineColor(kRed); // Gray); + + TGeoVolume* vol_al3 = gGeoManager->MakeBox( + "Al3", rpc_al, (det_dxAlPos) / 2.0, (det_yAlPos + (2 * det_dyAlPos)) / 2.0, det_zAlPos / 2.0); + vol_al3->SetLineColor(kRed); //); + + TGeoVolume* vol_strip = + gGeoManager->MakeBox("strip", rpc_strip, (det_xStripPos) / 2.0, (det_yStripPos) / 2.0, det_zStripPos / 2.0); + vol_strip->SetLineColor(42); + + TGeoVolume* vol_strip64 = gGeoManager->MakeBox( + "strip64", rpc_strip, (det_xStripPos64) / 2.0, (det_yStripPos64) / 2.0, det_zStripPos / 2.0); + vol_strip->SetLineColor(42); + + TGeoVolume* vol_pmma1 = gGeoManager->MakeBox("pmma1", + rpc_pmma, + (det_xPMMAPos + (2 * det_dxPMMAPos)) / 2.0, + (det_yPMMAPos + (2 * det_dyPMMAPos)) / 2.0, + det_dzPMMAPos / 2.0); + vol_pmma1->SetLineColor(kYellow); + + TGeoVolume* vol_pmma2 = gGeoManager->MakeBox( + "pmma2", rpc_pmma, (det_xPMMAPos + (2 * det_dxPMMAPos)) / 2.0, (det_dyPMMAPos) / 2.0, det_zPMMAPos / 2.0); + vol_pmma2->SetLineColor(kYellow); + + TGeoVolume* vol_pmma3 = gGeoManager->MakeBox( + "pmma3", rpc_pmma, (det_dxPMMAPos) / 2.0, (det_yPMMAPos + (2 * det_dyPMMAPos)) / 2.0, det_zPMMAPos / 2.0); + vol_pmma3->SetLineColor(kYellow); + + TGeoVolume* vol_glass = gGeoManager->MakeBox( + "glass_upstreamtagger", rpc_glass, det_xGlassPos / 2.0, det_yGlassPos / 2.0, det_zGlassPos / 2.0); + vol_glass->SetLineColor(kBlue); + AddSensitiveVolume(vol_glass); + + TGeoVolume* vol_glass_border = gGeoManager->MakeBox("glassB", + rpc_glass, + (det_xGlassPos + (det_xGlassBorderPos * 2.0)) / 2.0, + det_yGlassBorderPos / 2.0, + det_zGlassBorderPos / 2.0); + vol_glass_border->SetLineColor(kRed); + + TGeoVolume* vol_glass_border1 = gGeoManager->MakeBox( + "glassB1", rpc_glass, det_xGlassBorderPos / 2.0, det_yGlassPos / 2.0, det_zGlassBorderPos / 2.0); + vol_glass_border1->SetLineColor(kRed); + + TGeoVolume* vol_FR4 = gGeoManager->MakeBox("FR4", rpc_FR4, det_xFR4Pos / 2.0, det_yFR4Pos / 2.0, det_zFR4Pos / 2.0); + vol_FR4->SetLineColor(kBlack); + + TGeoVolume* vol_air = gGeoManager->MakeBox( + "air", rpc_air, (det_xPMMAPos + (2 * det_dxPMMAPos)) / 2.0, det_yAirPos / 2.0, det_zAirPos / 2.0); + vol_air->SetLineColor(kWhite); + + TGeoVolume* vol_FrSF6 = + gGeoManager->MakeBox("gas1", rpc_gas, det_xFreonSF6Pos / 2.0, det_yFreonSF6Pos / 2.0, det_zFreonSF6Pos / 2.0); + vol_FrSF6->SetLineColor(kGreen); + + TGeoVolume* vol_FrSF6_2 = + gGeoManager->MakeBox("gas2", rpc_gas, det_xPMMAPos / 2.0, det_yFreonSF6Pos_2 / 2.0, det_zFreonSF6Pos_2 / 2.0); + vol_FrSF6_2->SetLineColor(kGreen); + + TGeoVolume* vol_FrSF6_3 = gGeoManager->MakeBox("gas3", + rpc_gas, + det_xFreonSF6Pos_2 / 2.0, + (det_yPMMAPos / 2.0 - (2 * det_yFreonSF6Pos_2) / 2.0), + det_zFreonSF6Pos_2 / 2.0); + vol_FrSF6_2->SetLineColor(kGreen); + + //////////////////////////////////////////////////////////////////// + + InitMedium("vacuum"); + TGeoMedium* Vacuum_box = gGeoManager->GetMedium("vacuum"); + double xbox = xbox_fulldet; + double ybox = 113; + double zbox = 1.3503; + + // RPC Module with 32 horizontal strips + // TODO Make construction easier to understand (GeoAssemblies!) + TGeoVolume* Rpc_module_upstream = + gGeoManager->MakeBox("UpstreamTagger", Vacuum_box, xbox / 2.0, ybox / 2.0, zbox / 2.0); + Rpc_module_upstream->SetLineColor(kRed); + + Rpc_module_upstream->AddNode(vol_al1, 145, new TGeoTranslation(0, 0, (-(det_zAlPos / 2.0) - (det_dzAlPos / 2.0)))); + Rpc_module_upstream->AddNode(vol_al2, 146, new TGeoTranslation(0, ((-det_yAlPos / 2.0) - (det_dyAlPos / 2.0)), 0)); + Rpc_module_upstream->AddNode(vol_al2, 147, new TGeoTranslation(0, ((det_yAlPos / 2.0) + (det_dyAlPos / 2.0)), 0)); + Rpc_module_upstream->AddNode(vol_al3, 148, new TGeoTranslation(((-det_xAlPos / 2.0) - (det_dxAlPos / 2.0)), 0, 0)); + Rpc_module_upstream->AddNode(vol_al3, 149, new TGeoTranslation(((det_xAlPos / 2.0) + (det_dxAlPos / 2.0)), 0, 0)); + Rpc_module_upstream->AddNode(vol_al1, 150, new TGeoTranslation(0, 0, ((det_zAlPos / 2.0) + (det_dzAlPos / 2.0)))); + + Rpc_module_upstream->AddNode( + vol_pmma1, 151, new TGeoTranslation(0, 0, -((det_zAlPos / 2.0) - (det_dzPMMAPos / 2.0)))); + Rpc_module_upstream->AddNode(vol_pmma2, + 152, + new TGeoTranslation(0, + ((-det_yPMMAPos / 2.0) - (det_dyPMMAPos / 2.0)), + 0 - (det_zFR4Pos + det_zStripPos) / 2.0)); + Rpc_module_upstream->AddNode(vol_pmma2, + 153, + new TGeoTranslation(0, + ((det_yPMMAPos / 2.0) + (det_dyPMMAPos / 2.0)), + 0 - (det_zFR4Pos + det_zStripPos) / 2.0)); + Rpc_module_upstream->AddNode(vol_pmma3, + 154, + new TGeoTranslation(((-det_xPMMAPos / 2.0) - (det_dxPMMAPos / 2.0)), + 0, + 0 - (det_zFR4Pos + det_zStripPos) / 2.0)); + Rpc_module_upstream->AddNode(vol_pmma3, + 155, + new TGeoTranslation(((det_xPMMAPos / 2.0) + (det_dxPMMAPos / 2.0)), + 0, + 0 - (det_zFR4Pos + det_zStripPos) / 2.0)); + Rpc_module_upstream->AddNode( + vol_pmma1, + 156, + new TGeoTranslation(0, 0, -(det_zAlPos / 2.0) + det_dzPMMAPos + det_zPMMAPos + (det_dzPMMAPos / 2.0))); + + Rpc_module_upstream->AddNode(vol_glass_border, + 157, + new TGeoTranslation(0, + ((det_yGlassPos / 2.0) + (det_yGlassBorderPos / 2.0)), + ((det_zAlPos / 2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos + - (det_zGlassPos / 2.0)))); + Rpc_module_upstream->AddNode(vol_glass_border, + 158, + new TGeoTranslation(0, + (-(det_yGlassPos / 2.0) - (det_yGlassBorderPos / 2.0)), + ((det_zAlPos / 2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos + - (det_zGlassPos / 2.0)))); + Rpc_module_upstream->AddNode(vol_glass_border1, + 159, + new TGeoTranslation(((det_xGlassPos / 2.0) + (det_xGlassBorderPos / 2.0)), + 0, + ((det_zAlPos / 2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos + - (det_zGlassPos / 2.0)))); + Rpc_module_upstream->AddNode(vol_glass_border1, + 160, + new TGeoTranslation((-(det_xGlassPos / 2.0) - (det_xGlassBorderPos / 2.0)), + 0, + ((det_zAlPos / 2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos + - (det_zGlassPos / 2.0)))); + + Rpc_module_upstream->AddNode(vol_glass_border, + 161, + new TGeoTranslation(0, + ((det_yGlassPos / 2.0) + (det_yGlassBorderPos / 2.0)), + ((det_zAlPos / 2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos + - det_zGlassPos - det_zFreonSF6Pos - (det_zGlassPos / 2.0)))); + Rpc_module_upstream->AddNode(vol_glass_border, + 162, + new TGeoTranslation(0, + (-(det_yGlassPos / 2.0) - (det_yGlassBorderPos / 2.0)), + ((det_zAlPos / 2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos + - det_zGlassPos - det_zFreonSF6Pos - (det_zGlassPos / 2.0)))); + Rpc_module_upstream->AddNode(vol_glass_border1, + 163, + new TGeoTranslation(((det_xGlassPos / 2.0) + (det_xGlassBorderPos / 2.0)), + 0, + ((det_zAlPos / 2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos + - det_zGlassPos - det_zFreonSF6Pos - (det_zGlassPos / 2.0)))); + Rpc_module_upstream->AddNode(vol_glass_border1, + 164, + new TGeoTranslation((-(det_xGlassPos / 2.0) - (det_xGlassBorderPos / 2.0)), + 0, + ((det_zAlPos / 2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos + - det_zGlassPos - det_zFreonSF6Pos - (det_zGlassPos / 2.0)))); + + Rpc_module_upstream->AddNode( + vol_glass_border, + 165, + new TGeoTranslation(0, + ((det_yGlassPos / 2.0) + (det_yGlassBorderPos / 2.0)), + ((det_zAlPos / 2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos - (det_zGlassPos * 2.0) + - (det_zFreonSF6Pos * 2.0) - (det_zGlassPos / 2.0)))); + Rpc_module_upstream->AddNode( + vol_glass_border, + 166, + new TGeoTranslation(0, + (-(det_yGlassPos / 2.0) - (det_yGlassBorderPos / 2.0)), + ((det_zAlPos / 2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos - (det_zGlassPos * 2.0) + - (det_zFreonSF6Pos * 2.0) - (det_zGlassPos / 2.0)))); + Rpc_module_upstream->AddNode( + vol_glass_border1, + 167, + new TGeoTranslation(((det_xGlassPos / 2.0) + (det_xGlassBorderPos / 2.0)), + 0, + ((det_zAlPos / 2.0 - det_zFR4Pos - det_zStripPos) - det_dzPMMAPos - (det_zGlassPos * 2.0) + - (det_zFreonSF6Pos * 2.0) - (det_zGlassPos / 2.0)))); + Rpc_module_upstream->AddNode( + vol_glass_border1, + 168, + new TGeoTranslation((-(det_xGlassPos / 2.0) - (det_xGlassBorderPos / 2.0)), + 0, + ((det_zAlPos / 2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos - (det_zGlassPos * 2.0) + - (det_zFreonSF6Pos * 2.0) - (det_zGlassPos / 2.0)))); + + Rpc_module_upstream->AddNode( + vol_glass, + 169, + new TGeoTranslation( + 0, 0, ((det_zAlPos / 2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos - (det_zGlassPos / 2.0)))); + Rpc_module_upstream->AddNode(vol_glass, + 170, + new TGeoTranslation(0, + 0, + ((det_zAlPos / 2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos + - det_zGlassPos - det_zFreonSF6Pos - (det_zGlassPos / 2.0)))); + Rpc_module_upstream->AddNode( + vol_glass, + 171, + new TGeoTranslation(0, + 0, + ((det_zAlPos / 2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos - (det_zGlassPos * 2.0) + - (det_zFreonSF6Pos * 2.0) - (det_zGlassPos / 2.0)))); + + Rpc_module_upstream->AddNode(vol_FrSF6, + 172, + new TGeoTranslation(0, + 0, + ((det_zAlPos / 2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos + - (det_zGlassPos * 1.0) - (det_zFreonSF6Pos / 2.0)))); + Rpc_module_upstream->AddNode( + vol_FrSF6, + 173, + new TGeoTranslation(0, + 0, + ((det_zAlPos / 2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos - (det_zGlassPos * 2.0) + - (det_zFreonSF6Pos * 1.0) - (det_zFreonSF6Pos / 2.0)))); + + Rpc_module_upstream->AddNode( + vol_FrSF6_2, + 174, + new TGeoTranslation(0, + ((-det_yGlassPos / 2.0) - det_yGlassBorderPos - (det_yFreonSF6Pos_2 / 2.0)), + (-(det_zAlPos / 2.0) + (det_dzPMMAPos) + (det_zFreonSF6Pos_2 / 2.0)))); + Rpc_module_upstream->AddNode( + vol_FrSF6_2, + 175, + new TGeoTranslation(0, + ((det_yGlassPos / 2.0) + det_yGlassBorderPos + (det_yFreonSF6Pos_2 / 2.0)), + (-(det_zAlPos / 2.0) + (det_dzPMMAPos) + (det_zFreonSF6Pos_2 / 2.0)))); + Rpc_module_upstream->AddNode( + vol_FrSF6_3, + 176, + new TGeoTranslation(((det_xGlassPos / 2.0) + det_xGlassBorderPos + (det_xFreonSF6Pos_2 / 2.0)), + 0, + (-(det_zAlPos / 2.0) + (det_dzPMMAPos) + (det_zFreonSF6Pos_2 / 2.0)))); + Rpc_module_upstream->AddNode( + vol_FrSF6_3, + 177, + new TGeoTranslation(((-det_xGlassPos / 2.0) - det_xGlassBorderPos - (det_xFreonSF6Pos_2 / 2.0)), + 0, + (-(det_zAlPos / 2.0) + (det_dzPMMAPos) + (det_zFreonSF6Pos_2 / 2.0)))); + + Rpc_module_upstream->AddNode( + vol_FR4, + 178, + new TGeoTranslation( + 0, 0, -(det_zAlPos / 2.0) + det_dzPMMAPos + det_zPMMAPos + det_dzPMMAPos + det_zFR4Pos / 2.0)); + + Rpc_module_upstream->AddNode(vol_air, 179, new TGeoTranslation(0, ((-det_yAlPos / 2.0) + (det_yAirPos / 2.0)), 0)); + Rpc_module_upstream->AddNode(vol_air, 180, new TGeoTranslation(0, ((det_yAlPos / 2.0) - (det_yAirPos / 2.0)), 0)); + + Int_t interval = 0; + + // Add 32 copper strips to the Rpc module + for (int i = 181; i < 213; i++) { + + Rpc_module_upstream->AddNode(vol_strip, + i, + new TGeoTranslation(0, + (-det_yGlassPos / 2.0) - det_yGlassBorderPos + 1.5 + + (interval * det_yStripPos) + (interval * 0.15) + + ((det_yStripPos / 2.0)), + -(det_zAlPos / 2.0) + det_dzPMMAPos + det_zPMMAPos + + det_dzPMMAPos + det_zFR4Pos + (det_zStripPos / 2.0))); + interval++; + } - Rpc_module_upstream->AddNode(vol_strip, i, new TGeoTranslation(0, (-det_yGlassPos/2.0) - det_yGlassBorderPos + 1.5 + (interval*det_yStripPos) + (interval*0.15) + ((det_yStripPos/2.0)), -(det_zAlPos/2.0) + det_dzPMMAPos + det_zPMMAPos + det_dzPMMAPos + det_zFR4Pos + (det_zStripPos/2.0) )); - interval++; - } + // RPC Module with 64 vertical strips + // TODO Make construction easier to understand (GeoAssemblies!) + TGeoVolume* Rpc_module_upstream1 = + gGeoManager->MakeBox("UpstreamTagger1", Vacuum_box, xbox / 2.0, ybox / 2.0, zbox / 2.0); + Rpc_module_upstream1->SetLineColor(kRed); + + Rpc_module_upstream1->AddNode(vol_al1, 214, new TGeoTranslation(0, 0, (-(det_zAlPos / 2.0) - (det_dzAlPos / 2.0)))); + Rpc_module_upstream1->AddNode(vol_al2, 215, new TGeoTranslation(0, ((-det_yAlPos / 2.0) - (det_dyAlPos / 2.0)), 0)); + Rpc_module_upstream1->AddNode(vol_al2, 216, new TGeoTranslation(0, ((det_yAlPos / 2.0) + (det_dyAlPos / 2.0)), 0)); + Rpc_module_upstream1->AddNode(vol_al3, 217, new TGeoTranslation(((-det_xAlPos / 2.0) - (det_dxAlPos / 2.0)), 0, 0)); + Rpc_module_upstream1->AddNode(vol_al3, 218, new TGeoTranslation(((det_xAlPos / 2.0) + (det_dxAlPos / 2.0)), 0, 0)); + Rpc_module_upstream1->AddNode(vol_al1, 219, new TGeoTranslation(0, 0, ((det_zAlPos / 2.0) + (det_dzAlPos / 2.0)))); + + Rpc_module_upstream1->AddNode( + vol_pmma1, 220, new TGeoTranslation(0, 0, -((det_zAlPos / 2.0) - (det_dzPMMAPos / 2.0)))); + Rpc_module_upstream1->AddNode(vol_pmma2, + 221, + new TGeoTranslation(0, + ((-det_yPMMAPos / 2.0) - (det_dyPMMAPos / 2.0)), + 0 - (det_zFR4Pos + det_zStripPos) / 2.0)); + Rpc_module_upstream1->AddNode(vol_pmma2, + 222, + new TGeoTranslation(0, + ((det_yPMMAPos / 2.0) + (det_dyPMMAPos / 2.0)), + 0 - (det_zFR4Pos + det_zStripPos) / 2.0)); + Rpc_module_upstream1->AddNode(vol_pmma3, + 223, + new TGeoTranslation(((-det_xPMMAPos / 2.0) - (det_dxPMMAPos / 2.0)), + 0, + 0 - (det_zFR4Pos + det_zStripPos) / 2.0)); + Rpc_module_upstream1->AddNode(vol_pmma3, + 224, + new TGeoTranslation(((det_xPMMAPos / 2.0) + (det_dxPMMAPos / 2.0)), + 0, + 0 - (det_zFR4Pos + det_zStripPos) / 2.0)); + Rpc_module_upstream1->AddNode( + vol_pmma1, + 225, + new TGeoTranslation(0, 0, -(det_zAlPos / 2.0) + det_dzPMMAPos + det_zPMMAPos + (det_dzPMMAPos / 2.0))); + + Rpc_module_upstream1->AddNode(vol_glass_border, + 226, + new TGeoTranslation(0, + ((det_yGlassPos / 2.0) + (det_yGlassBorderPos / 2.0)), + ((det_zAlPos / 2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos + - (det_zGlassPos / 2.0)))); + Rpc_module_upstream1->AddNode(vol_glass_border, + 227, + new TGeoTranslation(0, + (-(det_yGlassPos / 2.0) - (det_yGlassBorderPos / 2.0)), + ((det_zAlPos / 2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos + - (det_zGlassPos / 2.0)))); + Rpc_module_upstream1->AddNode(vol_glass_border1, + 228, + new TGeoTranslation(((det_xGlassPos / 2.0) + (det_xGlassBorderPos / 2.0)), + 0, + ((det_zAlPos / 2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos + - (det_zGlassPos / 2.0)))); + Rpc_module_upstream1->AddNode(vol_glass_border1, + 229, + new TGeoTranslation((-(det_xGlassPos / 2.0) - (det_xGlassBorderPos / 2.0)), + 0, + ((det_zAlPos / 2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos + - (det_zGlassPos / 2.0)))); + + Rpc_module_upstream1->AddNode(vol_glass_border, + 230, + new TGeoTranslation(0, + ((det_yGlassPos / 2.0) + (det_yGlassBorderPos / 2.0)), + ((det_zAlPos / 2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos + - det_zGlassPos - det_zFreonSF6Pos - (det_zGlassPos / 2.0)))); + Rpc_module_upstream1->AddNode(vol_glass_border, + 231, + new TGeoTranslation(0, + (-(det_yGlassPos / 2.0) - (det_yGlassBorderPos / 2.0)), + ((det_zAlPos / 2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos + - det_zGlassPos - det_zFreonSF6Pos - (det_zGlassPos / 2.0)))); + Rpc_module_upstream1->AddNode(vol_glass_border1, + 232, + new TGeoTranslation(((det_xGlassPos / 2.0) + (det_xGlassBorderPos / 2.0)), + 0, + ((det_zAlPos / 2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos + - det_zGlassPos - det_zFreonSF6Pos - (det_zGlassPos / 2.0)))); + Rpc_module_upstream1->AddNode(vol_glass_border1, + 233, + new TGeoTranslation((-(det_xGlassPos / 2.0) - (det_xGlassBorderPos / 2.0)), + 0, + ((det_zAlPos / 2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos + - det_zGlassPos - det_zFreonSF6Pos - (det_zGlassPos / 2.0)))); + + Rpc_module_upstream1->AddNode( + vol_glass_border, + 234, + new TGeoTranslation(0, + ((det_yGlassPos / 2.0) + (det_yGlassBorderPos / 2.0)), + ((det_zAlPos / 2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos - (det_zGlassPos * 2.0) + - (det_zFreonSF6Pos * 2.0) - (det_zGlassPos / 2.0)))); + Rpc_module_upstream1->AddNode( + vol_glass_border, + 235, + new TGeoTranslation(0, + (-(det_yGlassPos / 2.0) - (det_yGlassBorderPos / 2.0)), + ((det_zAlPos / 2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos - (det_zGlassPos * 2.0) + - (det_zFreonSF6Pos * 2.0) - (det_zGlassPos / 2.0)))); + Rpc_module_upstream1->AddNode( + vol_glass_border1, + 236, + new TGeoTranslation(((det_xGlassPos / 2.0) + (det_xGlassBorderPos / 2.0)), + 0, + ((det_zAlPos / 2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos - (det_zGlassPos * 2.0) + - (det_zFreonSF6Pos * 2.0) - (det_zGlassPos / 2.0)))); + Rpc_module_upstream1->AddNode( + vol_glass_border1, + 237, + new TGeoTranslation((-(det_xGlassPos / 2.0) - (det_xGlassBorderPos / 2.0)), + 0, + ((det_zAlPos / 2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos - (det_zGlassPos * 2.0) + - (det_zFreonSF6Pos * 2.0) - (det_zGlassPos / 2.0)))); + + Rpc_module_upstream1->AddNode( + vol_glass, + 238, + new TGeoTranslation( + 0, 0, ((det_zAlPos / 2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos - (det_zGlassPos / 2.0)))); + Rpc_module_upstream1->AddNode(vol_glass, + 239, + new TGeoTranslation(0, + 0, + ((det_zAlPos / 2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos + - det_zGlassPos - det_zFreonSF6Pos - (det_zGlassPos / 2.0)))); + Rpc_module_upstream1->AddNode( + vol_glass, + 240, + new TGeoTranslation(0, + 0, + ((det_zAlPos / 2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos - (det_zGlassPos * 2.0) + - (det_zFreonSF6Pos * 2.0) - (det_zGlassPos / 2.0)))); + + Rpc_module_upstream1->AddNode(vol_FrSF6, + 241, + new TGeoTranslation(0, + 0, + ((det_zAlPos / 2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos + - (det_zGlassPos * 1.0) - (det_zFreonSF6Pos / 2.0)))); + Rpc_module_upstream1->AddNode( + vol_FrSF6, + 243, + new TGeoTranslation(0, + 0, + ((det_zAlPos / 2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos - (det_zGlassPos * 2.0) + - (det_zFreonSF6Pos * 1.0) - (det_zFreonSF6Pos / 2.0)))); + + Rpc_module_upstream1->AddNode( + vol_FrSF6_2, + 243, + new TGeoTranslation(0, + ((-det_yGlassPos / 2.0) - det_yGlassBorderPos - (det_yFreonSF6Pos_2 / 2.0)), + (-(det_zAlPos / 2.0) + (det_dzPMMAPos) + (det_zFreonSF6Pos_2 / 2.0)))); + Rpc_module_upstream1->AddNode( + vol_FrSF6_2, + 244, + new TGeoTranslation(0, + ((det_yGlassPos / 2.0) + det_yGlassBorderPos + (det_yFreonSF6Pos_2 / 2.0)), + (-(det_zAlPos / 2.0) + (det_dzPMMAPos) + (det_zFreonSF6Pos_2 / 2.0)))); + Rpc_module_upstream1->AddNode( + vol_FrSF6_3, + 245, + new TGeoTranslation(((det_xGlassPos / 2.0) + det_xGlassBorderPos + (det_xFreonSF6Pos_2 / 2.0)), + 0, + (-(det_zAlPos / 2.0) + (det_dzPMMAPos) + (det_zFreonSF6Pos_2 / 2.0)))); + Rpc_module_upstream1->AddNode( + vol_FrSF6_3, + 246, + new TGeoTranslation(((-det_xGlassPos / 2.0) - det_xGlassBorderPos - (det_xFreonSF6Pos_2 / 2.0)), + 0, + (-(det_zAlPos / 2.0) + (det_dzPMMAPos) + (det_zFreonSF6Pos_2 / 2.0)))); + + Rpc_module_upstream1->AddNode( + vol_FR4, + 247, + new TGeoTranslation( + 0, 0, -(det_zAlPos / 2.0) + det_dzPMMAPos + det_zPMMAPos + det_dzPMMAPos + det_zFR4Pos / 2.0)); + + Rpc_module_upstream1->AddNode(vol_air, 248, new TGeoTranslation(0, ((-det_yAlPos / 2.0) + (det_yAirPos / 2.0)), 0)); + Rpc_module_upstream1->AddNode(vol_air, 249, new TGeoTranslation(0, ((det_yAlPos / 2.0) - (det_yAirPos / 2.0)), 0)); + + interval = 0; + + // Add 64 copper strips to the Rpc module + for (int i = 250; i < 314; i++) { + + Rpc_module_upstream1->AddNode(vol_strip64, + i, + new TGeoTranslation((-det_xGlassPos / 2.0) - det_xGlassBorderPos + 2.175 + + (interval * det_xStripPos64) + (interval * 0.15) + + ((det_xStripPos64 / 2.0)), + 0, + -(det_zAlPos / 2.0) + det_dzPMMAPos + det_zPMMAPos + + det_dzPMMAPos + det_zFR4Pos + (det_zStripPos / 2.0))); + interval++; + } - //RPC Module with 64 vertical strips - // TODO Make construction easier to understand (GeoAssemblies!) - TGeoVolume *Rpc_module_upstream1 = gGeoManager->MakeBox("UpstreamTagger1",Vacuum_box, xbox/2.0, ybox/2.0, zbox/2.0); - Rpc_module_upstream1->SetLineColor(kRed); - - Rpc_module_upstream1->AddNode(vol_al1, 214, new TGeoTranslation(0, 0, (-(det_zAlPos/2.0) - (det_dzAlPos/2.0)) )); - Rpc_module_upstream1->AddNode(vol_al2, 215, new TGeoTranslation(0, ((-det_yAlPos/2.0) - (det_dyAlPos/2.0)), 0)); - Rpc_module_upstream1->AddNode(vol_al2, 216, new TGeoTranslation(0, ((det_yAlPos/2.0) + (det_dyAlPos/2.0)), 0)); - Rpc_module_upstream1->AddNode(vol_al3, 217, new TGeoTranslation(((-det_xAlPos/2.0) - (det_dxAlPos/2.0)), 0, 0)); - Rpc_module_upstream1->AddNode(vol_al3, 218, new TGeoTranslation(((det_xAlPos/2.0) + (det_dxAlPos/2.0)), 0, 0)); - Rpc_module_upstream1->AddNode(vol_al1, 219, new TGeoTranslation(0, 0, ((det_zAlPos/2.0) + (det_dzAlPos/2.0)) )); - - Rpc_module_upstream1->AddNode(vol_pmma1, 220, new TGeoTranslation(0, 0, -((det_zAlPos/2.0) - (det_dzPMMAPos/2.0)))); - Rpc_module_upstream1->AddNode(vol_pmma2, 221, new TGeoTranslation(0, ((-det_yPMMAPos/2.0) - (det_dyPMMAPos/2.0)), 0 - (det_zFR4Pos + det_zStripPos)/2.0 )); - Rpc_module_upstream1->AddNode(vol_pmma2, 222, new TGeoTranslation(0, ((det_yPMMAPos/2.0) + (det_dyPMMAPos/2.0)),0 - (det_zFR4Pos + det_zStripPos)/2.0 )); - Rpc_module_upstream1->AddNode(vol_pmma3, 223, new TGeoTranslation(((-det_xPMMAPos/2.0) - (det_dxPMMAPos/2.0)), 0, 0 - (det_zFR4Pos + det_zStripPos)/2.0 )); - Rpc_module_upstream1->AddNode(vol_pmma3, 224, new TGeoTranslation(((det_xPMMAPos/2.0) + (det_dxPMMAPos/2.0)), 0, 0 - (det_zFR4Pos + det_zStripPos)/2.0 )); - Rpc_module_upstream1->AddNode(vol_pmma1, 225, new TGeoTranslation(0, 0, -(det_zAlPos/2.0) + det_dzPMMAPos + det_zPMMAPos + (det_dzPMMAPos/2.0) )); - - Rpc_module_upstream1->AddNode(vol_glass_border, 226, new TGeoTranslation(0, ((det_yGlassPos/2.0) + (det_yGlassBorderPos/2.0)), ((det_zAlPos/2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos - (det_zGlassPos/2.0)))); - Rpc_module_upstream1->AddNode(vol_glass_border, 227, new TGeoTranslation(0, (-(det_yGlassPos/2.0) - (det_yGlassBorderPos/2.0)), ((det_zAlPos/2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos - (det_zGlassPos/2.0)))); - Rpc_module_upstream1->AddNode(vol_glass_border1, 228, new TGeoTranslation(((det_xGlassPos/2.0) + (det_xGlassBorderPos/2.0)), 0, ((det_zAlPos/2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos - (det_zGlassPos/2.0)))); - Rpc_module_upstream1->AddNode(vol_glass_border1, 229, new TGeoTranslation((-(det_xGlassPos/2.0) - (det_xGlassBorderPos/2.0)), 0, ((det_zAlPos/2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos - (det_zGlassPos/2.0)))); - - Rpc_module_upstream1->AddNode(vol_glass_border, 230, new TGeoTranslation(0, ((det_yGlassPos/2.0) + (det_yGlassBorderPos/2.0)), ((det_zAlPos/2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos - det_zGlassPos - det_zFreonSF6Pos - (det_zGlassPos/2.0)))); - Rpc_module_upstream1->AddNode(vol_glass_border, 231, new TGeoTranslation(0, (-(det_yGlassPos/2.0) - (det_yGlassBorderPos/2.0)), ((det_zAlPos/2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos - det_zGlassPos - det_zFreonSF6Pos - (det_zGlassPos/2.0)))); - Rpc_module_upstream1->AddNode(vol_glass_border1, 232, new TGeoTranslation(((det_xGlassPos/2.0) + (det_xGlassBorderPos/2.0)), 0, ((det_zAlPos/2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos - det_zGlassPos - det_zFreonSF6Pos - (det_zGlassPos/2.0)))); - Rpc_module_upstream1->AddNode(vol_glass_border1, 233, new TGeoTranslation((-(det_xGlassPos/2.0) - (det_xGlassBorderPos/2.0)), 0, ((det_zAlPos/2.0) - det_zFR4Pos - det_zStripPos- det_dzPMMAPos - det_zGlassPos - det_zFreonSF6Pos - (det_zGlassPos/2.0)))); - - Rpc_module_upstream1->AddNode(vol_glass_border, 234, new TGeoTranslation(0, ((det_yGlassPos/2.0) + (det_yGlassBorderPos/2.0)), ((det_zAlPos/2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos - (det_zGlassPos*2.0) - (det_zFreonSF6Pos*2.0) - (det_zGlassPos/2.0)))); - Rpc_module_upstream1->AddNode(vol_glass_border, 235, new TGeoTranslation(0, (-(det_yGlassPos/2.0) - (det_yGlassBorderPos/2.0)), ((det_zAlPos/2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos - (det_zGlassPos*2.0) - (det_zFreonSF6Pos*2.0) - (det_zGlassPos/2.0)))); - Rpc_module_upstream1->AddNode(vol_glass_border1, 236, new TGeoTranslation(((det_xGlassPos/2.0) + (det_xGlassBorderPos/2.0)), 0, ((det_zAlPos/2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos - (det_zGlassPos*2.0) - (det_zFreonSF6Pos*2.0) - (det_zGlassPos/2.0)))); - Rpc_module_upstream1->AddNode(vol_glass_border1, 237, new TGeoTranslation((-(det_xGlassPos/2.0) - (det_xGlassBorderPos/2.0)), 0, ((det_zAlPos/2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos - (det_zGlassPos*2.0) - (det_zFreonSF6Pos*2.0) - (det_zGlassPos/2.0)))); - - Rpc_module_upstream1->AddNode(vol_glass, 238, new TGeoTranslation(0, 0, ((det_zAlPos/2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos - (det_zGlassPos/2.0)))); - Rpc_module_upstream1->AddNode(vol_glass, 239, new TGeoTranslation(0, 0, ((det_zAlPos/2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos - det_zGlassPos - det_zFreonSF6Pos - (det_zGlassPos/2.0)))); - Rpc_module_upstream1->AddNode(vol_glass, 240, new TGeoTranslation(0, 0, ((det_zAlPos/2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos - (det_zGlassPos*2.0) - (det_zFreonSF6Pos*2.0) - (det_zGlassPos/2.0)))); - - Rpc_module_upstream1->AddNode(vol_FrSF6, 241, new TGeoTranslation(0, 0, ((det_zAlPos/2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos - (det_zGlassPos*1.0) - (det_zFreonSF6Pos/2.0)))); - Rpc_module_upstream1->AddNode(vol_FrSF6, 243, new TGeoTranslation(0, 0, ((det_zAlPos/2.0) - det_zFR4Pos - det_zStripPos - det_dzPMMAPos - (det_zGlassPos*2.0) - (det_zFreonSF6Pos*1.0) - (det_zFreonSF6Pos/2.0)))); - - Rpc_module_upstream1->AddNode(vol_FrSF6_2, 243, new TGeoTranslation(0, ((-det_yGlassPos/2.0) - det_yGlassBorderPos - (det_yFreonSF6Pos_2/2.0)), (-(det_zAlPos/2.0) + (det_dzPMMAPos) + (det_zFreonSF6Pos_2/2.0)))); - Rpc_module_upstream1->AddNode(vol_FrSF6_2, 244, new TGeoTranslation(0, ((det_yGlassPos/2.0) + det_yGlassBorderPos + (det_yFreonSF6Pos_2/2.0)), (-(det_zAlPos/2.0) + (det_dzPMMAPos) + (det_zFreonSF6Pos_2/2.0)))); - Rpc_module_upstream1->AddNode(vol_FrSF6_3, 245, new TGeoTranslation(((det_xGlassPos/2.0) + det_xGlassBorderPos + (det_xFreonSF6Pos_2/2.0)), 0, (-(det_zAlPos/2.0) + (det_dzPMMAPos) + (det_zFreonSF6Pos_2/2.0)))); - Rpc_module_upstream1->AddNode(vol_FrSF6_3, 246, new TGeoTranslation(((-det_xGlassPos/2.0) - det_xGlassBorderPos - (det_xFreonSF6Pos_2/2.0)), 0, (-(det_zAlPos/2.0) + (det_dzPMMAPos) + (det_zFreonSF6Pos_2/2.0)))); - - Rpc_module_upstream1->AddNode(vol_FR4, 247, new TGeoTranslation(0, 0, -(det_zAlPos/2.0) + det_dzPMMAPos + det_zPMMAPos + det_dzPMMAPos + det_zFR4Pos/2.0)); - - Rpc_module_upstream1->AddNode(vol_air, 248, new TGeoTranslation(0, ((-det_yAlPos/2.0) + (det_yAirPos/2.0)), 0)); - Rpc_module_upstream1->AddNode(vol_air, 249, new TGeoTranslation(0, ((det_yAlPos/2.0) - (det_yAirPos/2.0)), 0)); - - interval = 0; - - //Add 64 copper strips to the Rpc module - for(int i = 250; i < 314; i++){ - - Rpc_module_upstream1->AddNode(vol_strip64, i, new TGeoTranslation((-det_xGlassPos/2.0) - det_xGlassBorderPos + 2.175 + (interval*det_xStripPos64) + (interval*0.15) + ((det_xStripPos64/2.0)), 0, -(det_zAlPos/2.0) + det_dzPMMAPos + det_zPMMAPos + det_dzPMMAPos + det_zFR4Pos + (det_zStripPos/2.0) )); - interval++; - } - - - /////////////////////////////////////////////////////////////////// - - //UpstreamTagger_fulldet = new TGeoVolumeAssembly("Upstream_Tagger"); - UpstreamTagger_fulldet = gGeoManager->MakeBox("Upstream_Tagger", Vacuum_box, xbox_fulldet/2.0, ybox_fulldet/2.0, zbox_fulldet/2.0); - UpstreamTagger_fulldet->SetLineColor(kWhite); - - ybox_fulldet = 289 * cm; //resize box to define the modules position from active area of the detectors (discounting the aluminium box + acrilic) - - const double z_layer_1 = -(zbox_fulldet/2.0) + (det_zAlPos/2.0) + det_dzAlPos; - const double z_layer_spacing = det_zAlPos + det_dzAlPos*2.0 + z_space_layers; - const double z_layer_2 = z_layer_1 + z_layer_spacing; - const double z_layer_3 = z_layer_2 + z_layer_spacing; - const double z_layer_4 = z_layer_3 + z_layer_spacing; - const double y_odd_extreme = (ybox_fulldet/2.0) - ((det_yGlassPos)/2.0); - // const double y_even = (ybox_fulldet/2.0) - ((det_yGlassPos)) - ((det_yGlassPos)/2.0) + extra_y; - const double y_even = y_odd_extreme; - - const int n_modules = 10; - - // Module positions - // First Layer - module[1][0] = 0; - module[1][1] = y_odd_extreme; - module[1][2] = z_layer_1; - module[2][0] = 0; - module[2][1] = 0; - module[2][2] = z_layer_1; - module[3][0] = 0; - module[3][1] = -y_odd_extreme; - module[3][2] = z_layer_1; - - // Second Layer - module[4][0] = 0; - module[4][1] = y_even; - module[4][2] = z_layer_2; - module[5][0] = 0; - module[5][1] = -y_even; - module[5][2] = z_layer_2; - - // Third Layer - module[6][0] = 0; - module[6][1] = y_odd_extreme; - module[6][2] = z_layer_3; - module[7][0] = 0; - module[7][1] = 0; - module[7][2] = z_layer_3; - module[8][0] = 0; - module[8][1] = -y_odd_extreme; - module[8][2] = z_layer_3; - - // Fourth Layer - module[9][0] = 0; - module[9][1] = y_even; - module[9][2] = z_layer_4; - module[10][0] = 0; - module[10][1] = -y_even; - module[10][2] = z_layer_4; - - // Add detector nodes - for (auto &&i: TSeq(1, n_modules + 1)) { - if(i%5 == 1 || i%5 == 3) { - // skip unneeded modules to have 3 instead of 5 - continue; + /////////////////////////////////////////////////////////////////// + + // UpstreamTagger_fulldet = new TGeoVolumeAssembly("Upstream_Tagger"); + UpstreamTagger_fulldet = + gGeoManager->MakeBox("Upstream_Tagger", Vacuum_box, xbox_fulldet / 2.0, ybox_fulldet / 2.0, zbox_fulldet / 2.0); + UpstreamTagger_fulldet->SetLineColor(kWhite); + + ybox_fulldet = 289 * cm; // resize box to define the modules position from active area of the detectors + // (discounting the aluminium box + acrilic) + + const double z_layer_1 = -(zbox_fulldet / 2.0) + (det_zAlPos / 2.0) + det_dzAlPos; + const double z_layer_spacing = det_zAlPos + det_dzAlPos * 2.0 + z_space_layers; + const double z_layer_2 = z_layer_1 + z_layer_spacing; + const double z_layer_3 = z_layer_2 + z_layer_spacing; + const double z_layer_4 = z_layer_3 + z_layer_spacing; + const double y_odd_extreme = (ybox_fulldet / 2.0) - ((det_yGlassPos) / 2.0); + // const double y_even = (ybox_fulldet/2.0) - ((det_yGlassPos)) - ((det_yGlassPos)/2.0) + extra_y; + const double y_even = y_odd_extreme; + + const int n_modules = 10; + + // Module positions + // First Layer + module[1][0] = 0; + module[1][1] = y_odd_extreme; + module[1][2] = z_layer_1; + module[2][0] = 0; + module[2][1] = 0; + module[2][2] = z_layer_1; + module[3][0] = 0; + module[3][1] = -y_odd_extreme; + module[3][2] = z_layer_1; + + // Second Layer + module[4][0] = 0; + module[4][1] = y_even; + module[4][2] = z_layer_2; + module[5][0] = 0; + module[5][1] = -y_even; + module[5][2] = z_layer_2; + + // Third Layer + module[6][0] = 0; + module[6][1] = y_odd_extreme; + module[6][2] = z_layer_3; + module[7][0] = 0; + module[7][1] = 0; + module[7][2] = z_layer_3; + module[8][0] = 0; + module[8][1] = -y_odd_extreme; + module[8][2] = z_layer_3; + + // Fourth Layer + module[9][0] = 0; + module[9][1] = y_even; + module[9][2] = z_layer_4; + module[10][0] = 0; + module[10][1] = -y_even; + module[10][2] = z_layer_4; + + // Add detector nodes + for (auto&& i : TSeq(1, n_modules + 1)) { + if (i % 5 == 1 || i % 5 == 3) { + // skip unneeded modules to have 3 instead of 5 + continue; + } + UpstreamTagger_fulldet->AddNode( + Rpc_module_upstream1, i, new TGeoTranslation(module[i][0], module[i][1], module[i][2])); + UpstreamTagger_fulldet->AddNode(Rpc_module_upstream, + i + n_modules, + new TGeoTranslation(module[i][0], module[i][1], -module[n_modules + 1 - i][2])); } - UpstreamTagger_fulldet->AddNode(Rpc_module_upstream1, i, new TGeoTranslation(module[i][0], module[i][1], module[i][2])); - UpstreamTagger_fulldet->AddNode(Rpc_module_upstream, i + n_modules, new TGeoTranslation(module[i][0], module[i][1], -module[n_modules + 1 - i][2])); - } - top->AddNode(UpstreamTagger_fulldet, 1, new TGeoTranslation(0.0, 0.0, det_zPos)); + top->AddNode(UpstreamTagger_fulldet, 1, new TGeoTranslation(0.0, 0.0, det_zPos)); - cout << " Z Position (Upstream Tagger1) " << det_zPos << endl; - ////////////////////////////////////////////////////////////////// + cout << " Z Position (Upstream Tagger1) " << det_zPos << endl; + ////////////////////////////////////////////////////////////////// - return; + return; } - - -UpstreamTaggerPoint* UpstreamTagger::AddHit(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t time, Double_t length, - Double_t eLoss, Int_t pdgCode,TVector3 Lpos, TVector3 Lmom) +UpstreamTaggerPoint* UpstreamTagger::AddHit(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t time, + Double_t length, + Double_t eLoss, + Int_t pdgCode, + TVector3 Lpos, + TVector3 Lmom) { - TClonesArray& clref = *fUpstreamTaggerPointCollection; - Int_t size = clref.GetEntriesFast(); + TClonesArray& clref = *fUpstreamTaggerPointCollection; + Int_t size = clref.GetEntriesFast(); - return new(clref[size]) UpstreamTaggerPoint(trackID, detID, pos, mom, - time, length, eLoss, pdgCode,Lpos,Lmom); + return new (clref[size]) UpstreamTaggerPoint(trackID, detID, pos, mom, time, length, eLoss, pdgCode, Lpos, Lmom); } diff --git a/UpstreamTagger/UpstreamTagger.h b/UpstreamTagger/UpstreamTagger.h index 714c2a20d1..2d4be99965 100644 --- a/UpstreamTagger/UpstreamTagger.h +++ b/UpstreamTagger/UpstreamTagger.h @@ -2,26 +2,25 @@ #define UPSTREAMTAGGER_H #include "FairDetector.h" -#include "TVector3.h" -#include "TLorentzVector.h" #include "ShipUnit.h" +#include "TLorentzVector.h" +#include "TVector3.h" class UpstreamTaggerPoint; class FairVolume; class TClonesArray; -using ShipUnit::m; using ShipUnit::cm; +using ShipUnit::m; -class UpstreamTagger: public FairDetector +class UpstreamTagger : public FairDetector { public: - /** Name : Detector Name * Active: kTRUE for active detectors (ProcessHits() will be called) * kFALSE for inactive detectors - */ + */ UpstreamTagger(const char* Name, Bool_t Active); /** default constructor */ @@ -31,12 +30,12 @@ class UpstreamTagger: public FairDetector virtual ~UpstreamTagger(); /** Initialization of the detector is done here */ - virtual void Initialize(); + virtual void Initialize(); /** this method is called for each step during simulation * (see FairMCApplication::Stepping()) - */ - virtual Bool_t ProcessHits( FairVolume* v=0); + */ + virtual Bool_t ProcessHits(FairVolume* v = 0); /** Registers the produced collections in FAIRRootManager. */ virtual void Register(); @@ -48,133 +47,137 @@ class UpstreamTagger: public FairDetector virtual void Reset(); /** Sets detector position and sizes */ - void SetZposition(Double_t z) {det_zPos = z;} - void SetSizeX_Glass(Double_t xg) {det_xGlassPos = xg;} - void SetSizeY_Glass(Double_t yg) {det_yGlassPos = yg;} - void SetSizeZ_Glass(Double_t zg) {det_zGlassPos = zg;} - void SetSizeX_Glass_Border(Double_t xgB) {det_xGlassBorderPos = xgB;} - void SetSizeY_Glass_Border(Double_t ygB) {det_yGlassBorderPos = ygB;} - void SetSizeZ_Glass_Border(Double_t zgB) {det_zGlassBorderPos = zgB;} - void SetSizeX_PMMA(Double_t xpmma) {det_xPMMAPos = xpmma;} - void SetSizeY_PMMA(Double_t ypmma) {det_yPMMAPos = ypmma;} - void SetSizeZ_PMMA(Double_t zpmma) {det_zPMMAPos = zpmma;} - void SetSizeDX_PMMA(Double_t dxpmma) {det_dxPMMAPos = dxpmma;} - void SetSizeDY_PMMA(Double_t dypmma) {det_dyPMMAPos = dypmma;} - void SetSizeDZ_PMMA(Double_t dzpmma) {det_dzPMMAPos = dzpmma;} - void SetSizeX_FreonSF6(Double_t xfSF6) {det_xFreonSF6Pos = xfSF6;} - void SetSizeY_FreonSF6(Double_t yfSF6) {det_yFreonSF6Pos = yfSF6;} - void SetSizeZ_FreonSF6(Double_t zfSF6) {det_zFreonSF6Pos = zfSF6;} - void SetSizeX_FreonSF6_2(Double_t xfSF6_2) {det_xFreonSF6Pos_2 = xfSF6_2;} - void SetSizeY_FreonSF6_2(Double_t yfSF6_2) {det_yFreonSF6Pos_2 = yfSF6_2;} - void SetSizeZ_FreonSF6_2(Double_t zfSF6_2) {det_zFreonSF6Pos_2 = zfSF6_2;} - void SetSizeX_FR4(Double_t xf) {det_xFR4Pos = xf;} - void SetSizeY_FR4(Double_t yf) {det_yFR4Pos = yf;} - void SetSizeZ_FR4(Double_t zf) {det_zFR4Pos = zf;} - void SetSizeX_Al(Double_t xal) {det_xAlPos = xal;} - void SetSizeY_Al(Double_t yal) {det_yAlPos = yal;} - void SetSizeZ_Al(Double_t zal) {det_zAlPos = zal;} - void SetSizeDX_Al(Double_t dxal) {det_dxAlPos = dxal;} - void SetSizeDY_Al(Double_t dyal) {det_dyAlPos = dyal;} - void SetSizeDZ_Al(Double_t dzal) {det_dzAlPos = dzal;} - void SetSizeX_Air(Double_t xair) {det_xAirPos = xair;} - void SetSizeY_Air(Double_t yair) {det_yAirPos = yair;} - void SetSizeZ_Air(Double_t zair) {det_zAirPos = zair;} - void SetSizeX_Strip(Double_t xstrip) {det_xStripPos = xstrip;} - void SetSizeY_Strip(Double_t ystrip) {det_yStripPos = ystrip;} - void SetSizeX_Strip64(Double_t xstrip64) {det_xStripPos64 = xstrip64;} - void SetSizeY_Strip64(Double_t ystrip64) {det_yStripPos64 = ystrip64;} - void SetSizeZ_Strip(Double_t zstrip) {det_zStripPos = zstrip;} + void SetZposition(Double_t z) { det_zPos = z; } + void SetSizeX_Glass(Double_t xg) { det_xGlassPos = xg; } + void SetSizeY_Glass(Double_t yg) { det_yGlassPos = yg; } + void SetSizeZ_Glass(Double_t zg) { det_zGlassPos = zg; } + void SetSizeX_Glass_Border(Double_t xgB) { det_xGlassBorderPos = xgB; } + void SetSizeY_Glass_Border(Double_t ygB) { det_yGlassBorderPos = ygB; } + void SetSizeZ_Glass_Border(Double_t zgB) { det_zGlassBorderPos = zgB; } + void SetSizeX_PMMA(Double_t xpmma) { det_xPMMAPos = xpmma; } + void SetSizeY_PMMA(Double_t ypmma) { det_yPMMAPos = ypmma; } + void SetSizeZ_PMMA(Double_t zpmma) { det_zPMMAPos = zpmma; } + void SetSizeDX_PMMA(Double_t dxpmma) { det_dxPMMAPos = dxpmma; } + void SetSizeDY_PMMA(Double_t dypmma) { det_dyPMMAPos = dypmma; } + void SetSizeDZ_PMMA(Double_t dzpmma) { det_dzPMMAPos = dzpmma; } + void SetSizeX_FreonSF6(Double_t xfSF6) { det_xFreonSF6Pos = xfSF6; } + void SetSizeY_FreonSF6(Double_t yfSF6) { det_yFreonSF6Pos = yfSF6; } + void SetSizeZ_FreonSF6(Double_t zfSF6) { det_zFreonSF6Pos = zfSF6; } + void SetSizeX_FreonSF6_2(Double_t xfSF6_2) { det_xFreonSF6Pos_2 = xfSF6_2; } + void SetSizeY_FreonSF6_2(Double_t yfSF6_2) { det_yFreonSF6Pos_2 = yfSF6_2; } + void SetSizeZ_FreonSF6_2(Double_t zfSF6_2) { det_zFreonSF6Pos_2 = zfSF6_2; } + void SetSizeX_FR4(Double_t xf) { det_xFR4Pos = xf; } + void SetSizeY_FR4(Double_t yf) { det_yFR4Pos = yf; } + void SetSizeZ_FR4(Double_t zf) { det_zFR4Pos = zf; } + void SetSizeX_Al(Double_t xal) { det_xAlPos = xal; } + void SetSizeY_Al(Double_t yal) { det_yAlPos = yal; } + void SetSizeZ_Al(Double_t zal) { det_zAlPos = zal; } + void SetSizeDX_Al(Double_t dxal) { det_dxAlPos = dxal; } + void SetSizeDY_Al(Double_t dyal) { det_dyAlPos = dyal; } + void SetSizeDZ_Al(Double_t dzal) { det_dzAlPos = dzal; } + void SetSizeX_Air(Double_t xair) { det_xAirPos = xair; } + void SetSizeY_Air(Double_t yair) { det_yAirPos = yair; } + void SetSizeZ_Air(Double_t zair) { det_zAirPos = zair; } + void SetSizeX_Strip(Double_t xstrip) { det_xStripPos = xstrip; } + void SetSizeY_Strip(Double_t ystrip) { det_yStripPos = ystrip; } + void SetSizeX_Strip64(Double_t xstrip64) { det_xStripPos64 = xstrip64; } + void SetSizeY_Strip64(Double_t ystrip64) { det_yStripPos64 = ystrip64; } + void SetSizeZ_Strip(Double_t zstrip) { det_zStripPos = zstrip; } /** Create the detector geometry */ void ConstructGeometry(); /** This method is an example of how to add your own point * of type TimeRpcPoint to the clones array - */ - UpstreamTaggerPoint* AddHit(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t time, Double_t length, - Double_t eLoss, Int_t pdgCode,TVector3 Lpos, TVector3 Lmom); - - virtual void EndOfEvent(); - virtual void FinishPrimary() {;} - virtual void FinishRun() {;} - virtual void BeginPrimary() {;} - virtual void PostTrack() {;} - virtual void PreTrack() {;} - virtual void BeginEvent() {;} - - Double_t module[11][3]; // x,y,z centre positions for each module + */ + UpstreamTaggerPoint* AddHit(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t time, + Double_t length, + Double_t eLoss, + Int_t pdgCode, + TVector3 Lpos, + TVector3 Lmom); + + virtual void EndOfEvent(); + virtual void FinishPrimary() { ; } + virtual void FinishRun() { ; } + virtual void BeginPrimary() { ; } + virtual void PostTrack() { ; } + virtual void PreTrack() { ; } + virtual void BeginEvent() { ; } + + Double_t module[11][3]; // x,y,z centre positions for each module // TODO Avoid 1-indexed array! /** Track information to be stored until the track leaves the active volume.*/ - Int_t fTrackID; //! track index - Int_t fVolumeID; //! volume id - TLorentzVector fPos; //! position at entrance - TLorentzVector fMom; //! momentum at entrance - Double_t fTime; //! time - Double_t fLength; //! length - Double_t fELoss; //! energy loss + Int_t fTrackID; //! track index + Int_t fVolumeID; //! volume id + TLorentzVector fPos; //! position at entrance + TLorentzVector fMom; //! momentum at entrance + Double_t fTime; //! time + Double_t fLength; //! length + Double_t fELoss; //! energy loss /** Detector parameters.*/ - Double_t det_zPos; //! z-position of veto station - Double_t det_xGlassPos; //! x-size of Active Glass plates - Double_t det_yGlassPos; //! y-size of Active Glass plates - Double_t det_zGlassPos; //! z-size of Active Glass plates + Double_t det_zPos; //! z-position of veto station + Double_t det_xGlassPos; //! x-size of Active Glass plates + Double_t det_yGlassPos; //! y-size of Active Glass plates + Double_t det_zGlassPos; //! z-size of Active Glass plates - Double_t det_xGlassBorderPos; //! x-size of Inactive Glass plates - Double_t det_yGlassBorderPos; //! y-size of Inactive Glass plates - Double_t det_zGlassBorderPos; //! z-size of Inactive Glass plates + Double_t det_xGlassBorderPos; //! x-size of Inactive Glass plates + Double_t det_yGlassBorderPos; //! y-size of Inactive Glass plates + Double_t det_zGlassBorderPos; //! z-size of Inactive Glass plates - Double_t det_xPMMAPos; //! x-size of PMMA box - Double_t det_yPMMAPos; //! y-size of PMMA box - Double_t det_zPMMAPos; //! z-size of PMMA box + Double_t det_xPMMAPos; //! x-size of PMMA box + Double_t det_yPMMAPos; //! y-size of PMMA box + Double_t det_zPMMAPos; //! z-size of PMMA box - Double_t det_dxPMMAPos; //! x-thickness of PMMA box - Double_t det_dyPMMAPos; //! y-thickness of PMMA box - Double_t det_dzPMMAPos; //! z-thickness of PMMA box + Double_t det_dxPMMAPos; //! x-thickness of PMMA box + Double_t det_dyPMMAPos; //! y-thickness of PMMA box + Double_t det_dzPMMAPos; //! z-thickness of PMMA box - Double_t det_xFreonSF6Pos; //! x-size of gas gap - Double_t det_yFreonSF6Pos; //! y-size of gas gap - Double_t det_zFreonSF6Pos; //! z-size of gas gap + Double_t det_xFreonSF6Pos; //! x-size of gas gap + Double_t det_yFreonSF6Pos; //! y-size of gas gap + Double_t det_zFreonSF6Pos; //! z-size of gas gap - Double_t det_xFreonSF6Pos_2; //! x-size of gas gap - Double_t det_yFreonSF6Pos_2; //! y-size of gas gap - Double_t det_zFreonSF6Pos_2; //! z-size of gas gap + Double_t det_xFreonSF6Pos_2; //! x-size of gas gap + Double_t det_yFreonSF6Pos_2; //! y-size of gas gap + Double_t det_zFreonSF6Pos_2; //! z-size of gas gap - Double_t det_xFR4Pos; //! x-size of FR4 box - Double_t det_yFR4Pos; //! y-size of FR4 box - Double_t det_zFR4Pos; //! z-size of FR4 box + Double_t det_xFR4Pos; //! x-size of FR4 box + Double_t det_yFR4Pos; //! y-size of FR4 box + Double_t det_zFR4Pos; //! z-size of FR4 box - Double_t det_xAlPos; //! x-size of Aluminium box - Double_t det_yAlPos; //! y-size of Aluminium box - Double_t det_zAlPos; //! z-size of Aluminium box + Double_t det_xAlPos; //! x-size of Aluminium box + Double_t det_yAlPos; //! y-size of Aluminium box + Double_t det_zAlPos; //! z-size of Aluminium box - Double_t det_dxAlPos; //! x-thickness of Aluminium box - Double_t det_dyAlPos; //! y-thickness of Aluminium box - Double_t det_dzAlPos; //! z-thickness of Aluminium box + Double_t det_dxAlPos; //! x-thickness of Aluminium box + Double_t det_dyAlPos; //! y-thickness of Aluminium box + Double_t det_dzAlPos; //! z-thickness of Aluminium box - Double_t det_xAirPos; //! x-size of Aluminium box - Double_t det_yAirPos; //! y-size of Aluminium box - Double_t det_zAirPos; //! z-size of Aluminium box + Double_t det_xAirPos; //! x-size of Aluminium box + Double_t det_yAirPos; //! y-size of Aluminium box + Double_t det_zAirPos; //! z-size of Aluminium box - Double_t det_xStripPos64; //! x-size of Strip for modules with 64 strips - Double_t det_yStripPos64; //! y-size of Strip for modules with 64 strips - Double_t det_xStripPos; //! x-size of Strip for modules with 32 strips - Double_t det_yStripPos; //! y-size of Strip for modules with 32 strips - Double_t det_zStripPos; //! z-size of Strip + Double_t det_xStripPos64; //! x-size of Strip for modules with 64 strips + Double_t det_yStripPos64; //! y-size of Strip for modules with 64 strips + Double_t det_xStripPos; //! x-size of Strip for modules with 32 strips + Double_t det_yStripPos; //! y-size of Strip for modules with 32 strips + Double_t det_zStripPos; //! z-size of Strip - Double_t xbox_fulldet = 1.2 * m; //cm + Double_t xbox_fulldet = 1.2 * m; // cm Double_t ybox_fulldet = 2.97 * m; Double_t zbox_fulldet = 17.0024; Double_t z_space_layers = 0.2; - Double_t extra_y = 6.5 * cm; // overlap between modules - + Double_t extra_y = 6.5 * cm; // overlap between modules private: - - TGeoVolume* UpstreamTagger_fulldet; // Timing_detector_1 object + TGeoVolume* UpstreamTagger_fulldet; // Timing_detector_1 object /** container for data points */ TClonesArray* fUpstreamTaggerPointCollection; @@ -183,8 +186,7 @@ class UpstreamTagger: public FairDetector UpstreamTagger& operator=(const UpstreamTagger&); Int_t InitMedium(const char* name); - - ClassDef(UpstreamTagger,1) + ClassDef(UpstreamTagger, 1) }; -#endif //UPSTREAMTAGGER_H +#endif // UPSTREAMTAGGER_H diff --git a/UpstreamTagger/UpstreamTaggerHit.cxx b/UpstreamTagger/UpstreamTaggerHit.cxx index c996a5a1ad..5deaa3a8c2 100644 --- a/UpstreamTagger/UpstreamTaggerHit.cxx +++ b/UpstreamTagger/UpstreamTaggerHit.cxx @@ -1,114 +1,124 @@ #include "UpstreamTaggerHit.h" -#include "UpstreamTagger.h" -#include "TVector3.h" -#include "TMath.h" -#include "TRandom1.h" -#include "TRandom3.h" -#include "TGeoManager.h" + #include "TGeoBBox.h" +#include "TGeoManager.h" #include "TGeoNode.h" +#include "TMath.h" +#include "TRandom1.h" #include "TRandom3.h" +#include "TVector3.h" +#include "UpstreamTagger.h" -#include #include -#include /* srand, rand */ #include #include -#include /* time */ +#include +#include /* srand, rand */ +#include /* time */ using std::cout; using std::endl; -Double_t speedOfLight = TMath::C() *100./1000000000.0 ; // from m/sec to cm/ns +Double_t speedOfLight = TMath::C() * 100. / 1000000000.0; // from m/sec to cm/ns // ----- Default constructor -------------- UpstreamTaggerHit::UpstreamTaggerHit() - : ShipHit() + : ShipHit() { - flag = true; + flag = true; } - // ----- constructor from TimeDetPoint from TimeDetHit------------------------------- UpstreamTaggerHit::UpstreamTaggerHit(UpstreamTaggerPoint* p, UpstreamTagger* c, Double_t t0) - : ShipHit() + : ShipHit() { - fDetectorID = p->GetDetectorID(); - c0 = c; - - Double_t a1, b1, c1; - a1 = p->GetX(); b1 = p->GetY(); c1 = p->GetZ(); - const Double_t * point1[3]; - point1[0] = &a1; point1[1] = &b1; point1[2] = &c1; - point_final[0] = *point1[0];point_final[1] = *point1[1];point_final[2] = *point1[2]; - - Double_t a2, b2, c2; - a2 = p->GetPx(); b2 = p->GetPy(); c2 = p->GetPz(); - mom[0] = &a2; mom[1] = &b2; mom[2] = &c2; - - Float_t lpos, lneg; - Dist(p->GetX(), lpos, lneg); - Double_t sigma = T_resol; // in ns - t_1 = gRandom->Gaus( 0, sigma ) + lneg/v_drift + t0 + p->GetTime(); - t_2 = gRandom->Gaus( 0, sigma ) + lpos/v_drift + t0 + p->GetTime(); - + fDetectorID = p->GetDetectorID(); + c0 = c; + + Double_t a1, b1, c1; + a1 = p->GetX(); + b1 = p->GetY(); + c1 = p->GetZ(); + const Double_t* point1[3]; + point1[0] = &a1; + point1[1] = &b1; + point1[2] = &c1; + point_final[0] = *point1[0]; + point_final[1] = *point1[1]; + point_final[2] = *point1[2]; + + Double_t a2, b2, c2; + a2 = p->GetPx(); + b2 = p->GetPy(); + c2 = p->GetPz(); + mom[0] = &a2; + mom[1] = &b2; + mom[2] = &c2; + + Float_t lpos, lneg; + Dist(p->GetX(), lpos, lneg); + Double_t sigma = T_resol; // in ns + t_1 = gRandom->Gaus(0, sigma) + lneg / v_drift + t0 + p->GetTime(); + t_2 = gRandom->Gaus(0, sigma) + lpos / v_drift + t0 + p->GetTime(); } - // ----- Destructor ------------------------- -UpstreamTaggerHit::~UpstreamTaggerHit() { } +UpstreamTaggerHit::~UpstreamTaggerHit() {} // ---- return time information for a given track extrapolation -std::vector UpstreamTaggerHit::GetTime(Double_t x){ - // calculate distance to left and right end - Float_t lpos, lneg; - Dist(x, lpos, lneg); - Double_t dt = T_resol; - Double_t t = ( (t_1-lneg/v_drift) + (t_2-lpos/v_drift) )/2; - std::vector retVal; - retVal.push_back(t); - retVal.push_back(dt); - return retVal; +std::vector UpstreamTaggerHit::GetTime(Double_t x) +{ + // calculate distance to left and right end + Float_t lpos, lneg; + Dist(x, lpos, lneg); + Double_t dt = T_resol; + Double_t t = ((t_1 - lneg / v_drift) + (t_2 - lpos / v_drift)) / 2; + std::vector retVal; + retVal.push_back(t); + retVal.push_back(dt); + return retVal; } // ---- return mean time information -std::vector UpstreamTaggerHit::GetTime(){ - TGeoBBox* shape = (TGeoBBox*)gGeoManager->GetVolume("UpstreamTagger")->GetShape(); - Double_t t0; - if(RpcModule < 6) - t0 = (t_1+t_2)/2. - 114.5/v_drift;// strip length = 229 cm in x - else - t0 = (t_1+t_2)/2. - 55.5/v_drift;// strip length = 111 cm in y - Double_t dt = T_resol; - std::vector retVal; - retVal.push_back(t0); - retVal.push_back(dt); - return retVal; +std::vector UpstreamTaggerHit::GetTime() +{ + TGeoBBox* shape = (TGeoBBox*)gGeoManager->GetVolume("UpstreamTagger")->GetShape(); + Double_t t0; + if (RpcModule < 6) + t0 = (t_1 + t_2) / 2. - 114.5 / v_drift; // strip length = 229 cm in x + else + t0 = (t_1 + t_2) / 2. - 55.5 / v_drift; // strip length = 111 cm in y + Double_t dt = T_resol; + std::vector retVal; + retVal.push_back(t0); + retVal.push_back(dt); + return retVal; } -std::vector UpstreamTaggerHit::GetMeasurements(){ - std::vector retVal; - retVal.push_back( t_1); - retVal.push_back( t_2); - return retVal; +std::vector UpstreamTaggerHit::GetMeasurements() +{ + std::vector retVal; + retVal.push_back(t_1); + retVal.push_back(t_2); + return retVal; } // distance to edges -void UpstreamTaggerHit::Dist(Float_t x, Float_t& lpos, Float_t& lneg){ - - Double_t hit_final; - Int_t mod; - TGeoNode* node = GetNode(hit_final, mod); - auto shape = dynamic_cast(node->GetVolume()->GetShape()); - TVector3 pos = GetXYZ(); - if(mod > 0 && mod < 6){ - lpos = TMath::Abs( pos.X() + 114.5 - hit_final ); // strip length = 229 cm in x - lneg = TMath::Abs( pos.X() - 114.5 - hit_final ); - } - else if (mod >= 6){ - lpos = TMath::Abs( pos.Y() + 55.5 - hit_final ); // strip length = 111 cm in y - lneg = TMath::Abs( pos.Y() - 55.5 - hit_final ); - } +void UpstreamTaggerHit::Dist(Float_t x, Float_t& lpos, Float_t& lneg) +{ + + Double_t hit_final; + Int_t mod; + TGeoNode* node = GetNode(hit_final, mod); + auto shape = dynamic_cast(node->GetVolume()->GetShape()); + TVector3 pos = GetXYZ(); + if (mod > 0 && mod < 6) { + lpos = TMath::Abs(pos.X() + 114.5 - hit_final); // strip length = 229 cm in x + lneg = TMath::Abs(pos.X() - 114.5 - hit_final); + } else if (mod >= 6) { + lpos = TMath::Abs(pos.Y() + 55.5 - hit_final); // strip length = 111 cm in y + lneg = TMath::Abs(pos.Y() - 55.5 - hit_final); + } } // ---------------------------------------------- TVector3 UpstreamTaggerHit::GetXYZ() @@ -117,235 +127,267 @@ TVector3 UpstreamTaggerHit::GetXYZ() Int_t mod; TGeoNavigator* nav = gGeoManager->GetCurrentNavigator(); TGeoNode* node = GetNode(hit_final, mod); - auto shape = dynamic_cast(node->GetVolume()->GetShape()); - Double_t origin[3] = {shape->GetOrigin()[0],shape->GetOrigin()[1],shape->GetOrigin()[2]}; - Double_t master[3] = {0,0,0}; - nav->LocalToMaster(origin,master); - TVector3 pos = TVector3(master[0],master[1],master[2]); + auto shape = dynamic_cast(node->GetVolume()->GetShape()); + Double_t origin[3] = {shape->GetOrigin()[0], shape->GetOrigin()[1], shape->GetOrigin()[2]}; + Double_t master[3] = {0, 0, 0}; + nav->LocalToMaster(origin, master); + TVector3 pos = TVector3(master[0], master[1], master[2]); return pos; } - Double_t UpstreamTaggerHit::GetX() -{ TVector3 pos = GetXYZ(); - return pos.X(); +{ + TVector3 pos = GetXYZ(); + return pos.X(); } - Double_t UpstreamTaggerHit::GetY() -{ TVector3 pos = GetXYZ(); - return pos.Y(); +{ + TVector3 pos = GetXYZ(); + return pos.Y(); } - Double_t UpstreamTaggerHit::GetZ() -{ TVector3 pos = GetXYZ(); - return pos.Z(); +{ + TVector3 pos = GetXYZ(); + return pos.Z(); } - -TGeoNode* UpstreamTaggerHit::GetNode(Double_t &hit_final, Int_t &mod) +TGeoNode* UpstreamTaggerHit::GetNode(Double_t& hit_final, Int_t& mod) { - TGeoNavigator* nav = gGeoManager->GetCurrentNavigator(); - mod = 0; - - Double_t XHit1 = point_final[0]; - Double_t YHit1 = point_final[1]; - Double_t ZHit1 = point_final[2]; - - const Double_t PxHit1 = *mom[0]; - const Double_t PyHit1 = *mom[1]; - const Double_t PzHit1 = *mom[2]; - - Double_t Ymodule1 = -1000; - Double_t Zmodule1 = 0; - Double_t Xmodule11 = -1000; - Double_t Zmodule11 = 0; - Double_t dist1 = 1000; - - Int_t flag0 = 1; - - c0->ybox_fulldet = 499; //resize box to define the modules position from active area of the detectors (discounting the aluminium box + acrilic) + TGeoNavigator* nav = gGeoManager->GetCurrentNavigator(); + mod = 0; + + Double_t XHit1 = point_final[0]; + Double_t YHit1 = point_final[1]; + Double_t ZHit1 = point_final[2]; + + const Double_t PxHit1 = *mom[0]; + const Double_t PyHit1 = *mom[1]; + const Double_t PzHit1 = *mom[2]; + + Double_t Ymodule1 = -1000; + Double_t Zmodule1 = 0; + Double_t Xmodule11 = -1000; + Double_t Zmodule11 = 0; + Double_t dist1 = 1000; + + Int_t flag0 = 1; + + c0->ybox_fulldet = 499; // resize box to define the modules position from active area of the detectors + // (discounting the aluminium box + acrilic) + + // First Layer of full Rpc detector covering 2.23 x 4.99 meters with 32 strips + c0->module[1][0] = 0; + c0->module[1][1] = ((c0->ybox_fulldet / 2.0) - ((c0->det_yGlassPos) / 2.0)); + c0->module[1][2] = (-(c0->zbox_fulldet / 2.0) + (c0->det_zAlPos / 2.0) + c0->det_dzAlPos); + c0->module[2][0] = 0; + c0->module[2][1] = 0; + c0->module[2][2] = (-(c0->zbox_fulldet / 2.0) + (c0->det_zAlPos / 2.0) + c0->det_dzAlPos); + c0->module[3][0] = 0; + c0->module[3][1] = -((c0->ybox_fulldet / 2.0) - ((c0->det_yGlassPos) / 2.0)); + c0->module[3][2] = (-(c0->zbox_fulldet / 2.0) + (c0->det_zAlPos / 2.0) + c0->det_dzAlPos); + + // Second Layer of full Rpc detector covering 2.23 x 4.99 meters with 32 strips + c0->module[4][0] = 0; + c0->module[4][1] = ((c0->ybox_fulldet / 2.0) - ((c0->det_yGlassPos)) - ((c0->det_yGlassPos) / 2.0) + c0->extra_y); + c0->module[4][2] = (-(c0->zbox_fulldet / 2.0) + c0->det_zAlPos + c0->det_dzAlPos * 3.0 + c0->z_space_layers + + (c0->det_zAlPos / 2.0)); + c0->module[5][0] = 0; + c0->module[5][1] = -((c0->ybox_fulldet / 2.0) - ((c0->det_yGlassPos)) - ((c0->det_yGlassPos) / 2.0) + c0->extra_y); + c0->module[5][2] = (-(c0->zbox_fulldet / 2.0) + c0->det_zAlPos + c0->det_dzAlPos * 3.0 + c0->z_space_layers + + (c0->det_zAlPos / 2.0)); + + // Third Layer of full Rpc detector covering 2.23 x 4.99 meters with 64 strips + c0->module[6][0] = 0; + c0->module[6][1] = ((c0->ybox_fulldet / 2.0) - ((c0->det_yGlassPos) / 2.0)); + c0->module[6][2] = (-(c0->zbox_fulldet / 2.0) + (c0->det_zAlPos * 2.0) + c0->det_dzAlPos * 5.0 + + (c0->z_space_layers * 2.0) + (c0->det_zAlPos / 2.0)); + c0->module[7][0] = 0; + c0->module[7][1] = 0; + c0->module[7][2] = (-(c0->zbox_fulldet / 2.0) + (c0->det_zAlPos * 2.0) + c0->det_dzAlPos * 5.0 + + (c0->z_space_layers * 3.0) + (c0->det_zAlPos / 2.0)); + c0->module[8][0] = 0; + c0->module[8][1] = -((c0->ybox_fulldet / 2.0) - ((c0->det_yGlassPos) / 2.0)); + c0->module[8][2] = (-(c0->zbox_fulldet / 2.0) + (c0->det_zAlPos * 2.0) + c0->det_dzAlPos * 5.0 + + (c0->z_space_layers * 2.0) + (c0->det_zAlPos / 2.0)); + + // Fourth Layer of full Rpc detector covering 2.23 x 4.99 meters with 64 strips + c0->module[9][0] = 0; + c0->module[9][1] = ((c0->ybox_fulldet / 2.0) - ((c0->det_yGlassPos)) - ((c0->det_yGlassPos) / 2.0) + c0->extra_y); + c0->module[9][2] = (-(c0->zbox_fulldet / 2.0) + (c0->det_zAlPos * 3.0) + c0->det_dzAlPos * 7.0 + + (c0->z_space_layers * 3.0) + (c0->det_zAlPos / 2.0)); + c0->module[10][0] = 0; + c0->module[10][1] = -((c0->ybox_fulldet / 2.0) - ((c0->det_yGlassPos)) - ((c0->det_yGlassPos) / 2.0) + c0->extra_y); + c0->module[10][2] = (-(c0->zbox_fulldet / 2.0) + (c0->det_zAlPos * 3.0) + c0->det_dzAlPos * 7.0 + + (c0->z_space_layers * 3.0) + (c0->det_zAlPos / 2.0)); + + for (int i = 1; i <= 10; i++) { + + if (XHit1 >= c0->module[i][0] - (c0->det_xGlassPos) / 2.0 + && XHit1 <= c0->module[i][0] + (c0->det_xGlassPos) / 2.0 + && YHit1 >= c0->module[i][1] - (c0->det_yGlassPos) / 2.0 + && YHit1 <= c0->module[i][1] + (c0->det_yGlassPos) / 2.0 + && ZHit1 >= c0->det_zPos + (c0->module[i][2] - (c0->det_zAlPos + 2 * c0->det_dzAlPos) / 2.0) + && ZHit1 <= c0->det_zPos + (c0->module[i][2] + (c0->det_zAlPos + 2 * c0->det_dzAlPos) / 2.0)) { + + if (fabs(c0->det_zPos + c0->module[i][2] - ZHit1) < dist1) { + + if (flag0) { + RpcDetector = 1; + mod = i; + } else { + RpcDetector = 2; + mod = i + 10; + } + + if (i < 6) { + Zmodule1 = c0->det_zPos + c0->module[i][2] + c0->det_zAlPos - c0->det_zStripPos; + Ymodule1 = c0->module[i][1] - (c0->det_yGlassPos + 2 * c0->det_yGlassBorderPos) / 2.0 + 1.5; + } else { + Zmodule11 = c0->det_zPos + c0->module[i][2] + c0->det_zAlPos - c0->det_zStripPos; + Xmodule11 = c0->module[i][0] - (c0->det_xGlassPos + 2 * c0->det_xGlassBorderPos) / 2.0 + 2.175; + } + dist1 = fabs(c0->det_zPos + c0->module[i][2] - ZHit1); + } + } + if (i == 10 && flag0) { + Double_t tmp = -c0->module[6][2]; + Double_t tmp1 = -c0->module[4][2]; + Double_t tmp2 = -c0->module[1][2]; + + c0->module[1][2] = -c0->module[9][2]; + c0->module[2][2] = -c0->module[9][2]; + c0->module[3][2] = -c0->module[9][2]; + c0->module[4][2] = tmp; + c0->module[5][2] = tmp; + + c0->module[6][2] = tmp1; + c0->module[7][2] = tmp1; + c0->module[8][2] = tmp1; + c0->module[9][2] = tmp2; + c0->module[10][2] = tmp2; + + i = 0; + flag0 = 0; + } + } - //First Layer of full Rpc detector covering 2.23 x 4.99 meters with 32 strips - c0->module[1][0] = 0; c0->module[1][1] = ((c0->ybox_fulldet/2.0) - ((c0->det_yGlassPos)/2.0)); c0->module[1][2] = (-(c0->zbox_fulldet/2.0) + (c0->det_zAlPos/2.0) + c0->det_dzAlPos); - c0->module[2][0] = 0; c0->module[2][1] = 0; c0->module[2][2] = (-(c0->zbox_fulldet/2.0) + (c0->det_zAlPos/2.0) + c0->det_dzAlPos); - c0->module[3][0] = 0; c0->module[3][1] = -((c0->ybox_fulldet/2.0) - ((c0->det_yGlassPos)/2.0)); c0->module[3][2] = (-(c0->zbox_fulldet/2.0) + (c0->det_zAlPos/2.0) + c0->det_dzAlPos); + Double_t glass = -1; + if (fDetectorID == 169) + glass = 1; + else if (fDetectorID == 170) + glass = 2; + else if (fDetectorID == 171) + glass = 3; + if (fDetectorID == 238) + glass = 4; + else if (fDetectorID == 239) + glass = 5; + else if (fDetectorID == 240) + glass = 6; + + Int_t Strip = -1; + Int_t str = -1; + Double_t X = -1; + Double_t Y = -1; + + if (Zmodule1 != 0) { + + Double_t Z = Zmodule1 - ZHit1; + X = XHit1 + (Z * (PxHit1 / TMath::Sqrt(PxHit1 * PxHit1 + PyHit1 * PyHit1 + PzHit1 * PzHit1))); + Y = YHit1 + (Z * (PyHit1 / TMath::Sqrt(PxHit1 * PxHit1 + PyHit1 * PyHit1 + PzHit1 * PzHit1))); + + Double_t count_strips = -1; + Int_t counter = 0; + + for (int i = 1; i <= 32; i++) { + + count_strips = Ymodule1 + i * (c0->det_yStripPos + 0.15); + counter++; + + if (Y >= (count_strips - 3.25) && Y < count_strips) { + + if (Y > count_strips - 0.075) + Strip = counter + 1; + else + Strip = counter; + + if (Y > count_strips - (3.25 / 2.0)) + str = 2; + else + str = 1; + + break; + } + } + } - //Second Layer of full Rpc detector covering 2.23 x 4.99 meters with 32 strips - c0->module[4][0] = 0; c0->module[4][1] = ((c0->ybox_fulldet/2.0) - ((c0->det_yGlassPos)) - ((c0->det_yGlassPos)/2.0) + c0->extra_y); c0->module[4][2] = (-(c0->zbox_fulldet/2.0) + c0->det_zAlPos + c0->det_dzAlPos*3.0 + c0->z_space_layers + (c0->det_zAlPos/2.0)); - c0->module[5][0] = 0; c0->module[5][1] = -((c0->ybox_fulldet/2.0) - ((c0->det_yGlassPos)) - ((c0->det_yGlassPos)/2.0) + c0->extra_y); c0->module[5][2] = (-(c0->zbox_fulldet/2.0) + c0->det_zAlPos + c0->det_dzAlPos*3.0 + c0->z_space_layers + (c0->det_zAlPos/2.0)); + if (Zmodule11 != 0) { - //Third Layer of full Rpc detector covering 2.23 x 4.99 meters with 64 strips - c0->module[6][0] = 0; c0->module[6][1] = ((c0->ybox_fulldet/2.0) - ((c0->det_yGlassPos)/2.0)); c0->module[6][2] = (-(c0->zbox_fulldet/2.0) + (c0->det_zAlPos*2.0) + c0->det_dzAlPos*5.0 + (c0->z_space_layers*2.0) + (c0->det_zAlPos/2.0)); - c0->module[7][0] = 0; c0->module[7][1] = 0; c0->module[7][2] = (-(c0->zbox_fulldet/2.0) + (c0->det_zAlPos*2.0) + c0->det_dzAlPos*5.0 + (c0->z_space_layers*3.0) + (c0->det_zAlPos/2.0)); - c0->module[8][0] = 0; c0->module[8][1] = -((c0->ybox_fulldet/2.0) - ((c0->det_yGlassPos)/2.0)); c0->module[8][2] = (-(c0->zbox_fulldet/2.0) + (c0->det_zAlPos*2.0) + c0->det_dzAlPos*5.0 + (c0->z_space_layers*2.0) + (c0->det_zAlPos/2.0)); + Double_t Z = Zmodule11 - ZHit1; + X = XHit1 + (Z * (PxHit1 / TMath::Sqrt(PxHit1 * PxHit1 + PyHit1 * PyHit1 + PzHit1 * PzHit1))); + Y = YHit1 + (Z * (PyHit1 / TMath::Sqrt(PxHit1 * PxHit1 + PyHit1 * PyHit1 + PzHit1 * PzHit1))); - //Fourth Layer of full Rpc detector covering 2.23 x 4.99 meters with 64 strips - c0->module[9][0] = 0; c0->module[9][1] = ((c0->ybox_fulldet/2.0) - ((c0->det_yGlassPos)) - ((c0->det_yGlassPos)/2.0) + c0->extra_y); c0->module[9][2] = (-(c0->zbox_fulldet/2.0) + (c0->det_zAlPos*3.0) + c0->det_dzAlPos*7.0 + (c0->z_space_layers*3.0) + (c0->det_zAlPos/2.0)); - c0->module[10][0] = 0; c0->module[10][1] = -((c0->ybox_fulldet/2.0) - ((c0->det_yGlassPos)) - ((c0->det_yGlassPos)/2.0) + c0->extra_y); c0->module[10][2] = (-(c0->zbox_fulldet/2.0) + (c0->det_zAlPos*3.0) + c0->det_dzAlPos*7.0 + (c0->z_space_layers*3.0) + (c0->det_zAlPos/2.0)); + Double_t count_strips = -1; + Int_t counter = 0; + for (int i = 1; i <= 64; i++) { - for(int i = 1; i<= 10; i++){ + count_strips = Xmodule11 + i * (c0->det_xStripPos64 + 0.15); + counter++; - if(XHit1 >= c0->module[i][0] - (c0->det_xGlassPos)/2.0 && XHit1 <= c0->module[i][0] + (c0->det_xGlassPos)/2.0 && YHit1 >= c0->module[i][1] - (c0->det_yGlassPos)/2.0 && YHit1 <= c0->module[i][1] + (c0->det_yGlassPos)/2.0 && ZHit1 >= c0->det_zPos + (c0->module[i][2] - (c0->det_zAlPos+2*c0->det_dzAlPos)/2.0) && ZHit1 <= c0->det_zPos + (c0->module[i][2] + (c0->det_zAlPos+2*c0->det_dzAlPos)/2.0)){ + if (X >= (count_strips - 3.45) && X < count_strips) { + if (X > count_strips - 0.075) + Strip = counter + 1; + else + Strip = counter; - if(fabs(c0->det_zPos + c0->module[i][2] - ZHit1) < dist1){ + if (X > count_strips - (3.45 / 2.0)) + str = 2; + else + str = 1; - if (flag0){ - RpcDetector = 1; - mod = i; - } - else{ - RpcDetector = 2; - mod = i+10; - } + break; + } + } + } - if(i < 6){ - Zmodule1 = c0->det_zPos + c0->module[i][2] + c0->det_zAlPos - c0->det_zStripPos; - Ymodule1 = c0->module[i][1] - (c0->det_yGlassPos + 2*c0->det_yGlassBorderPos)/2.0 + 1.5; - } - else{ - Zmodule11 = c0->det_zPos + c0->module[i][2] + c0->det_zAlPos - c0->det_zStripPos; - Xmodule11 = c0->module[i][0] - (c0->det_xGlassPos + 2*c0->det_xGlassBorderPos)/2.0 + 2.175; - } - dist1 = fabs(c0->det_zPos + c0->module[i][2] - ZHit1); - } + RpcModule = mod; + RpcGlass = glass; + RpcStrip = Strip; + Rpc_NeighbourStrip = str; + + if (Zmodule1 != 0) + hit_final = X; + if (Zmodule11 != 0) + hit_final = Y; + + TString path, path1; + + if (mod >= 6 && mod <= 10 || mod >= 16) { + path = "/cave_1/Upstream_Tagger_1/UpstreamTagger1_"; + path += mod; + path += "/glass_upstreamtagger_"; + path += fDetectorID; + Bool_t rc = nav->cd(path); + } else { + path1 = "/cave_1/Upstream_Tagger_1/UpstreamTagger_"; + path1 += mod; + path1 += "/glass_upstreamtagger_"; + path1 += fDetectorID; + Bool_t rc = nav->cd(path1); } - if(i == 10 && flag0){ - Double_t tmp = -c0->module[6][2]; - Double_t tmp1 = -c0->module[4][2]; - Double_t tmp2 = -c0->module[1][2]; - - c0->module[1][2] = -c0->module[9][2]; - c0->module[2][2] = -c0->module[9][2]; - c0->module[3][2] = -c0->module[9][2]; - c0->module[4][2] = tmp; - c0->module[5][2] = tmp; - - c0->module[6][2] = tmp1; - c0->module[7][2] = tmp1; - c0->module[8][2] = tmp1; - c0->module[9][2] = tmp2; - c0->module[10][2] = tmp2; - - i = 0; - flag0 = 0; - } - } - - Double_t glass = -1; - if(fDetectorID == 169) - glass = 1; - else if(fDetectorID == 170) - glass = 2; - else if(fDetectorID == 171) - glass = 3; - if(fDetectorID == 238) - glass = 4; - else if(fDetectorID == 239) - glass = 5; - else if(fDetectorID == 240) - glass = 6; - - Int_t Strip = -1; - Int_t str = -1; - Double_t X = -1; - Double_t Y = -1; - - if(Zmodule1 != 0){ - - Double_t Z = Zmodule1 - ZHit1; - X = XHit1 + (Z*(PxHit1/TMath::Sqrt(PxHit1*PxHit1 + PyHit1*PyHit1 + PzHit1*PzHit1))); - Y = YHit1 + (Z*(PyHit1/TMath::Sqrt(PxHit1*PxHit1 + PyHit1*PyHit1 + PzHit1*PzHit1))); - - Double_t count_strips = -1; - Int_t counter = 0; - - for(int i = 1; i <= 32; i++){ - - count_strips = Ymodule1 + i*(c0->det_yStripPos+0.15); - counter++; - - if(Y >= (count_strips - 3.25) && Y < count_strips){ - - if(Y > count_strips - 0.075) - Strip = counter + 1; - else - Strip = counter; - - if(Y > count_strips - (3.25/2.0)) - str = 2; - else - str = 1; - - break; - } - } - } - - if(Zmodule11 != 0){ - - Double_t Z = Zmodule11 - ZHit1; - X = XHit1 + (Z*(PxHit1/TMath::Sqrt(PxHit1*PxHit1 + PyHit1*PyHit1 + PzHit1*PzHit1))); - Y = YHit1 + (Z*(PyHit1/TMath::Sqrt(PxHit1*PxHit1 + PyHit1*PyHit1 + PzHit1*PzHit1))); - - Double_t count_strips = -1; - Int_t counter = 0; - - for(int i = 1; i <= 64; i++){ - - count_strips = Xmodule11 + i*(c0->det_xStripPos64+0.15); - counter++; - - if(X >= (count_strips - 3.45) && X < count_strips){ - - if(X > count_strips - 0.075) - Strip = counter + 1; - else - Strip = counter; - - if(X > count_strips - (3.45/2.0)) - str = 2; - else - str = 1; - - break; - } - } - } - - RpcModule = mod; - RpcGlass = glass; - RpcStrip = Strip; - Rpc_NeighbourStrip = str; - - if(Zmodule1 != 0) - hit_final = X; - if(Zmodule11 != 0) - hit_final = Y; - - TString path, path1; - - if(mod >=6 && mod <= 10 || mod >= 16){ - path = "/cave_1/Upstream_Tagger_1/UpstreamTagger1_";path+=mod;path+="/glass_upstreamtagger_";path+=fDetectorID; - Bool_t rc = nav->cd(path); - } - else{ - path1 = "/cave_1/Upstream_Tagger_1/UpstreamTagger_";path1+=mod;path1+="/glass_upstreamtagger_";path1+=fDetectorID; - Bool_t rc = nav->cd(path1); - } - - return nav->GetCurrentNode(); + + return nav->GetCurrentNode(); } // ----- Public method Print ----------------------- void UpstreamTaggerHit::Print() const { - cout << "-I- UpstreamTaggerHit: UpstreamTagger hit " << " in detector " << fDetectorID << endl; - cout << " TDC left " << t_1 << " ns TDC right " << t_2 << " ns" << endl; + cout << "-I- UpstreamTaggerHit: UpstreamTagger hit " << " in detector " << fDetectorID << endl; + cout << " TDC left " << t_1 << " ns TDC right " << t_2 << " ns" << endl; } - // ----------------------------------------------------- diff --git a/UpstreamTagger/UpstreamTaggerHit.h b/UpstreamTagger/UpstreamTaggerHit.h index d945ae8aa7..5396911c4a 100644 --- a/UpstreamTagger/UpstreamTaggerHit.h +++ b/UpstreamTagger/UpstreamTaggerHit.h @@ -2,17 +2,17 @@ #define UpstreamTaggerHIT_H 1 #include "FairVolume.h" #include "ShipHit.h" -#include "UpstreamTaggerPoint.h" -#include "UpstreamTagger.h" -#include "TObject.h" -#include "TGeoShape.h" #include "TGeoPhysicalNode.h" +#include "TGeoShape.h" +#include "TObject.h" +#include "UpstreamTagger.h" +#include "UpstreamTaggerPoint.h" - -class UpstreamTaggerHit : public ShipHit, UpstreamTagger +class UpstreamTaggerHit + : public ShipHit + , UpstreamTagger { public: - /** Default constructor **/ UpstreamTaggerHit(); @@ -27,49 +27,57 @@ class UpstreamTaggerHit : public ShipHit, UpstreamTagger Double_t GetZ(); TVector3 GetXYZ(); - - TGeoNode* GetNode(Double_t &hit_final, Int_t &mod); + TGeoNode* GetNode(Double_t& hit_final, Int_t& mod); std::vector GetTime(Double_t x); std::vector GetTime(); std::vector GetMeasurements(); /** Modifier **/ - void SetTDC(Float_t val1, Float_t val2){t_1=val1;t_2=val2;} - void SetPoint(Double_t p1, Double_t p2, Double_t p3){point_final[0]=p1;point_final[1]=p2;point_final[2]=p3;} + void SetTDC(Float_t val1, Float_t val2) + { + t_1 = val1; + t_2 = val2; + } + void SetPoint(Double_t p1, Double_t p2, Double_t p3) + { + point_final[0] = p1; + point_final[1] = p2; + point_final[2] = p3; + } /** Output to screen **/ virtual void Print() const; void Dist(Float_t x, Float_t& lpos, Float_t& lneg); - void setInvalid() {flag = false;} - void setIsValid() {flag = true;} - Int_t GetModule() const {return RpcModule;} - Int_t GetGlass() const {return RpcGlass;} - Int_t GetStrip() const {return RpcStrip;} - Int_t GetNeighbour() const {return Rpc_NeighbourStrip;} - Int_t GetRpcDetector() const {return RpcDetector;} + void setInvalid() { flag = false; } + void setIsValid() { flag = true; } + Int_t GetModule() const { return RpcModule; } + Int_t GetGlass() const { return RpcGlass; } + Int_t GetStrip() const { return RpcStrip; } + Int_t GetNeighbour() const { return Rpc_NeighbourStrip; } + Int_t GetRpcDetector() const { return RpcDetector; } + + // Rpc time is invalid if isValid returns False + bool isValid() const { return flag; } - //Rpc time is invalid if isValid returns False - bool isValid() const {return flag;} private: UpstreamTaggerHit(const UpstreamTaggerHit& point); UpstreamTaggerHit operator=(const UpstreamTaggerHit& point); - Double_t v_drift = 17.7;// cm/ns - Double_t T_resol = 0.283; // Rpc time resolution in ns + Double_t v_drift = 17.7; // cm/ns + Double_t T_resol = 0.283; // Rpc time resolution in ns UpstreamTagger* c0; Double_t point_final[3]; - const Double_t * mom[3]; - - Float_t flag; ///< flag - Float_t t_1,t_2; ///< TDC on both sides - Int_t RpcModule; //Rpc module - Int_t RpcGlass; //Rpc glass - Int_t RpcStrip; //Rpc Strip - Int_t RpcDetector; //Rpc detector 1 or 2 - Int_t Rpc_NeighbourStrip; //Neighbour strip likely to be activated - Double_t det_zdet1; //! z-position of veto station + const Double_t* mom[3]; - ClassDef(UpstreamTaggerHit,1); + Float_t flag; ///< flag + Float_t t_1, t_2; ///< TDC on both sides + Int_t RpcModule; // Rpc module + Int_t RpcGlass; // Rpc glass + Int_t RpcStrip; // Rpc Strip + Int_t RpcDetector; // Rpc detector 1 or 2 + Int_t Rpc_NeighbourStrip; // Neighbour strip likely to be activated + Double_t det_zdet1; //! z-position of veto station + ClassDef(UpstreamTaggerHit, 1); }; #endif diff --git a/UpstreamTagger/UpstreamTaggerPoint.cxx b/UpstreamTagger/UpstreamTaggerPoint.cxx index 480c8d69c4..24b68723c3 100644 --- a/UpstreamTagger/UpstreamTaggerPoint.cxx +++ b/UpstreamTagger/UpstreamTaggerPoint.cxx @@ -4,38 +4,41 @@ using std::cout; using std::endl; - // ----- Default constructor ------------------------------------------- UpstreamTaggerPoint::UpstreamTaggerPoint() - : FairMCPoint() -{ -} + : FairMCPoint() +{} // ------------------------------------------------------------------------- // ----- Standard constructor ------------------------------------------ -UpstreamTaggerPoint::UpstreamTaggerPoint(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t tof, Double_t length, - Double_t eLoss, Int_t pdgcode,TVector3 Lpos, TVector3 Lmom) - : FairMCPoint(trackID, detID, pos, mom, tof, length, eLoss), fPdgCode(pdgcode),fLpos(Lpos),fLmom(Lmom) -{ -} +UpstreamTaggerPoint::UpstreamTaggerPoint(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t tof, + Double_t length, + Double_t eLoss, + Int_t pdgcode, + TVector3 Lpos, + TVector3 Lmom) + : FairMCPoint(trackID, detID, pos, mom, tof, length, eLoss) + , fPdgCode(pdgcode) + , fLpos(Lpos) + , fLmom(Lmom) +{} // ------------------------------------------------------------------------- // ----- Destructor ---------------------------------------------------- -UpstreamTaggerPoint::~UpstreamTaggerPoint() { } +UpstreamTaggerPoint::~UpstreamTaggerPoint() {} // ------------------------------------------------------------------------- // ----- Public method Print ------------------------------------------- void UpstreamTaggerPoint::Print() const { - cout << "-I- TimeRpcPoint: veto point for track " << fTrackID - << " in detector " << fDetectorID << endl; - cout << " Position (" << fX << ", " << fY << ", " << fZ - << ") cm" << endl; - cout << " Momentum (" << fPx << ", " << fPy << ", " << fPz - << ") GeV" << endl; - cout << " Time " << fTime << " ns, Length " << fLength - << " cm, Energy loss " << fELoss*1.0e06 << " keV" << endl; + cout << "-I- TimeRpcPoint: veto point for track " << fTrackID << " in detector " << fDetectorID << endl; + cout << " Position (" << fX << ", " << fY << ", " << fZ << ") cm" << endl; + cout << " Momentum (" << fPx << ", " << fPy << ", " << fPz << ") GeV" << endl; + cout << " Time " << fTime << " ns, Length " << fLength << " cm, Energy loss " << fELoss * 1.0e06 << " keV" + << endl; } // ------------------------------------------------------------------------- diff --git a/UpstreamTagger/UpstreamTaggerPoint.h b/UpstreamTagger/UpstreamTaggerPoint.h index b2627ddf61..5313e21819 100644 --- a/UpstreamTagger/UpstreamTaggerPoint.h +++ b/UpstreamTagger/UpstreamTaggerPoint.h @@ -1,23 +1,19 @@ #ifndef UPSTREAMTAGGERPOINT_H #define UPSTREAMTAGGERPOINT_H 1 - #include "FairMCPoint.h" -#include "UpstreamTaggerHit.h" -#include "UpstreamTagger.h" #include "TObject.h" #include "TVector3.h" - +#include "UpstreamTagger.h" +#include "UpstreamTaggerHit.h" class UpstreamTaggerPoint : public FairMCPoint { public: - /** Default constructor **/ UpstreamTaggerPoint(); - /** Constructor with arguments *@param trackID Index of MCTrack *@param detID Detector ID @@ -26,28 +22,35 @@ class UpstreamTaggerPoint : public FairMCPoint *@param tof Time since event start [ns] *@param length Track length since creation [cm] *@param eLoss Energy deposit [GeV] - **/ - UpstreamTaggerPoint(Int_t trackID, Int_t detID, TVector3 pos, TVector3 mom, - Double_t tof, Double_t length, Double_t eLoss, Int_t pdgCode, TVector3 Lpos, TVector3 Lmom); + **/ + UpstreamTaggerPoint(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t tof, + Double_t length, + Double_t eLoss, + Int_t pdgCode, + TVector3 Lpos, + TVector3 Lmom); /** Destructor **/ virtual ~UpstreamTaggerPoint(); /** Output to screen **/ virtual void Print() const; - Int_t PdgCode() const {return fPdgCode;} - TVector3 LastPoint() const {return fLpos;} - TVector3 LastMom() const {return fLmom;} + Int_t PdgCode() const { return fPdgCode; } + TVector3 LastPoint() const { return fLpos; } + TVector3 LastMom() const { return fLmom; } private: /** Copy constructor **/ Int_t fPdgCode; - TVector3 fLpos,fLmom; + TVector3 fLpos, fLmom; UpstreamTaggerPoint(const UpstreamTaggerPoint& point); UpstreamTaggerPoint operator=(const UpstreamTaggerPoint& point); - ClassDef(UpstreamTaggerPoint,1) - + ClassDef(UpstreamTaggerPoint, 1) }; #endif diff --git a/cmake/modules/CppStyleGuideChecks.cmake b/cmake/modules/CppStyleGuideChecks.cmake index c32602930e..c84d77229a 100644 --- a/cmake/modules/CppStyleGuideChecks.cmake +++ b/cmake/modules/CppStyleGuideChecks.cmake @@ -3,87 +3,124 @@ set(BUILD_SUPPORT_DIR "${CMAKE_SOURCE_DIR}/housekeeping") # define commands to obtain source file lists set(ALL_SRC_FILES "${BUILD_SUPPORT_DIR}/get-all-src-files.sh") set(STAGED_SRC_FILES "${BUILD_SUPPORT_DIR}/get-staged-src-files.sh") -set(CHANGED_SRC_FILES_ORIGIN_MASTER "${BUILD_SUPPORT_DIR}/get-changed-src-files-origin-master.sh") +set(CHANGED_SRC_FILES_ORIGIN_MASTER + "${BUILD_SUPPORT_DIR}/get-changed-src-files-origin-master.sh") # create helper target to check header files with clang-tidy set(clang_tidy_header_helper ${CMAKE_BINARY_DIR}/clang_tidy_header_helper.cc) -file(WRITE ${clang_tidy_header_helper} "" ) # creates file -add_executable(clang-tidy-header-helper EXCLUDE_FROM_ALL ${clang_tidy_header_helper}) +file(WRITE ${clang_tidy_header_helper} "") # creates file +add_executable(clang-tidy-header-helper EXCLUDE_FROM_ALL + ${clang_tidy_header_helper}) -# -------------------- "make format*", "make show-format*" and "make check-format*" targets ------------ +# -------------------- "make format*", "make show-format*" and "make +# check-format*" targets ------------ function(add_clang_format_target make_target_id get_files_cmd) - if (${CLANG_FORMAT_FOUND}) - add_custom_target(${make_target_id} - COMMAND ${BUILD_SUPPORT_DIR}/run-clang-format.sh ${CMAKE_CURRENT_SOURCE_DIR} ${CLANG_FORMAT_BIN} 1 `${get_files_cmd} ${PROJECT_SOURCE_DIR}` + if(${CLANG_FORMAT_FOUND}) + add_custom_target( + ${make_target_id} + COMMAND + ${BUILD_SUPPORT_DIR}/run-clang-format.sh ${CMAKE_CURRENT_SOURCE_DIR} + ${CLANG_FORMAT_BIN} 1 `${get_files_cmd} ${PROJECT_SOURCE_DIR}` WORKING_DIRECTORY ${PROJECT_SOURCE_DIR} COMMENT "Run clang-format on selected files and update them in-place") - add_custom_target(show-${make_target_id} - COMMAND ${BUILD_SUPPORT_DIR}/run-clang-format.sh ${CMAKE_CURRENT_SOURCE_DIR} ${CLANG_FORMAT_BIN} 2 `${get_files_cmd} ${PROJECT_SOURCE_DIR}` + add_custom_target( + show-${make_target_id} + COMMAND + ${BUILD_SUPPORT_DIR}/run-clang-format.sh ${CMAKE_CURRENT_SOURCE_DIR} + ${CLANG_FORMAT_BIN} 2 `${get_files_cmd} ${PROJECT_SOURCE_DIR}` WORKING_DIRECTORY ${PROJECT_SOURCE_DIR} COMMENT "Run clang-format on selected files and display differences") - add_custom_target(check-${make_target_id} - COMMAND ${BUILD_SUPPORT_DIR}/run-clang-format.sh ${CMAKE_CURRENT_SOURCE_DIR} ${CLANG_FORMAT_BIN} 0 `${get_files_cmd} ${PROJECT_SOURCE_DIR}` + add_custom_target( + check-${make_target_id} + COMMAND + ${BUILD_SUPPORT_DIR}/run-clang-format.sh ${CMAKE_CURRENT_SOURCE_DIR} + ${CLANG_FORMAT_BIN} 0 `${get_files_cmd} ${PROJECT_SOURCE_DIR}` WORKING_DIRECTORY ${PROJECT_SOURCE_DIR} - COMMENT "Run clang-format on selected files. Fails if any file needs to be reformatted") + COMMENT + "Run clang-format on selected files. Fails if any file needs to be reformatted" + ) endif() endfunction(add_clang_format_target) -# -------------------- "make tidy*", "make show-tidy*" and "make check-tidy*" targets ------------ +# -------------------- "make tidy*", "make show-tidy*" and "make check-tidy*" +# targets ------------ function(add_clang_tidy_target make_target_id get_files_cmd) - if (${CLANG_TIDY_FOUND}) - add_custom_target(${make_target_id} - COMMAND ${BUILD_SUPPORT_DIR}/run-clang-tidy.sh ${CLANG_TIDY_BIN} ${clang_tidy_header_helper} ${CMAKE_BINARY_DIR}/compile_commands.json 1 - `${get_files_cmd} ${PROJECT_SOURCE_DIR} | grep -v -F -f ${PROJECT_SOURCE_DIR}/.clang-tidy-ignore` + if(${CLANG_TIDY_FOUND}) + add_custom_target( + ${make_target_id} + COMMAND + ${BUILD_SUPPORT_DIR}/run-clang-tidy.sh ${CLANG_TIDY_BIN} + ${clang_tidy_header_helper} ${CMAKE_BINARY_DIR}/compile_commands.json 1 + `${get_files_cmd} ${PROJECT_SOURCE_DIR} | grep -v -F -f + ${PROJECT_SOURCE_DIR}/.clang-tidy-ignore` WORKING_DIRECTORY ${PROJECT_SOURCE_DIR} - COMMENT "Run clang-tidy on selected files and attempt to fix any warning automatically") + COMMENT + "Run clang-tidy on selected files and attempt to fix any warning automatically" + ) - add_custom_target(show-${make_target_id} - COMMAND ${BUILD_SUPPORT_DIR}/run-clang-tidy.sh ${CLANG_TIDY_BIN} ${clang_tidy_header_helper} ${CMAKE_BINARY_DIR}/compile_commands.json 2 - `${get_files_cmd} ${PROJECT_SOURCE_DIR} | grep -v -F -f ${PROJECT_SOURCE_DIR}/.clang-tidy-ignore` + add_custom_target( + show-${make_target_id} + COMMAND + ${BUILD_SUPPORT_DIR}/run-clang-tidy.sh ${CLANG_TIDY_BIN} + ${clang_tidy_header_helper} ${CMAKE_BINARY_DIR}/compile_commands.json 2 + `${get_files_cmd} ${PROJECT_SOURCE_DIR} | grep -v -F -f + ${PROJECT_SOURCE_DIR}/.clang-tidy-ignore` WORKING_DIRECTORY ${PROJECT_SOURCE_DIR} COMMENT "Run clang-tidy on selected files and display errors.") - add_custom_target(check-${make_target_id} - COMMAND ${BUILD_SUPPORT_DIR}/run-clang-tidy.sh ${CLANG_TIDY_BIN} ${clang_tidy_header_helper} ${CMAKE_BINARY_DIR}/compile_commands.json 0 - `${get_files_cmd} ${PROJECT_SOURCE_DIR} | grep -v -F -f ${PROJECT_SOURCE_DIR}/.clang-tidy-ignore` + add_custom_target( + check-${make_target_id} + COMMAND + ${BUILD_SUPPORT_DIR}/run-clang-tidy.sh ${CLANG_TIDY_BIN} + ${clang_tidy_header_helper} ${CMAKE_BINARY_DIR}/compile_commands.json 0 + `${get_files_cmd} ${PROJECT_SOURCE_DIR} | grep -v -F -f + ${PROJECT_SOURCE_DIR}/.clang-tidy-ignore` WORKING_DIRECTORY ${PROJECT_SOURCE_DIR} COMMENT "Run clang-tidy on selected files. Fails if errors are found.") endif() endfunction(add_clang_tidy_target) function(add_cpplint_target make_target_id get_files_cmd) - add_custom_target(${make_target_id} - COMMAND ${BUILD_SUPPORT_DIR}/cpplint/runCppLint.sh `${get_files_cmd} ${PROJECT_SOURCE_DIR}` + add_custom_target( + ${make_target_id} + COMMAND ${BUILD_SUPPORT_DIR}/cpplint/runCppLint.sh `${get_files_cmd} + ${PROJECT_SOURCE_DIR}` WORKING_DIRECTORY ${PROJECT_SOURCE_DIR} COMMENT "Run cpplint on selected files. Fails if errors are found.") endfunction(add_cpplint_target) -if (GIT_FOUND) - add_custom_target(fetch-master +if(GIT_FOUND) + add_custom_target( + fetch-master COMMAND git fetch origin master WORKING_DIRECTORY ${PROJECT_SOURCE_DIR} COMMENT "Fetch latest changes from origin master. If you forked the project, make sure that it is synchronized with the FairShip repository!") - add_clang_format_target(format "${CHANGED_SRC_FILES_ORIGIN_MASTER}" ) - add_clang_tidy_target(tidy "${CHANGED_SRC_FILES_ORIGIN_MASTER}" ) - add_cpplint_target(check-cpplint "${CHANGED_SRC_FILES_ORIGIN_MASTER}" ) + add_clang_format_target(format "${CHANGED_SRC_FILES_ORIGIN_MASTER}") + add_clang_tidy_target(tidy "${CHANGED_SRC_FILES_ORIGIN_MASTER}") + add_cpplint_target(check-cpplint "${CHANGED_SRC_FILES_ORIGIN_MASTER}") - add_clang_format_target(format-staged "${STAGED_SRC_FILES}" ) - add_clang_tidy_target(tidy-staged "${STAGED_SRC_FILES}" ) - add_cpplint_target(check-cpplint-staged "${STAGED_SRC_FILES}" ) + add_clang_format_target(format-staged "${STAGED_SRC_FILES}") + add_clang_tidy_target(tidy-staged "${STAGED_SRC_FILES}") + add_cpplint_target(check-cpplint-staged "${STAGED_SRC_FILES}") # check submission - add_custom_target(check-submission + add_custom_target( + check-submission COMMAND "${BUILD_SUPPORT_DIR}/check-submission.sh" "${CMAKE_BINARY_DIR}" - COMMENT "check-submission will build, run all tests, check formatting, code style, and generate documentation and coverage report") + COMMENT + "check-submission will build, run all tests, check formatting, code style, and generate documentation and coverage report" + ) # fix submission - add_custom_target(fix-submission + add_custom_target( + fix-submission COMMAND "${BUILD_SUPPORT_DIR}/fix-submission.sh" "${CMAKE_BINARY_DIR}" - COMMENT "fix-submission will attempt to fix the reported issues using clang-format and clang-tidy. + COMMENT + "fix-submission will attempt to fix the reported issues using clang-format and clang-tidy. Failing tests and issues from cpplint must be fixed manually.") endif() diff --git a/cmake/modules/FindClangTools.cmake b/cmake/modules/FindClangTools.cmake index 25be823024..eb53d527b3 100644 --- a/cmake/modules/FindClangTools.cmake +++ b/cmake/modules/FindClangTools.cmake @@ -1,42 +1,39 @@ # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at +# Licensed under the Apache License, Version 2.0 (the "License"); you may not +# use this file except in compliance with the License. You may obtain a copy of +# the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations under +# the License. # # Tries to find the clang-tidy and clang-format modules # # Usage of this module as follows: # -# find_package(ClangTools) +# find_package(ClangTools) # # Variables used by this module, they can change the default behaviour and need # to be set before calling find_package: # -# ClangToolsBin_HOME - -# When set, this path is inspected instead of standard library binary locations -# to find clang-tidy and clang-format +# ClangToolsBin_HOME - When set, this path is inspected instead of standard +# library binary locations to find clang-tidy and clang-format # -# This module defines -# CLANG_TIDY_BIN, The path to the clang tidy binary -# CLANG_TIDY_FOUND, Whether clang tidy was found -# CLANG_FORMAT_BIN, The path to the clang format binary -# CLANG_TIDY_FOUND, Whether clang format was found +# This module defines CLANG_TIDY_BIN, The path to the clang tidy binary +# CLANG_TIDY_FOUND, Whether clang tidy was found CLANG_FORMAT_BIN, The path to +# the clang format binary CLANG_TIDY_FOUND, Whether clang format was found -find_program(CLANG_TIDY_BIN +find_program( + CLANG_TIDY_BIN NAMES clang-tidy-4.0 clang-tidy-3.9 clang-tidy-3.8 clang-tidy PATHS ${ClangTools_PATH} $ENV{CLANG_TOOLS_PATH} /usr/local/bin /usr/bin - NO_CMAKE_PATH NO_CMAKE_ENVIRONMENT_PATH NO_CMAKE_SYSTEM_PATH -) + NO_CMAKE_PATH NO_CMAKE_ENVIRONMENT_PATH NO_CMAKE_SYSTEM_PATH) -if ( "${CLANG_TIDY_BIN}" STREQUAL "CLANG_TIDY_BIN-NOTFOUND" ) +if("${CLANG_TIDY_BIN}" STREQUAL "CLANG_TIDY_BIN-NOTFOUND") set(CLANG_TIDY_FOUND 0) message(STATUS "clang-tidy not found") else() @@ -44,13 +41,13 @@ else() message(STATUS "clang-tidy found at ${CLANG_TIDY_BIN}") endif() -find_program(CLANG_FORMAT_BIN +find_program( + CLANG_FORMAT_BIN NAMES clang-format-4.0 clang-format-3.9 clang-format-3.8 clang-format PATHS ${ClangTools_PATH} $ENV{CLANG_TOOLS_PATH} /usr/local/bin /usr/bin - NO_CMAKE_PATH NO_CMAKE_ENVIRONMENT_PATH NO_CMAKE_SYSTEM_PATH -) + NO_CMAKE_PATH NO_CMAKE_ENVIRONMENT_PATH NO_CMAKE_SYSTEM_PATH) -if ( "${CLANG_FORMAT_BIN}" STREQUAL "CLANG_FORMAT_BIN-NOTFOUND" ) +if("${CLANG_FORMAT_BIN}" STREQUAL "CLANG_FORMAT_BIN-NOTFOUND") set(CLANG_FORMAT_FOUND 0) message(STATUS "clang-format not found") else() diff --git a/cmake/modules/FindEvtGen.cmake b/cmake/modules/FindEvtGen.cmake index 5d598ed0a8..3529137439 100644 --- a/cmake/modules/FindEvtGen.cmake +++ b/cmake/modules/FindEvtGen.cmake @@ -1,45 +1,46 @@ - ################################################################################ - # Copyright (C) 2014 GSI Helmholtzzentrum fuer Schwerionenforschung GmbH # - # # - # This software is distributed under the terms of the # - # GNU Lesser General Public Licence version 3 (LGPL) version 3, # - # copied verbatim in the file "LICENSE" # - ################################################################################ -# - Try to find EvtGen instalation -# Once done this will define +# ############################################################################## +# Copyright (C) 2014 GSI Helmholtzzentrum fuer Schwerionenforschung GmbH # # +# This software is distributed under the terms of the # GNU Lesser +# General Public Licence version 3 (LGPL) version 3, # copied verbatim in +# the file "LICENSE" # +# ############################################################################## +# * Try to find EvtGen instalation Once done this will define # -MESSAGE(STATUS "Looking for EvtGen ...") +message(STATUS "Looking for EvtGen ...") -FIND_PATH(EVTGEN_INCLUDE_DIR NAMES EvtGen/EvtGen.hh PATHS - ${SIMPATH}/include/EvtGen - NO_DEFAULT_PATH -) +find_path( + EVTGEN_INCLUDE_DIR + NAMES EvtGen/EvtGen.hh + PATHS ${SIMPATH}/include/EvtGen + NO_DEFAULT_PATH) -FIND_PATH(EVTGEN_LIBRARY_DIR NAMES libEvtGen.so PATHS - ${SIMPATH}/lib - NO_DEFAULT_PATH -) +find_path( + EVTGEN_LIBRARY_DIR + NAMES libEvtGen.so + PATHS ${SIMPATH}/lib + NO_DEFAULT_PATH) -Find_Path(EVTGENDATA NAMES evt.pdl PATHS - ${SIMPATH}/share/EvtGen/ -) +find_path( + EVTGENDATA + NAMES evt.pdl + PATHS ${SIMPATH}/share/EvtGen/) -If (NOT EVTGENDATA) - Message(STATUS "Could not find EvtGen data files") -EndIf() +if(NOT EVTGENDATA) + message(STATUS "Could not find EvtGen data files") +endif() -if (EVTGEN_INCLUDE_DIR AND EVTGEN_LIBRARY_DIR) - set(EVTGEN_FOUND TRUE) -endif (EVTGEN_INCLUDE_DIR AND EVTGEN_LIBRARY_DIR) +if(EVTGEN_INCLUDE_DIR AND EVTGEN_LIBRARY_DIR) + set(EVTGEN_FOUND TRUE) +endif(EVTGEN_INCLUDE_DIR AND EVTGEN_LIBRARY_DIR) -if (EVTGEN_FOUND) - if (NOT EVTGEN_FOUND_QUIETLY) - MESSAGE(STATUS "Looking for EVTGEN... - found ${EVTGEN_LIBRARY_DIR}") - SET(LD_LIBRARY_PATH ${LD_LIBRARY_PATH} ${EVTGEN_LIBRARY_DIR}) - endif (NOT EVTGEN_FOUND_QUIETLY) -else (EVTGEN_FOUND) - if (EVTGEN_FOUND_REQUIRED) +if(EVTGEN_FOUND) + if(NOT EVTGEN_FOUND_QUIETLY) + message(STATUS "Looking for EVTGEN... - found ${EVTGEN_LIBRARY_DIR}") + set(LD_LIBRARY_PATH ${LD_LIBRARY_PATH} ${EVTGEN_LIBRARY_DIR}) + endif(NOT EVTGEN_FOUND_QUIETLY) +else(EVTGEN_FOUND) + if(EVTGEN_FOUND_REQUIRED) message(FATAL_ERROR "Looking for EVTGEN... - Not found") - endif (EVTGEN_FOUND_REQUIRED) -endif (EVTGEN_FOUND) + endif(EVTGEN_FOUND_REQUIRED) +endif(EVTGEN_FOUND) diff --git a/cmake/modules/GenerateVersionInfo.cmake b/cmake/modules/GenerateVersionInfo.cmake index e566281964..a95289d8b1 100644 --- a/cmake/modules/GenerateVersionInfo.cmake +++ b/cmake/modules/GenerateVersionInfo.cmake @@ -1,25 +1,26 @@ - ################################################################################ - # Copyright (C) 2014 GSI Helmholtzzentrum fuer Schwerionenforschung GmbH # - # # - # This software is distributed under the terms of the # - # GNU Lesser General Public Licence (LGPL) version 3, # - # copied verbatim in the file "LICENSE" # - ################################################################################ - # Configure FairVersion.h - # ------------------------------ +# ############################################################################## +# Copyright (C) 2014 GSI Helmholtzzentrum fuer Schwerionenforschung GmbH # # +# This software is distributed under the terms of the # GNU Lesser +# General Public Licence (LGPL) version 3, # copied verbatim in the +# file "LICENSE" # +# ############################################################################## +# Configure FairVersion.h +# ------------------------------ - Find_Package(Git) +find_package(Git) - If(GIT_FOUND AND EXISTS "${SOURCE_DIR}/.git") - Execute_Process(COMMAND ${GIT_EXECUTABLE} describe --tags - OUTPUT_VARIABLE FAIRROOT_GIT_VERSION - OUTPUT_STRIP_TRAILING_WHITESPACE - WORKING_DIRECTORY ${SOURCE_DIR} - ) - Execute_Process(COMMAND ${GIT_EXECUTABLE} log -1 --format=%cd - OUTPUT_VARIABLE FAIRROOT_GIT_DATE - OUTPUT_STRIP_TRAILING_WHITESPACE - WORKING_DIRECTORY ${SOURCE_DIR} - ) - Message(STATUS "FairShip Version - ${FAIRSHIP_GIT_VERSION} from - ${FAIRSHIP_GIT_DATE}") - EndIf() +if(GIT_FOUND AND EXISTS "${SOURCE_DIR}/.git") + execute_process( + COMMAND ${GIT_EXECUTABLE} describe --tags + OUTPUT_VARIABLE FAIRROOT_GIT_VERSION + OUTPUT_STRIP_TRAILING_WHITESPACE + WORKING_DIRECTORY ${SOURCE_DIR}) + execute_process( + COMMAND ${GIT_EXECUTABLE} log -1 --format=%cd + OUTPUT_VARIABLE FAIRROOT_GIT_DATE + OUTPUT_STRIP_TRAILING_WHITESPACE + WORKING_DIRECTORY ${SOURCE_DIR}) + message( + STATUS + "FairShip Version - ${FAIRSHIP_GIT_VERSION} from - ${FAIRSHIP_GIT_DATE}") +endif() diff --git a/ecal/CMakeLists.txt b/ecal/CMakeLists.txt index f024f3f322..afd3594dcb 100644 --- a/ecal/CMakeLists.txt +++ b/ecal/CMakeLists.txt @@ -1,56 +1,48 @@ -# Create a library called "libecal" which includes the source files given in -# the array . -# The extension is already found. Any number of sources could be listed here. +# Create a library called "libecal" which includes the source files given in the +# array . The extension is already found. Any number of sources could be listed +# here. -set(INCLUDE_DIRECTORIES -#put here all directories where header files are located -${CMAKE_SOURCE_DIR}/shipdata -${CMAKE_SOURCE_DIR}/ecal -${genfit2_INCDIR} -) +set(INCLUDE_DIRECTORIES # put here all directories where header files are + # located + ${CMAKE_SOURCE_DIR}/shipdata ${CMAKE_SOURCE_DIR}/ecal ${genfit2_INCDIR}) -include_directories(${INCLUDE_DIRECTORIES} ${VMC_INCLUDE_DIRS} ${FAIRROOT_INCLUDE_DIR}) +include_directories(${INCLUDE_DIRECTORIES} ${VMC_INCLUDE_DIRS} + ${FAIRROOT_INCLUDE_DIR}) include_directories(SYSTEM ${SYSTEM_INCLUDE_DIRECTORIES}) -set(LINK_DIRECTORIES -${ROOT_LIBRARY_DIR} -${FAIRROOT_LIBRARY_DIR} -${genfit2_LIBDIR} -) +set(LINK_DIRECTORIES ${ROOT_LIBRARY_DIR} ${FAIRROOT_LIBRARY_DIR} + ${genfit2_LIBDIR}) -link_directories( ${LINK_DIRECTORIES}) +link_directories(${LINK_DIRECTORIES}) set(SRCS -#Put here your sourcefiles -ecal.cxx -ecalContFact.cxx -ecalPoint.cxx -ecalLightMap.cxx -ecalCell.cxx -ecalCellMC.cxx -ecalModule.cxx -ecalInf.cxx -ecalStructure.cxx -ecalStructureFiller.cxx -ecalDigi.cxx -ecalPrepare.cxx -ecalAnalysisSimple.cxx -ecalAnalysisMaterial.cxx -ecalMaximum.cxx -ecalMaximumLocator.cxx -ecalCluster.cxx -ecalClusterFinder.cxx -ecalClusterCalibration.cxx -ecalDrawer.cxx -ecalReconstructed.cxx -ecalReco.cxx -ecalMatch.cxx -) + # Put here your sourcefiles + ecal.cxx + ecalContFact.cxx + ecalPoint.cxx + ecalLightMap.cxx + ecalCell.cxx + ecalCellMC.cxx + ecalModule.cxx + ecalInf.cxx + ecalStructure.cxx + ecalStructureFiller.cxx + ecalDigi.cxx + ecalPrepare.cxx + ecalAnalysisSimple.cxx + ecalAnalysisMaterial.cxx + ecalMaximum.cxx + ecalMaximumLocator.cxx + ecalCluster.cxx + ecalClusterFinder.cxx + ecalClusterCalibration.cxx + ecalDrawer.cxx + ecalReconstructed.cxx + ecalReco.cxx + ecalMatch.cxx) -Set(LINKDEF ecalLinkDef.h) -Set(LIBRARY_NAME ecal) -Set(DEPENDENCIES - Base ShipData FairLogger::FairLogger -) +set(LINKDEF ecalLinkDef.h) +set(LIBRARY_NAME ecal) +set(DEPENDENCIES Base ShipData FairLogger::FairLogger) -GENERATE_LIBRARY() +generate_library() diff --git a/ecal/ecal.cxx b/ecal/ecal.cxx index aff2dae02a..040a5e155b 100644 --- a/ecal/ecal.cxx +++ b/ecal/ecal.cxx @@ -7,33 +7,31 @@ #include "ecal.h" -#include "ecalPoint.h" -#include "ecalLightMap.h" - #include "FairGeoInterface.h" #include "FairGeoLoader.h" +#include "FairGeoMedia.h" +#include "FairGeoMedium.h" #include "FairGeoNode.h" #include "FairGeoRootBuilder.h" -#include "FairRuntimeDb.h" #include "FairRootManager.h" #include "FairRun.h" #include "FairRunAna.h" -#include "ShipStack.h" +#include "FairRuntimeDb.h" #include "FairVolume.h" -#include "FairGeoMedium.h" -#include "FairGeoMedia.h" - +#include "ShipStack.h" #include "TClonesArray.h" +#include "TGeoBBox.h" +#include "TGeoEltu.h" #include "TGeoMCGeometry.h" #include "TGeoManager.h" -#include "TParticle.h" -#include "TVirtualMC.h" -#include "TGeoBBox.h" +#include "TGeoMatrix.h" #include "TGeoPgon.h" #include "TGeoTube.h" -#include "TGeoEltu.h" -#include "TGeoMatrix.h" #include "TList.h" +#include "TParticle.h" +#include "TVirtualMC.h" +#include "ecalLightMap.h" +#include "ecalPoint.h" #include #include @@ -44,1278 +42,1416 @@ using namespace std; // ----- Default constructor ------------------------------------------- ecal::ecal() - : FairDetector("ECAL", kTRUE, kecal), - fInf(NULL), - fDebug(NULL), - fTrackID(-1), - fVolumeID(-1), - fPos(), - fMom(), - fTime(-1.), - fLength(-1.), - fELoss(-1.), - fPosIndex(0), - fEcalCollection(new TClonesArray("ecalPoint")), - fLiteCollection(new TClonesArray("ecalPoint")), - fEcalSize(), - fSimpleGeo(0), - fXSize(0), - fYSize(0), - fDX(0.), - fDY(0.), - fModuleSize(0.), - fZEcal(0.), - fSemiX(0.), - fSemiY(0.), - fThicknessLead(0.), - fThicknessScin(0.), - fThicknessTyvk(0.), - fThicknessLayer(0.), - fThicknessSteel(0.), - fEdging(0.), - fHoleRad(0.), - fFiberRad(0.), - fXCell(), - fYCell(), - fNH(), - fCF(), - fLightMapNames(), - fLightMaps(), - fNLayers(0), - fModuleLenght(0.), - fGeoScale(0.), - fNColumns1(0), - fNRows1(0), - fNColumns2(0), - fNRows2(0), - fNColumns(0), - fNRows(0), - fVolIdMax(0), - fFirstNumber(0), - fVolArr(), - fModules(), - fCells(), - fScTiles(), - fTileEdging(), - fPbTiles(), - fTvTiles(), - fHoleVol(), - fFiberVol(), - fSteelTapes(), - fHolePos(), - fModulesWithType(), - fRawNumber(), - fStructureId() + : FairDetector("ECAL", kTRUE, kecal) + , fInf(NULL) + , fDebug(NULL) + , fTrackID(-1) + , fVolumeID(-1) + , fPos() + , fMom() + , fTime(-1.) + , fLength(-1.) + , fELoss(-1.) + , fPosIndex(0) + , fEcalCollection(new TClonesArray("ecalPoint")) + , fLiteCollection(new TClonesArray("ecalPoint")) + , fEcalSize() + , fSimpleGeo(0) + , fXSize(0) + , fYSize(0) + , fDX(0.) + , fDY(0.) + , fModuleSize(0.) + , fZEcal(0.) + , fSemiX(0.) + , fSemiY(0.) + , fThicknessLead(0.) + , fThicknessScin(0.) + , fThicknessTyvk(0.) + , fThicknessLayer(0.) + , fThicknessSteel(0.) + , fEdging(0.) + , fHoleRad(0.) + , fFiberRad(0.) + , fXCell() + , fYCell() + , fNH() + , fCF() + , fLightMapNames() + , fLightMaps() + , fNLayers(0) + , fModuleLenght(0.) + , fGeoScale(0.) + , fNColumns1(0) + , fNRows1(0) + , fNColumns2(0) + , fNRows2(0) + , fNColumns(0) + , fNRows(0) + , fVolIdMax(0) + , fFirstNumber(0) + , fVolArr() + , fModules() + , fCells() + , fScTiles() + , fTileEdging() + , fPbTiles() + , fTvTiles() + , fHoleVol() + , fFiberVol() + , fSteelTapes() + , fHolePos() + , fModulesWithType() + , fRawNumber() + , fStructureId() { - fVerboseLevel = 1; + fVerboseLevel = 1; - Int_t i; + Int_t i; - for(i=kN-1;i>-1;i--) - fVolArr[i]=-1111; + for (i = kN - 1; i > -1; i--) + fVolArr[i] = -1111; } // ------------------------------------------------------------------------- - - // ----- Standard constructor ------------------------------------------ ecal::ecal(const char* name, Bool_t active, const char* fileGeo) - : FairDetector(name, active, kecal), - fInf(NULL), - fDebug(NULL), - fTrackID(-1), - fVolumeID(-1), - fPos(), - fMom(), - fTime(-1.), - fLength(-1.), - fELoss(-1.), - fPosIndex(0), - fEcalCollection(new TClonesArray("ecalPoint")), - fLiteCollection(new TClonesArray("ecalPoint")), - fEcalSize(), - fSimpleGeo(0), - fXSize(0), - fYSize(0), - fDX(0.), - fDY(0.), - fModuleSize(0.), - fZEcal(0.), - fSemiX(0.), - fSemiY(0.), - fThicknessLead(0.), - fThicknessScin(0.), - fThicknessTyvk(0.), - fThicknessLayer(0.), - fThicknessSteel(0.), - fEdging(0.), - fHoleRad(0.), - fFiberRad(0.), - fXCell(), - fYCell(), - fNH(), - fCF(), - fLightMapNames(), - fLightMaps(), - fNLayers(0), - fModuleLenght(0.), - fGeoScale(0.), - fNColumns1(0), - fNRows1(0), - fNColumns2(0), - fNRows2(0), - fNColumns(0), - fNRows(0), - fVolIdMax(0), - fFirstNumber(0), - fVolArr(), - fModules(), - fCells(), - fScTiles(), - fTileEdging(), - fPbTiles(), - fTvTiles(), - fHoleVol(), - fFiberVol(), - fSteelTapes(), - fHolePos(), - fModulesWithType(), - fRawNumber(), - fStructureId() + : FairDetector(name, active, kecal) + , fInf(NULL) + , fDebug(NULL) + , fTrackID(-1) + , fVolumeID(-1) + , fPos() + , fMom() + , fTime(-1.) + , fLength(-1.) + , fELoss(-1.) + , fPosIndex(0) + , fEcalCollection(new TClonesArray("ecalPoint")) + , fLiteCollection(new TClonesArray("ecalPoint")) + , fEcalSize() + , fSimpleGeo(0) + , fXSize(0) + , fYSize(0) + , fDX(0.) + , fDY(0.) + , fModuleSize(0.) + , fZEcal(0.) + , fSemiX(0.) + , fSemiY(0.) + , fThicknessLead(0.) + , fThicknessScin(0.) + , fThicknessTyvk(0.) + , fThicknessLayer(0.) + , fThicknessSteel(0.) + , fEdging(0.) + , fHoleRad(0.) + , fFiberRad(0.) + , fXCell() + , fYCell() + , fNH() + , fCF() + , fLightMapNames() + , fLightMaps() + , fNLayers(0) + , fModuleLenght(0.) + , fGeoScale(0.) + , fNColumns1(0) + , fNRows1(0) + , fNColumns2(0) + , fNRows2(0) + , fNColumns(0) + , fNRows(0) + , fVolIdMax(0) + , fFirstNumber(0) + , fVolArr() + , fModules() + , fCells() + , fScTiles() + , fTileEdging() + , fPbTiles() + , fTvTiles() + , fHoleVol() + , fFiberVol() + , fSteelTapes() + , fHolePos() + , fModulesWithType() + , fRawNumber() + , fStructureId() { - /** ecal constructor: - ** reads geometry parameters from the ascii file , - ** creates the ECAL geometry container ecalInf - ** and initializes basic geometry parameters needed to construct - ** TGeo geometry - **/ - - fVerboseLevel=0; - Int_t i; - Int_t j; - TString nm; - Info("ecal","Geometry is read from file %s.", fileGeo); - fInf=ecalInf::GetInstance(fileGeo); - if (fInf==NULL) - { - Fatal("ecal"," Can't read geometry from %s.", fileGeo); - return; - } - fGeoScale=1.; - fEcalSize[0]=fInf->GetEcalSize(0); - fEcalSize[1]=fInf->GetEcalSize(1); - fEcalSize[2]=fInf->GetEcalSize(2); - - fZEcal=fInf->GetZPos(); - - fThicknessLead=fInf->GetLead(); - fThicknessScin=fInf->GetScin(); - fThicknessTyvk=fInf->GetTyveec(); - fNLayers=fInf->GetNLayers(); - - fXSize=fInf->GetXSize(); - fYSize=fInf->GetYSize(); - - fPosIndex=0; - fDebug=""; - - fSemiX=fInf->GetVariableStrict("xsemiaxis"); - fSemiY=fInf->GetVariableStrict("ysemiaxis"); - fHoleRad=fInf->GetVariableStrict("holeradius"); - fFiberRad=fInf->GetVariableStrict("fiberradius"); - fThicknessSteel=fInf->GetVariableStrict("steel"); - fEdging=fInf->GetVariableStrict("tileedging"); - fModuleSize=fInf->GetVariableStrict("modulesize"); - fSimpleGeo=(Int_t)fInf->GetVariableStrict("usesimplegeo"); - fDX=fInf->GetVariableStrict("xpos"); - fDY=fInf->GetVariableStrict("ypos"); - - fInf->AddVariable("ecalversion", "1"); - for(i=kN-1;i>-1;i--) - fVolArr[i]=-1111; - - - for(i=0;iGetXSize();i++) - for(j=0;jGetYSize();j++) - fModulesWithType[fInf->GetType(i,j)]++; - - for(i=1;iGetVariableStrict(nm); - nm="nh[";nm+=i; nm+="]"; - fNH[i]=(Int_t)fInf->GetVariableStrict(nm); - nm="lightmap["; nm+=i; nm+="]"; - fLightMapNames[i]=fInf->GetStringVariable(nm); - if (fLightMapNames[i]!="none") - { - fLightMaps[i]=new ecalLightMap(fLightMapNames[i],nm); - Info("ecal", "Number of modules of type %d is %d (%d channels), lightmap %s", i, fModulesWithType[i], fModulesWithType[i]*i*i, fLightMapNames[i].Data()); + /** ecal constructor: + ** reads geometry parameters from the ascii file , + ** creates the ECAL geometry container ecalInf + ** and initializes basic geometry parameters needed to construct + ** TGeo geometry + **/ + + fVerboseLevel = 0; + Int_t i; + Int_t j; + TString nm; + Info("ecal", "Geometry is read from file %s.", fileGeo); + fInf = ecalInf::GetInstance(fileGeo); + if (fInf == NULL) { + Fatal("ecal", " Can't read geometry from %s.", fileGeo); + return; + } + fGeoScale = 1.; + fEcalSize[0] = fInf->GetEcalSize(0); + fEcalSize[1] = fInf->GetEcalSize(1); + fEcalSize[2] = fInf->GetEcalSize(2); + + fZEcal = fInf->GetZPos(); + + fThicknessLead = fInf->GetLead(); + fThicknessScin = fInf->GetScin(); + fThicknessTyvk = fInf->GetTyveec(); + fNLayers = fInf->GetNLayers(); + + fXSize = fInf->GetXSize(); + fYSize = fInf->GetYSize(); + + fPosIndex = 0; + fDebug = ""; + + fSemiX = fInf->GetVariableStrict("xsemiaxis"); + fSemiY = fInf->GetVariableStrict("ysemiaxis"); + fHoleRad = fInf->GetVariableStrict("holeradius"); + fFiberRad = fInf->GetVariableStrict("fiberradius"); + fThicknessSteel = fInf->GetVariableStrict("steel"); + fEdging = fInf->GetVariableStrict("tileedging"); + fModuleSize = fInf->GetVariableStrict("modulesize"); + fSimpleGeo = (Int_t)fInf->GetVariableStrict("usesimplegeo"); + fDX = fInf->GetVariableStrict("xpos"); + fDY = fInf->GetVariableStrict("ypos"); + + fInf->AddVariable("ecalversion", "1"); + for (i = kN - 1; i > -1; i--) + fVolArr[i] = -1111; + + for (i = 0; i < cMaxModuleType; i++) { + fModules[i] = NULL; + fCells[i] = NULL; + fScTiles[i] = NULL; + fPbTiles[i] = NULL; + fTvTiles[i] = NULL; + fHolePos[i] = NULL; + fTileEdging[i] = NULL; + fModulesWithType[i] = 0; + fLightMapNames[i] = ""; + fLightMaps[i] = NULL; + } + for (i = 0; i < 2; i++) { + fSteelTapes[i] = NULL; + } + for (i = 0; i < 3; i++) { + fHoleVol[i] = NULL; + fFiberVol[i] = NULL; + } + /** Counting modules **/ + for (i = 0; i < fInf->GetXSize(); i++) + for (j = 0; j < fInf->GetYSize(); j++) + fModulesWithType[fInf->GetType(i, j)]++; + + for (i = 1; i < cMaxModuleType; i++) { + if (fModulesWithType[i] == 0) + continue; + nm = "cf["; + nm += i; + nm += "]"; + fCF[i] = (Int_t)fInf->GetVariableStrict(nm); + nm = "nh["; + nm += i; + nm += "]"; + fNH[i] = (Int_t)fInf->GetVariableStrict(nm); + nm = "lightmap["; + nm += i; + nm += "]"; + fLightMapNames[i] = fInf->GetStringVariable(nm); + if (fLightMapNames[i] != "none") { + fLightMaps[i] = new ecalLightMap(fLightMapNames[i], nm); + Info("ecal", + "Number of modules of type %d is %d (%d channels), lightmap %s", + i, + fModulesWithType[i], + fModulesWithType[i] * i * i, + fLightMapNames[i].Data()); + } else + fLightMaps[i] = NULL; + fXCell[i] = (fModuleSize - 2.0 * fThicknessSteel) / i - 2.0 * fEdging; + fYCell[i] = (fModuleSize - 2.0 * fThicknessSteel) / i - 2.0 * fEdging; + Info("ecal", "Size of cell of type %d is %f cm.", i, fXCell[i]); } - else - fLightMaps[i]=NULL; - fXCell[i]=(fModuleSize-2.0*fThicknessSteel)/i-2.0*fEdging; - fYCell[i]=(fModuleSize-2.0*fThicknessSteel)/i-2.0*fEdging; - Info("ecal", "Size of cell of type %d is %f cm.", i, fXCell[i]); - } } // ------------------------------------------------------------------------- void ecal::Initialize() { - FairDetector::Initialize(); -/* - FairRun* sim = FairRun::Instance(); - FairRuntimeDb* rtdb=sim->GetRuntimeDb(); - CbmGeoEcalPar *par=new CbmGeoEcalPar(); -// fInf->FillGeoPar(par,0); - rtdb->addContainer(par); -*/ + FairDetector::Initialize(); + /* + FairRun* sim = FairRun::Instance(); + FairRuntimeDb* rtdb=sim->GetRuntimeDb(); + CbmGeoEcalPar *par=new CbmGeoEcalPar(); + // fInf->FillGeoPar(par,0); + rtdb->addContainer(par); + */ } // ----- Destructor ---------------------------------------------------- ecal::~ecal() { - if (fEcalCollection) { - fEcalCollection->Delete(); - delete fEcalCollection; - fEcalCollection=NULL; - } - if (fLiteCollection) { - fLiteCollection->Delete(); - delete fLiteCollection; - fLiteCollection=NULL; - } + if (fEcalCollection) { + fEcalCollection->Delete(); + delete fEcalCollection; + fEcalCollection = NULL; + } + if (fLiteCollection) { + fLiteCollection->Delete(); + delete fLiteCollection; + fLiteCollection = NULL; + } } // ------------------------------------------------------------------------- // ----- Private method SetEcalCuts ------------------------------------ void ecal::SetEcalCuts(Int_t medium) { - /** Set GEANT3 tracking energy cuts for selected medium **/ - if (fInf->GetElectronCut() > 0) { - gMC->Gstpar(medium,"CUTGAM",fInf->GetElectronCut()); - gMC->Gstpar(medium,"CUTELE",fInf->GetElectronCut()); - gMC->Gstpar(medium,"BCUTE" ,fInf->GetElectronCut()); - gMC->Gstpar(medium,"BCUTM" ,fInf->GetElectronCut()); - } - - if (fInf->GetHadronCut() > 0) { - gMC->Gstpar(medium,"CUTNEU",fInf->GetHadronCut()); - gMC->Gstpar(medium,"CUTHAD",fInf->GetHadronCut()); - gMC->Gstpar(medium,"CUTMUO",fInf->GetHadronCut()); - gMC->Gstpar(medium,"PPCUTM",fInf->GetHadronCut()); - } - ; + /** Set GEANT3 tracking energy cuts for selected medium **/ + if (fInf->GetElectronCut() > 0) { + gMC->Gstpar(medium, "CUTGAM", fInf->GetElectronCut()); + gMC->Gstpar(medium, "CUTELE", fInf->GetElectronCut()); + gMC->Gstpar(medium, "BCUTE", fInf->GetElectronCut()); + gMC->Gstpar(medium, "BCUTM", fInf->GetElectronCut()); + } + + if (fInf->GetHadronCut() > 0) { + gMC->Gstpar(medium, "CUTNEU", fInf->GetHadronCut()); + gMC->Gstpar(medium, "CUTHAD", fInf->GetHadronCut()); + gMC->Gstpar(medium, "CUTMUO", fInf->GetHadronCut()); + gMC->Gstpar(medium, "PPCUTM", fInf->GetHadronCut()); + }; } // ------------------------------------------------------------------------- void ecal::FinishPrimary() { - fFirstNumber=fLiteCollection->GetEntriesFast(); + fFirstNumber = fLiteCollection->GetEntriesFast(); } //_____________________________________________________________________________ void ecal::ChangeHit(ecalPoint* oldHit) { - Double_t edep = fELoss; - Double_t el=oldHit->GetEnergyLoss(); - Double_t ttime=gMC->TrackTime()*1.0e9; - oldHit->SetEnergyLoss(el+edep); - if(ttimeGetTime()) - oldHit->SetTime(ttime); + Double_t edep = fELoss; + Double_t el = oldHit->GetEnergyLoss(); + Double_t ttime = gMC->TrackTime() * 1.0e9; + oldHit->SetEnergyLoss(el + edep); + if (ttime < oldHit->GetTime()) + oldHit->SetTime(ttime); } //_____________________________________________________________________________ void ecal::SetSpecialPhysicsCuts() { - /** Change the special tracking cuts for - ** two ECAL media, Scintillator and Lead - **/ - FairRun* fRun = FairRun::Instance(); -// if (strcmp(fRun->GetName(),"TGeant3") == 0) - { - Int_t mediumID; - mediumID = gGeoManager->GetMedium("Scintillator")->GetId(); - SetEcalCuts(mediumID); - mediumID = gGeoManager->GetMedium("Lead")->GetId(); - SetEcalCuts(mediumID); - mediumID = gGeoManager->GetMedium("Tyvek")->GetId(); - SetEcalCuts(mediumID); - mediumID = gGeoManager->GetMedium("SensVacuum")->GetId(); - SetEcalCuts(mediumID); - mediumID = gGeoManager->GetMedium("ECALAir")->GetId(); - SetEcalCuts(mediumID); - mediumID = gGeoManager->GetMedium("ECALFiber")->GetId(); - SetEcalCuts(mediumID); - mediumID = gGeoManager->GetMedium("ECALTileEdging")->GetId(); - SetEcalCuts(mediumID); - mediumID = gGeoManager->GetMedium("ECALSteel")->GetId(); - SetEcalCuts(mediumID); - } + /** Change the special tracking cuts for + ** two ECAL media, Scintillator and Lead + **/ + FairRun* fRun = FairRun::Instance(); + // if (strcmp(fRun->GetName(),"TGeant3") == 0) + { + Int_t mediumID; + mediumID = gGeoManager->GetMedium("Scintillator")->GetId(); + SetEcalCuts(mediumID); + mediumID = gGeoManager->GetMedium("Lead")->GetId(); + SetEcalCuts(mediumID); + mediumID = gGeoManager->GetMedium("Tyvek")->GetId(); + SetEcalCuts(mediumID); + mediumID = gGeoManager->GetMedium("SensVacuum")->GetId(); + SetEcalCuts(mediumID); + mediumID = gGeoManager->GetMedium("ECALAir")->GetId(); + SetEcalCuts(mediumID); + mediumID = gGeoManager->GetMedium("ECALFiber")->GetId(); + SetEcalCuts(mediumID); + mediumID = gGeoManager->GetMedium("ECALTileEdging")->GetId(); + SetEcalCuts(mediumID); + mediumID = gGeoManager->GetMedium("ECALSteel")->GetId(); + SetEcalCuts(mediumID); + } } // ----- Public method ProcessHits -------------------------------------- -Bool_t ecal::ProcessHits(FairVolume* vol) +Bool_t ecal::ProcessHits(FairVolume* vol) { - /** Fill MC point for sensitive ECAL volumes **/ - TString Ecal="Ecal"; - fELoss = gMC->Edep(); - fTrackID = gMC->GetStack()->GetCurrentTrackNumber(); - fTime = gMC->TrackTime()*1.0e09; - fLength = gMC->TrackLength(); - Double_t bx, by, bz; - TParticle* bp=gMC->GetStack()->GetCurrentTrack(); - gMC->TrackPosition(bx, by, bz); - Int_t volID; - gMC->CurrentVolID(volID); - //cout <<"Ecal called "<getVolumeId()<<" "<GetVolume(vol->getVolumeId())->GetName()<<" "<CurrentVolName()<<" "<getVolumeId()==fStructureId) { - if (Ecal.CompareTo(gMC->CurrentVolName())==0) { - if (gMC->IsTrackEntering()) { - FillWallPoint(); - //cout <<"fill wallpoint "<getVolumeId()<<" "<GetStack())->AddPoint(kecal, fTrackID); - - ResetParameters(); - - return kTRUE; - } else { - return kFALSE; + /** Fill MC point for sensitive ECAL volumes **/ + TString Ecal = "Ecal"; + fELoss = gMC->Edep(); + fTrackID = gMC->GetStack()->GetCurrentTrackNumber(); + fTime = gMC->TrackTime() * 1.0e09; + fLength = gMC->TrackLength(); + Double_t bx, by, bz; + TParticle* bp = gMC->GetStack()->GetCurrentTrack(); + gMC->TrackPosition(bx, by, bz); + Int_t volID; + gMC->CurrentVolID(volID); + // cout <<"Ecal called "<getVolumeId()<<" "<GetVolume(vol->getVolumeId())->GetName()<<" "<CurrentVolName()<<" "<getVolumeId()==fStructureId) { + if (Ecal.CompareTo(gMC->CurrentVolName()) == 0) { + if (gMC->IsTrackEntering()) { + FillWallPoint(); + // cout <<"fill wallpoint "<getVolumeId()<<" "<GetStack())->AddPoint(kecal, fTrackID); + + ResetParameters(); + + return kTRUE; + } else { + return kFALSE; + } } - } - - if (fELoss<=0) return kFALSE; - if (fELoss>0) - { - Int_t i; - TParticle* p=gMC->GetStack()->GetCurrentTrack(); - Double_t x, y, z; - Double_t px; - Double_t py; - Double_t dx; - Int_t mx; - Int_t my; - Int_t cell; - Int_t type; - Int_t cx; - Int_t cy; - gMC->TrackPosition(x, y, z); -// cout << "Id: " << p->GetPdgCode() << " (" << x << ", " << y << ", "; -// cout << z << "): "; -// cout << endl; -/* - for(i=0;i<10;i++) - { - gMC->CurrentVolOffID(i, mx); cout << i << ":" << mx << ", "; - } - cout << endl; -*/ - if (fSimpleGeo==0) - { - gMC->CurrentVolOffID(3, mx); mx--; - gMC->CurrentVolOffID(4, my); my--; - gMC->CurrentVolOffID(2, cell); cell--; - } - else - { - gMC->CurrentVolOffID(2, mx); mx--; - gMC->CurrentVolOffID(3, my); my--; - gMC->CurrentVolOffID(1, cell); cell--; - } - Int_t id=(my*100+mx)*100+cell+1; - if (id<0){ - if (Ecal.CompareTo(gMC->CurrentVolName())==0&&fELoss<1e-19) - return kTRUE; - cout << "neg id "<CurrentVolName()<<" "<CurrentVolOffName(1)<<" "<CurrentVolOffName(2)<<" "<GetType(mx, my); - Float_t d=fInf->GetVariableStrict("modulesize")/type; - if (x>rx-0.001&&xry-0.001&&y 0) { + Int_t i; + TParticle* p = gMC->GetStack()->GetCurrentTrack(); + Double_t x, y, z; + Double_t px; + Double_t py; + Double_t dx; + Int_t mx; + Int_t my; + Int_t cell; + Int_t type; + Int_t cx; + Int_t cy; + gMC->TrackPosition(x, y, z); + // cout << "Id: " << p->GetPdgCode() << " (" << x << ", " << y << ", "; + // cout << z << "): "; + // cout << endl; + /* + for(i=0;i<10;i++) + { + gMC->CurrentVolOffID(i, mx); cout << i << ":" << mx << ", "; + } + cout << endl; + */ + if (fSimpleGeo == 0) { + gMC->CurrentVolOffID(3, mx); + mx--; + gMC->CurrentVolOffID(4, my); + my--; + gMC->CurrentVolOffID(2, cell); + cell--; + } else { + gMC->CurrentVolOffID(2, mx); + mx--; + gMC->CurrentVolOffID(3, my); + my--; + gMC->CurrentVolOffID(1, cell); + cell--; + } + Int_t id = (my * 100 + mx) * 100 + cell + 1; + if (id < 0) { + if (Ecal.CompareTo(gMC->CurrentVolName()) == 0 && fELoss < 1e-19) + return kTRUE; + cout << "neg id " << mx << " " << my << " " << cell << " " << gMC->CurrentVolName() << " " + << gMC->CurrentVolOffName(1) << " " << gMC->CurrentVolOffName(2) << " " << fELoss << " " + << fELoss * 1e10 << endl; + } + /* + Float_t rx; Float_t ry; Int_t ten; + GetCellCoordInf(id, rx, ry, ten); rx--; ry--; + type=fInf->GetType(mx, my); + Float_t d=fInf->GetVariableStrict("modulesize")/type; + if (x>rx-0.001&&xry-0.001&&yGetType(mx, my); + cx = cell % type; + cy = cell / type; + // An old version + // px=mx*fModuleSize-fEcalSize[0]/2.0+cx*fModuleSize/type; + // py=my*fModuleSize-fEcalSize[1]/2.0+cy*fModuleSize/type; + // With correction for steel tapes and edging + px = mx * fModuleSize - fEcalSize[0] / 2.0 + fXCell[type] * cx + (2 * cx + 1) * fEdging + fThicknessSteel; + py = my * fModuleSize - fEcalSize[1] / 2.0 + fYCell[type] * cy + (2 * cy + 1) * fEdging + fThicknessSteel; + + px = (x - px) / fXCell[type]; + py = (y - py) / fYCell[type]; + if (px >= 0 && px < 1 && py >= 0 && py < 1) { + fELoss *= fLightMaps[type]->Data(px - 0.5, py - 0.5); + FillLitePoint(0); + } + } else + FillLitePoint(0); + // for(i=0;i<8;i++) + // { + // Int_t t; + // + // gMC->CurrentVolOffID(i, t); + // cout << i << ": " << gMC->CurrentVolOffName(i) << " " << t << "; "; + // } + // cout << endl; } - else - { - cout << mx << ", " << my << ", " << cell << endl; - cout << "--- "; - cout << "(" << x << ", " << y << ") : (" << rx << ", " << ry << ")" << endl; - } -*/ - fVolumeID=id; - if (fSimpleGeo==0) - { - type=fInf->GetType(mx, my); - cx=cell%type; - cy=cell/type; - // An old version - // px=mx*fModuleSize-fEcalSize[0]/2.0+cx*fModuleSize/type; - // py=my*fModuleSize-fEcalSize[1]/2.0+cy*fModuleSize/type; - // With correction for steel tapes and edging - px=mx*fModuleSize-fEcalSize[0]/2.0+fXCell[type]*cx+(2*cx+1)*fEdging+fThicknessSteel; - py=my*fModuleSize-fEcalSize[1]/2.0+fYCell[type]*cy+(2*cy+1)*fEdging+fThicknessSteel; - - px=(x-px)/fXCell[type]; - py=(y-py)/fYCell[type]; - if (px>=0&&px<1&&py>=0&&py<1) - { - fELoss*=fLightMaps[type]->Data(px-0.5, py-0.5); - FillLitePoint(0); - } - } - else - FillLitePoint(0); -// for(i=0;i<8;i++) -// { -// Int_t t; -// -// gMC->CurrentVolOffID(i, t); -// cout << i << ": " << gMC->CurrentVolOffName(i) << " " << t << "; "; -// } -// cout << endl; - } - ((ShipStack*)gMC->GetStack())->AddPoint(kecal, fTrackID); - - ResetParameters(); - - return kTRUE; + ((ShipStack*)gMC->GetStack())->AddPoint(kecal, fTrackID); + + ResetParameters(); + return kTRUE; } /** returns type of volume **/ Int_t ecal::GetVolType(Int_t volnum) { - Int_t i; - for(i=kN-1;i>-1;i--) { - if (fVolArr[i]==volnum) break; - } + Int_t i; + for (i = kN - 1; i > -1; i--) { + if (fVolArr[i] == volnum) + break; + } - return i; + return i; } //----------------------------------------------------------------------------- void ecal::FillWallPoint() { - /** Fill MC points on the ECAL front wall **/ - - gMC->TrackPosition(fPos); - gMC->TrackMomentum(fMom); - fVolumeID = -1; - Double_t mass = gMC->TrackMass(); - // Calculate kinetic energy - Double_t ekin = TMath::Sqrt( fMom.Px()*fMom.Px() + - fMom.Py()*fMom.Py() + - fMom.Pz()*fMom.Pz() + - mass * mass ) - mass; - fELoss = ekin; - // Create ecalPoint at the entrance of calorimeter - // for particles with pz>0 coming through the front wall - if (fMom.Pz() > 0 && fPos.Z() < fZEcal+0.01) - { - TParticle* part=((ShipStack*)gMC->GetStack())->GetParticle(fTrackID); - AddHit(fTrackID, fVolumeID, TVector3(fPos.X(), fPos.Y(), fPos.Z()), - TVector3(fMom.Px(), fMom.Py(), fMom.Pz()), fTime, fLength, - fELoss, part->GetPdgCode()); - } - fTrackID=gMC->GetStack()->GetCurrentTrackNumber(); + /** Fill MC points on the ECAL front wall **/ + + gMC->TrackPosition(fPos); + gMC->TrackMomentum(fMom); + fVolumeID = -1; + Double_t mass = gMC->TrackMass(); + // Calculate kinetic energy + Double_t ekin = + TMath::Sqrt(fMom.Px() * fMom.Px() + fMom.Py() * fMom.Py() + fMom.Pz() * fMom.Pz() + mass * mass) - mass; + fELoss = ekin; + // Create ecalPoint at the entrance of calorimeter + // for particles with pz>0 coming through the front wall + if (fMom.Pz() > 0 && fPos.Z() < fZEcal + 0.01) { + TParticle* part = ((ShipStack*)gMC->GetStack())->GetParticle(fTrackID); + AddHit(fTrackID, + fVolumeID, + TVector3(fPos.X(), fPos.Y(), fPos.Z()), + TVector3(fMom.Px(), fMom.Py(), fMom.Pz()), + fTime, + fLength, + fELoss, + part->GetPdgCode()); + } + fTrackID = gMC->GetStack()->GetCurrentTrackNumber(); } ecalPoint* ecal::FindHit(Int_t VolId, Int_t TrackId) { - for(Int_t i=fFirstNumber;iGetEntriesFast();i++) - { - ecalPoint* point=(ecalPoint*)fLiteCollection->At(i); - if (point->GetTrackID()==TrackId&&point->GetDetectorID()==VolId) - return point; - } - return NULL; + for (Int_t i = fFirstNumber; i < fLiteCollection->GetEntriesFast(); i++) { + ecalPoint* point = (ecalPoint*)fLiteCollection->At(i); + if (point->GetTrackID() == TrackId && point->GetDetectorID() == VolId) + return point; + } + return NULL; } //----------------------------------------------------------------------------- Bool_t ecal::FillLitePoint(Int_t volnum) { - /** Fill MC points inside the ECAL for non-zero deposited energy **/ - - //Search for input track - - static Float_t zmin=fZEcal-0.0001; - static Float_t zmax=fZEcal+fEcalSize[2]; - static Float_t xecal=fEcalSize[0]/2; - static Float_t yecal=fEcalSize[1]/2; - TParticle* part=gMC->GetStack()->GetCurrentTrack(); - fTrackID=gMC->GetStack()->GetCurrentTrackNumber(); - -// cout << zmin << " : " << zmax << " : " << xecal << ", " << yecal << endl; -// cout << part->GetFirstMother() << " : " << part->Vx() << ", " << part->Vy() << ", " << part->Vz() << endl; - /** Need to rewrite this part **/ - while (part->GetFirstMother()>=0&&part->Vz()>=zmin&&part->Vz()<=zmax&&TMath::Abs(part->Vx())<=xecal&&TMath::Abs(part->Vy())<=yecal) - { - fTrackID=part->GetFirstMother(); - part =((ShipStack*)gMC->GetStack())->GetParticle(fTrackID); -// cout << "-> " << part->GetFirstMother() << " : " << part->Vx() << ", " << part->Vy() << ", " << part->Vz() << endl; + /** Fill MC points inside the ECAL for non-zero deposited energy **/ + + // Search for input track + + static Float_t zmin = fZEcal - 0.0001; + static Float_t zmax = fZEcal + fEcalSize[2]; + static Float_t xecal = fEcalSize[0] / 2; + static Float_t yecal = fEcalSize[1] / 2; + TParticle* part = gMC->GetStack()->GetCurrentTrack(); + fTrackID = gMC->GetStack()->GetCurrentTrackNumber(); + + // cout << zmin << " : " << zmax << " : " << xecal << ", " << yecal << endl; + // cout << part->GetFirstMother() << " : " << part->Vx() << ", " << part->Vy() << ", " << part->Vz() << endl; + /** Need to rewrite this part **/ + while (part->GetFirstMother() >= 0 && part->Vz() >= zmin && part->Vz() <= zmax && TMath::Abs(part->Vx()) <= xecal + && TMath::Abs(part->Vy()) <= yecal) { + fTrackID = part->GetFirstMother(); + part = ((ShipStack*)gMC->GetStack())->GetParticle(fTrackID); + // cout << "-> " << part->GetFirstMother() << " : " << part->Vx() << ", " << part->Vy() << ", " << + // part->Vz() << endl; } // if (part->Vz()>500) // cout << part->Vx() << ", " << part->Vy() << ", " << part->Vz() << endl; #ifdef _DECAL - if (fTrackID<0) cout<<"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!fTrackID="<GetEntriesFast(); - cout << "-I- ecal: " << nLiteHits << " lite points registered in this event."; - cout << endl; - - if (fVerboseLevel>1) - { - for (i=0;iPrint(); - for (i=0;iPrint(); - } + Int_t nHits = fEcalCollection->GetEntriesFast(); + Int_t nLiteHits; + Int_t i; + + cout << "-I- ecal: " << nHits << " points registered in this event."; + cout << endl; + + nLiteHits = fLiteCollection->GetEntriesFast(); + cout << "-I- ecal: " << nLiteHits << " lite points registered in this event."; + cout << endl; + + if (fVerboseLevel > 1) { + for (i = 0; i < nHits; i++) + (*fEcalCollection)[i]->Print(); + for (i = 0; i < nLiteHits; i++) + (*fLiteCollection)[i]->Print(); + } } // ------------------------------------------------------------------------- // ----- Public method CopyClones -------------------------------------- void ecal::CopyClones(TClonesArray* cl1, TClonesArray* cl2, Int_t offset) { - Int_t nEntries = cl1->GetEntriesFast(); - Int_t i; - Int_t index; - cout << "-I- ecal: " << nEntries << " entries to add." << endl; - TClonesArray& clref = *cl2; - if (cl1->GetClass()==ecalPoint::Class()) { - ecalPoint* oldpoint = NULL; - for (i=0; iAt(i); - index = oldpoint->GetTrackID()+offset; - oldpoint->SetTrackID(index); - new (clref[fPosIndex]) ecalPoint(*oldpoint); - fPosIndex++; - } - cout << "-I- ecal: " << cl2->GetEntriesFast() << " merged entries." - << endl; - } - else if (cl1->GetClass()==ecalPoint::Class()) { - ecalPoint* oldpoint = NULL; - for (i=0; iAt(i); - index = oldpoint->GetTrackID()+offset; - oldpoint->SetTrackID(index); - new (clref[fPosIndex]) ecalPoint(*oldpoint); - fPosIndex++; + Int_t nEntries = cl1->GetEntriesFast(); + Int_t i; + Int_t index; + cout << "-I- ecal: " << nEntries << " entries to add." << endl; + TClonesArray& clref = *cl2; + if (cl1->GetClass() == ecalPoint::Class()) { + ecalPoint* oldpoint = NULL; + for (i = 0; i < nEntries; i++) { + oldpoint = (ecalPoint*)cl1->At(i); + index = oldpoint->GetTrackID() + offset; + oldpoint->SetTrackID(index); + new (clref[fPosIndex]) ecalPoint(*oldpoint); + fPosIndex++; + } + cout << "-I- ecal: " << cl2->GetEntriesFast() << " merged entries." << endl; + } else if (cl1->GetClass() == ecalPoint::Class()) { + ecalPoint* oldpoint = NULL; + for (i = 0; i < nEntries; i++) { + oldpoint = (ecalPoint*)cl1->At(i); + index = oldpoint->GetTrackID() + offset; + oldpoint->SetTrackID(index); + new (clref[fPosIndex]) ecalPoint(*oldpoint); + fPosIndex++; + } + cout << "-I- ecal: " << cl2->GetEntriesFast() << " merged entries." << endl; } - cout << "-I- ecal: " << cl2->GetEntriesFast() << " merged entries." - << endl; - } } // ------------------------------------------------------------------------- // ----- Public method Register ---------------------------------------- void ecal::Register() { - FairRootManager::Instance()->Register("EcalPoint","Ecal",fEcalCollection,kTRUE); - FairRootManager::Instance()->Register("EcalPointLite","EcalLite",fLiteCollection,kTRUE); - ; + FairRootManager::Instance()->Register("EcalPoint", "Ecal", fEcalCollection, kTRUE); + FairRootManager::Instance()->Register("EcalPointLite", "EcalLite", fLiteCollection, kTRUE); + ; } // ------------------------------------------------------------------------- // ----- Public method ConstructGeometry ------------------------------- void ecal::ConstructGeometry() { - FairGeoLoader*geoLoad = FairGeoLoader::Instance(); - FairGeoInterface *geoFace = geoLoad->getGeoInterface(); - FairGeoMedia *Media = geoFace->getMedia(); - FairGeoBuilder *geobuild=geoLoad->getGeoBuilder(); - - TGeoVolume *top=gGeoManager->GetTopVolume(); - - // cout << top->GetName() << endl; - TGeoVolume *volume; - FairGeoMedium *CbmMedium; - TGeoPgon *spl; - - Float_t *buf = 0; - Int_t i; - Double_t par[10]; - Float_t y; - TString nm; - Double_t thickness=fThicknessLead+fThicknessScin+fThicknessTyvk*2; - Double_t moduleth=thickness*fNLayers; -// Float_t sumWeight; -// Int_t i; - - // create SensVacuum which is defined in the media file - - /** Initialize all media **/ - InitMedia(); - par[0]=fSemiX; - par[1]=fSemiY; - par[2]=moduleth/2.0+0.1; - volume=gGeoManager->Volume("Ecal", "BOX", gGeoManager->GetMedium("SensVacuum")->GetId(), par, 3); - gGeoManager->Node("Ecal", 1, top->GetName(), 0.0,0.0, fZEcal+par[2]-0.05, 0, kTRUE, buf, 0); - volume->SetVisLeaves(kTRUE); - volume->SetVisContainers(kFALSE); - volume->SetVisibility(kFALSE); - AddSensitiveVolume(volume); - fStructureId=volume->GetNumber(); - - for(i=1;i0) { - if (fSimpleGeo==0) - ConstructModule(i); - else - ConstructModuleSimple(i); + FairGeoLoader* geoLoad = FairGeoLoader::Instance(); + FairGeoInterface* geoFace = geoLoad->getGeoInterface(); + FairGeoMedia* Media = geoFace->getMedia(); + FairGeoBuilder* geobuild = geoLoad->getGeoBuilder(); + + TGeoVolume* top = gGeoManager->GetTopVolume(); + + // cout << top->GetName() << endl; + TGeoVolume* volume; + FairGeoMedium* CbmMedium; + TGeoPgon* spl; + + Float_t* buf = 0; + Int_t i; + Double_t par[10]; + Float_t y; + TString nm; + Double_t thickness = fThicknessLead + fThicknessScin + fThicknessTyvk * 2; + Double_t moduleth = thickness * fNLayers; + // Float_t sumWeight; + // Int_t i; + + // create SensVacuum which is defined in the media file + + /** Initialize all media **/ + InitMedia(); + par[0] = fSemiX; + par[1] = fSemiY; + par[2] = moduleth / 2.0 + 0.1; + volume = gGeoManager->Volume("Ecal", "BOX", gGeoManager->GetMedium("SensVacuum")->GetId(), par, 3); + gGeoManager->Node("Ecal", 1, top->GetName(), 0.0, 0.0, fZEcal + par[2] - 0.05, 0, kTRUE, buf, 0); + volume->SetVisLeaves(kTRUE); + volume->SetVisContainers(kFALSE); + volume->SetVisibility(kFALSE); + AddSensitiveVolume(volume); + fStructureId = volume->GetNumber(); + + for (i = 1; i < cMaxModuleType; i++) { + if (fModulesWithType[i] > 0) { + if (fSimpleGeo == 0) + ConstructModule(i); + else + ConstructModuleSimple(i); + } } - } - - TGeoVolume* vol=new TGeoVolumeAssembly("EcalStructure"); -//To suppress warring - vol->SetMedium(gGeoManager->GetMedium("SensVacuum")); - for(i=0;iSetMedium(gGeoManager->GetMedium("SensVacuum")); + for (i = 0; i < fYSize; i++) { + // cout << i << " " << flush; + volume = ConstructRaw(i); + if (volume == NULL) { + // cout << endl; + continue; + } + nm = volume->GetName(); + y = (i - fYSize / 2.0 + 0.5) * fModuleSize; + // cout << volume->GetName() << flush; + gGeoManager->Node(nm.Data(), i + 1, "EcalStructure", 0.0, y, 0.0, 0, kTRUE, buf, 0); + // cout << endl << flush; } - nm=volume->GetName(); - y=(i-fYSize/2.0+0.5)*fModuleSize; -// cout << volume->GetName() << flush; - gGeoManager->Node(nm.Data(), i+1, "EcalStructure", 0.0, y, 0.0, 0, kTRUE, buf, 0); -// cout << endl << flush; - } -//TODO: -//Should move the guarding volume, not structure itself - gGeoManager->Node("EcalStructure", 1, "Ecal", fDX, fDY, 0.0, 0, kTRUE, buf, 0); + // TODO: + // Should move the guarding volume, not structure itself + gGeoManager->Node("EcalStructure", 1, "Ecal", fDX, fDY, 0.0, 0, kTRUE, buf, 0); } // ------------------------------------------------------------------------- // ----- Public method ConstructRaw ---------------------------------------- TGeoVolume* ecal::ConstructRaw(Int_t num) { - Int_t i; - list >::const_iterator p=fRawNumber.begin(); - pair out; - Float_t x; - Float_t* buf=NULL; - for(i=0;iGetType(i, num)!=0) break; - if (i==fXSize) - return NULL; - for(;p!=fRawNumber.end();++p) - { - for(i=0;iGetType(i, num)!=fInf->GetType(i, (*p).first)) - break; - if (i==fXSize) - break; - } - if (p!=fRawNumber.end()) - return (*p).second; - TString nm="ECALRaw"; nm+=num; - TString md; - TGeoVolume* vol=new TGeoVolumeAssembly(nm); -//To suppress warring - vol->SetMedium(gGeoManager->GetMedium("SensVacuum")); - for(i=0;iGetType(i, num)==0) continue; - md="EcalModule"; md+=(Int_t)fInf->GetType(i, num); - gGeoManager->Node(md.Data(),i+1, nm.Data(), x, 0.0, 0.0, 0, kTRUE, buf, 0); - } - - out.first=num; - out.second=vol; - fRawNumber.push_back(out); - return out.second; + Int_t i; + list>::const_iterator p = fRawNumber.begin(); + pair out; + Float_t x; + Float_t* buf = NULL; + for (i = 0; i < fXSize; i++) + if ((Int_t)fInf->GetType(i, num) != 0) + break; + if (i == fXSize) + return NULL; + for (; p != fRawNumber.end(); ++p) { + for (i = 0; i < fXSize; i++) + if (fInf->GetType(i, num) != fInf->GetType(i, (*p).first)) + break; + if (i == fXSize) + break; + } + if (p != fRawNumber.end()) + return (*p).second; + TString nm = "ECALRaw"; + nm += num; + TString md; + TGeoVolume* vol = new TGeoVolumeAssembly(nm); + // To suppress warring + vol->SetMedium(gGeoManager->GetMedium("SensVacuum")); + for (i = 0; i < fXSize; i++) { + x = (i - fXSize / 2.0 + 0.5) * fModuleSize; + if (fInf->GetType(i, num) == 0) + continue; + md = "EcalModule"; + md += (Int_t)fInf->GetType(i, num); + gGeoManager->Node(md.Data(), i + 1, nm.Data(), x, 0.0, 0.0, 0, kTRUE, buf, 0); + } + + out.first = num; + out.second = vol; + fRawNumber.push_back(out); + return out.second; } // ------------------------------------------------------------------------- - // ----- Public method BeginEvent ----------------------------------------- void ecal::BeginEvent() { - ; + ; } // ------------------------------------------------------------------------- - // ------------------------------------------------------------------------- // ----- Private method AddHit ----------------------------------------- -ecalPoint* ecal::AddHit(Int_t trackID, Int_t detID, TVector3 pos, - TVector3 mom, Double_t time, Double_t length, - Double_t eLoss, Int_t pdgcode) +ecalPoint* ecal::AddHit(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t time, + Double_t length, + Double_t eLoss, + Int_t pdgcode) { - TClonesArray& clref = *fEcalCollection; - Int_t size = clref.GetEntriesFast(); - return new(clref[size]) ecalPoint(trackID, detID, pos, mom, - time, length, eLoss, pdgcode); + TClonesArray& clref = *fEcalCollection; + Int_t size = clref.GetEntriesFast(); + return new (clref[size]) ecalPoint(trackID, detID, pos, mom, time, length, eLoss, pdgcode); } // ------------------------------------------------------------------------- // ----- Private method AddHit ----------------------------------------- ecalPoint* ecal::AddLiteHit(Int_t trackID, Int_t detID, Double32_t time, Double32_t eLoss) { - TClonesArray& clref = *fLiteCollection; - Int_t size = clref.GetEntriesFast(); - return new(clref[size]) ecalPoint(trackID, detID, time, eLoss); + TClonesArray& clref = *fLiteCollection; + Int_t size = clref.GetEntriesFast(); + return new (clref[size]) ecalPoint(trackID, detID, time, eLoss); } // ------------------------------------------------------------------------- // ----- Private method ConstructModule ---------------------------------- void ecal::ConstructModule(Int_t type) { - if (fModules[type]!=NULL) return; - ConstructCell(type); - - TString nm="EcalModule"; nm+=type; - TString nm1; - TString cellname="EcalCell"; cellname+=type; - Int_t i; - Int_t j; - Int_t n; - Float_t x; - Float_t y; - Float_t* buf=NULL; - Double_t thickness=fThicknessLead+fThicknessScin+fThicknessTyvk*2; - Double_t moduleth=thickness*fNLayers; - Double_t par[3]={fModuleSize/2.0, fModuleSize/2.0, moduleth/2.0}; - if (fSteelTapes[0]==NULL) - { - TGeoBBox* st1=new TGeoBBox(fThicknessSteel/2.0, fModuleSize/2.0-fThicknessSteel, moduleth/2.0); - nm1="EcalModuleSteelTape1_"; //nm1+=type; - fSteelTapes[0]=new TGeoVolume(nm1.Data(), st1, gGeoManager->GetMedium("ECALSteel")); - } - if (fSteelTapes[1]==NULL) - { - TGeoBBox* st2=new TGeoBBox(fModuleSize/2.0-fThicknessSteel, fThicknessSteel/2.0, moduleth/2.0); - nm1="EcalModuleSteelTape2_"; //nm1+=type; - fSteelTapes[1]=new TGeoVolume(nm1.Data(), st2, gGeoManager->GetMedium("ECALSteel")); - } - - -// TGeoVolume* modulev=new TGeoVolumeAssembly(nm); - TGeoVolume* modulev=gGeoManager->Volume(nm.Data(), "BOX", gGeoManager->GetMedium("ECALAir")->GetId(), par, 3); - modulev->SetLineColor(kYellow); - - //Adding cells into module - for(i=0;iNode(cellname.Data(), n, nm.Data(), x, y, 0.0, 0, kTRUE, buf, 0); - } - nm1="EcalModuleSteelTape1_"; //nm1+=type; - gGeoManager->Node(nm1.Data(), 1, nm.Data(), -fThicknessSteel/2.0+fModuleSize/2.0, 0.0, 0.0, 0, kTRUE, buf, 0); - gGeoManager->Node(nm1.Data(), 2, nm.Data(), +fThicknessSteel/2.0-fModuleSize/2.0, 0.0, 0.0, 0, kTRUE, buf, 0); - nm1="EcalModuleSteelTape2_"; //nm1+=type; - gGeoManager->Node(nm1.Data(), 1, nm.Data(), 0.0, -fThicknessSteel/2.0+fModuleSize/2.0, 0.0, 0, kTRUE, buf, 0); - gGeoManager->Node(nm1.Data(), 2, nm.Data(), 0.0, +fThicknessSteel/2.0-fModuleSize/2.0, 0.0, 0, kTRUE, buf, 0); - fModuleLenght=moduleth; + if (fModules[type] != NULL) + return; + ConstructCell(type); + + TString nm = "EcalModule"; + nm += type; + TString nm1; + TString cellname = "EcalCell"; + cellname += type; + Int_t i; + Int_t j; + Int_t n; + Float_t x; + Float_t y; + Float_t* buf = NULL; + Double_t thickness = fThicknessLead + fThicknessScin + fThicknessTyvk * 2; + Double_t moduleth = thickness * fNLayers; + Double_t par[3] = {fModuleSize / 2.0, fModuleSize / 2.0, moduleth / 2.0}; + if (fSteelTapes[0] == NULL) { + TGeoBBox* st1 = new TGeoBBox(fThicknessSteel / 2.0, fModuleSize / 2.0 - fThicknessSteel, moduleth / 2.0); + nm1 = "EcalModuleSteelTape1_"; // nm1+=type; + fSteelTapes[0] = new TGeoVolume(nm1.Data(), st1, gGeoManager->GetMedium("ECALSteel")); + } + if (fSteelTapes[1] == NULL) { + TGeoBBox* st2 = new TGeoBBox(fModuleSize / 2.0 - fThicknessSteel, fThicknessSteel / 2.0, moduleth / 2.0); + nm1 = "EcalModuleSteelTape2_"; // nm1+=type; + fSteelTapes[1] = new TGeoVolume(nm1.Data(), st2, gGeoManager->GetMedium("ECALSteel")); + } + + // TGeoVolume* modulev=new TGeoVolumeAssembly(nm); + TGeoVolume* modulev = gGeoManager->Volume(nm.Data(), "BOX", gGeoManager->GetMedium("ECALAir")->GetId(), par, 3); + modulev->SetLineColor(kYellow); + + // Adding cells into module + for (i = 0; i < type; i++) + for (j = 0; j < type; j++) { + x = (i - type / 2.0 + 0.5) * (fXCell[type] + 2.0 * fEdging); + y = (j - type / 2.0 + 0.5) * (fYCell[type] + 2.0 * fEdging); + n = i + j * type + 1; + gGeoManager->Node(cellname.Data(), n, nm.Data(), x, y, 0.0, 0, kTRUE, buf, 0); + } + nm1 = "EcalModuleSteelTape1_"; // nm1+=type; + gGeoManager->Node(nm1.Data(), 1, nm.Data(), -fThicknessSteel / 2.0 + fModuleSize / 2.0, 0.0, 0.0, 0, kTRUE, buf, 0); + gGeoManager->Node(nm1.Data(), 2, nm.Data(), +fThicknessSteel / 2.0 - fModuleSize / 2.0, 0.0, 0.0, 0, kTRUE, buf, 0); + nm1 = "EcalModuleSteelTape2_"; // nm1+=type; + gGeoManager->Node(nm1.Data(), 1, nm.Data(), 0.0, -fThicknessSteel / 2.0 + fModuleSize / 2.0, 0.0, 0, kTRUE, buf, 0); + gGeoManager->Node(nm1.Data(), 2, nm.Data(), 0.0, +fThicknessSteel / 2.0 - fModuleSize / 2.0, 0.0, 0, kTRUE, buf, 0); + fModuleLenght = moduleth; } // ------------------------------------------------------------------------- // ----- Private method ConstructModuleSimple----------------------------- void ecal::ConstructModuleSimple(Int_t type) { - if (fModules[type]!=NULL) return; - ConstructCellSimple(type); - - TString nm="EcalModule"; nm+=type; - TString nm1; - TString cellname="EcalCell"; cellname+=type; - Int_t i; - Int_t j; - Int_t n; - Float_t x; - Float_t y; - Float_t* buf=NULL; - Double_t thickness=fThicknessLead+fThicknessScin+fThicknessTyvk*2; - Double_t moduleth=thickness*fNLayers; - Double_t par[3]={fModuleSize/2.0, fModuleSize/2.0, moduleth/2.0}; - -// TGeoVolume* modulev=new TGeoVolumeAssembly(nm); - TGeoVolume* modulev=gGeoManager->Volume(nm.Data(), "BOX", gGeoManager->GetMedium("ECALAir")->GetId(), par, 3); - modulev->SetLineColor(kYellow); - - //Adding cells into module - for(i=0;iNode(cellname.Data(), n, nm.Data(), x, y, 0.0, 0, kTRUE, buf, 0); - } - fModuleLenght=moduleth; + if (fModules[type] != NULL) + return; + ConstructCellSimple(type); + + TString nm = "EcalModule"; + nm += type; + TString nm1; + TString cellname = "EcalCell"; + cellname += type; + Int_t i; + Int_t j; + Int_t n; + Float_t x; + Float_t y; + Float_t* buf = NULL; + Double_t thickness = fThicknessLead + fThicknessScin + fThicknessTyvk * 2; + Double_t moduleth = thickness * fNLayers; + Double_t par[3] = {fModuleSize / 2.0, fModuleSize / 2.0, moduleth / 2.0}; + + // TGeoVolume* modulev=new TGeoVolumeAssembly(nm); + TGeoVolume* modulev = gGeoManager->Volume(nm.Data(), "BOX", gGeoManager->GetMedium("ECALAir")->GetId(), par, 3); + modulev->SetLineColor(kYellow); + + // Adding cells into module + for (i = 0; i < type; i++) + for (j = 0; j < type; j++) { + x = (i - type / 2.0 + 0.5) * fModuleSize / type; + y = (j - type / 2.0 + 0.5) * fModuleSize / type; + n = i + j * type + 1; + gGeoManager->Node(cellname.Data(), n, nm.Data(), x, y, 0.0, 0, kTRUE, buf, 0); + } + fModuleLenght = moduleth; } // ------------------------------------------------------------------------- // ----- Private method ConstructCell ------------------------------------ void ecal::ConstructCell(Int_t type) { - if (fCells[type]!=NULL) return; - - ConstructTile(type, 0); - ConstructTile(type, 1); - if (fThicknessTyvk>0) ConstructTile(type, 2); - - Double_t thickness=fThicknessLead+fThicknessScin+fThicknessTyvk*2; - Int_t i; - TString nm="EcalCell"; nm+=type; - TString scin="ScTile"; scin+=type; scin+="_edging"; - TString lead="LeadTile"; lead+=type; - TString tyvek="TvTile"; tyvek+=type; - Double_t* buf=NULL; - Double_t moduleth=thickness*fNLayers; - Double_t par[3]={fXCell[type]/2.0+fEdging, fYCell[type]/2.0+fEdging, moduleth/2.0}; -// TGeoVolume* cellv=new TGeoVolumeAssembly(nm); - TGeoVolume* cellv=gGeoManager->Volume(nm.Data(),"BOX", gGeoManager->GetMedium("ECALAir")->GetId(), par, 3); - for(i=0;iNode(scin.Data(), i+1, nm.Data(), 0.0, 0.0, -thickness*fNLayers/2.0+fThicknessScin/2.0+i*thickness, 0, kTRUE, buf, 0); - gGeoManager->Node(lead.Data(), i+1, nm.Data(), 0.0, 0.0, -thickness*fNLayers/2.0+fThicknessScin+i*thickness+fThicknessTyvk+fThicknessLead/2.0, 0, kTRUE, buf, 0); - if (fThicknessTyvk>0.0) - { - gGeoManager->Node(tyvek.Data(), 2*i+1, nm.Data(), 0.0, 0.0, -thickness*fNLayers/2.0+fThicknessScin+i*thickness+1.5*fThicknessTyvk+fThicknessLead, 0, kTRUE, buf, 0); - gGeoManager->Node(tyvek.Data(), 2*i+2, nm.Data(), 0.0, 0.0, -thickness*fNLayers/2.0+fThicknessScin+i*thickness+0.5*fThicknessTyvk, 0, kTRUE, buf, 0); + if (fCells[type] != NULL) + return; + + ConstructTile(type, 0); + ConstructTile(type, 1); + if (fThicknessTyvk > 0) + ConstructTile(type, 2); + + Double_t thickness = fThicknessLead + fThicknessScin + fThicknessTyvk * 2; + Int_t i; + TString nm = "EcalCell"; + nm += type; + TString scin = "ScTile"; + scin += type; + scin += "_edging"; + TString lead = "LeadTile"; + lead += type; + TString tyvek = "TvTile"; + tyvek += type; + Double_t* buf = NULL; + Double_t moduleth = thickness * fNLayers; + Double_t par[3] = {fXCell[type] / 2.0 + fEdging, fYCell[type] / 2.0 + fEdging, moduleth / 2.0}; + // TGeoVolume* cellv=new TGeoVolumeAssembly(nm); + TGeoVolume* cellv = gGeoManager->Volume(nm.Data(), "BOX", gGeoManager->GetMedium("ECALAir")->GetId(), par, 3); + for (i = 0; i < fNLayers; i++) { + gGeoManager->Node(scin.Data(), + i + 1, + nm.Data(), + 0.0, + 0.0, + -thickness * fNLayers / 2.0 + fThicknessScin / 2.0 + i * thickness, + 0, + kTRUE, + buf, + 0); + gGeoManager->Node(lead.Data(), + i + 1, + nm.Data(), + 0.0, + 0.0, + -thickness * fNLayers / 2.0 + fThicknessScin + i * thickness + fThicknessTyvk + + fThicknessLead / 2.0, + 0, + kTRUE, + buf, + 0); + if (fThicknessTyvk > 0.0) { + gGeoManager->Node(tyvek.Data(), + 2 * i + 1, + nm.Data(), + 0.0, + 0.0, + -thickness * fNLayers / 2.0 + fThicknessScin + i * thickness + 1.5 * fThicknessTyvk + + fThicknessLead, + 0, + kTRUE, + buf, + 0); + gGeoManager->Node(tyvek.Data(), + 2 * i + 2, + nm.Data(), + 0.0, + 0.0, + -thickness * fNLayers / 2.0 + fThicknessScin + i * thickness + 0.5 * fThicknessTyvk, + 0, + kTRUE, + buf, + 0); + } } - } - fCells[type]=cellv; + fCells[type] = cellv; } // ------------------------------------------------------------------------- // ----- Private method ConstructCellSimple ------------------------------ void ecal::ConstructCellSimple(Int_t type) { - if (fCells[type]!=NULL) return; - - ConstructTileSimple(type, 0); - ConstructTileSimple(type, 1); - if (fThicknessTyvk>0) ConstructTileSimple(type, 2); - - Double_t thickness=fThicknessLead+fThicknessScin+fThicknessTyvk*2; - Int_t i; - TString nm="EcalCell"; nm+=type; - TString scin="ScTile"; scin+=type; - TString lead="LeadTile"; lead+=type; - TString tyvek="TvTile"; tyvek+=type; - Double_t* buf=NULL; - Double_t moduleth=thickness*fNLayers; - Double_t par[3]={fModuleSize/type/2.0, fModuleSize/type/2.0, moduleth/2.0}; -// TGeoVolume* cellv=new TGeoVolumeAssembly(nm); - TGeoVolume* cellv=gGeoManager->Volume(nm.Data(),"BOX", gGeoManager->GetMedium("ECALAir")->GetId(), par, 3); - for(i=0;iNode(scin.Data(), i+1, nm.Data(), 0.0, 0.0, -thickness*fNLayers/2.0+fThicknessScin/2.0+i*thickness, 0, kTRUE, buf, 0); - gGeoManager->Node(lead.Data(), i+1, nm.Data(), 0.0, 0.0, -thickness*fNLayers/2.0+fThicknessScin+i*thickness+fThicknessTyvk+fThicknessLead/2.0, 0, kTRUE, buf, 0); - if (fThicknessTyvk>0.0) - { - gGeoManager->Node(tyvek.Data(), 2*i+1, nm.Data(), 0.0, 0.0, -thickness*fNLayers/2.0+fThicknessScin+i*thickness+1.5*fThicknessTyvk+fThicknessLead, 0, kTRUE, buf, 0); - gGeoManager->Node(tyvek.Data(), 2*i+2, nm.Data(), 0.0, 0.0, -thickness*fNLayers/2.0+fThicknessScin+i*thickness+0.5*fThicknessTyvk, 0, kTRUE, buf, 0); + if (fCells[type] != NULL) + return; + + ConstructTileSimple(type, 0); + ConstructTileSimple(type, 1); + if (fThicknessTyvk > 0) + ConstructTileSimple(type, 2); + + Double_t thickness = fThicknessLead + fThicknessScin + fThicknessTyvk * 2; + Int_t i; + TString nm = "EcalCell"; + nm += type; + TString scin = "ScTile"; + scin += type; + TString lead = "LeadTile"; + lead += type; + TString tyvek = "TvTile"; + tyvek += type; + Double_t* buf = NULL; + Double_t moduleth = thickness * fNLayers; + Double_t par[3] = {fModuleSize / type / 2.0, fModuleSize / type / 2.0, moduleth / 2.0}; + // TGeoVolume* cellv=new TGeoVolumeAssembly(nm); + TGeoVolume* cellv = gGeoManager->Volume(nm.Data(), "BOX", gGeoManager->GetMedium("ECALAir")->GetId(), par, 3); + for (i = 0; i < fNLayers; i++) { + gGeoManager->Node(scin.Data(), + i + 1, + nm.Data(), + 0.0, + 0.0, + -thickness * fNLayers / 2.0 + fThicknessScin / 2.0 + i * thickness, + 0, + kTRUE, + buf, + 0); + gGeoManager->Node(lead.Data(), + i + 1, + nm.Data(), + 0.0, + 0.0, + -thickness * fNLayers / 2.0 + fThicknessScin + i * thickness + fThicknessTyvk + + fThicknessLead / 2.0, + 0, + kTRUE, + buf, + 0); + if (fThicknessTyvk > 0.0) { + gGeoManager->Node(tyvek.Data(), + 2 * i + 1, + nm.Data(), + 0.0, + 0.0, + -thickness * fNLayers / 2.0 + fThicknessScin + i * thickness + 1.5 * fThicknessTyvk + + fThicknessLead, + 0, + kTRUE, + buf, + 0); + gGeoManager->Node(tyvek.Data(), + 2 * i + 2, + nm.Data(), + 0.0, + 0.0, + -thickness * fNLayers / 2.0 + fThicknessScin + i * thickness + 0.5 * fThicknessTyvk, + 0, + kTRUE, + buf, + 0); + } } - } - fCells[type]=cellv; + fCells[type] = cellv; } // ------------------------------------------------------------------------- // ----- Private method InitMedium --------------------------------------- Int_t ecal::InitMedium(const char* name) { - static FairGeoLoader *geoLoad=FairGeoLoader::Instance(); - static FairGeoInterface *geoFace=geoLoad->getGeoInterface(); - static FairGeoMedia *media=geoFace->getMedia(); - static FairGeoBuilder *geoBuild=geoLoad->getGeoBuilder(); - - FairGeoMedium *CbmMedium=media->getMedium(name); - - if (!CbmMedium) - { - Fatal("InitMedium","Material %s not defined in media file.", name); - return -1111; - } - TGeoMedium* medium=gGeoManager->GetMedium(name); - if (medium!=NULL) - return CbmMedium->getMediumIndex(); - - return geoBuild->createMedium(CbmMedium); + static FairGeoLoader* geoLoad = FairGeoLoader::Instance(); + static FairGeoInterface* geoFace = geoLoad->getGeoInterface(); + static FairGeoMedia* media = geoFace->getMedia(); + static FairGeoBuilder* geoBuild = geoLoad->getGeoBuilder(); + + FairGeoMedium* CbmMedium = media->getMedium(name); + + if (!CbmMedium) { + Fatal("InitMedium", "Material %s not defined in media file.", name); + return -1111; + } + TGeoMedium* medium = gGeoManager->GetMedium(name); + if (medium != NULL) + return CbmMedium->getMediumIndex(); + + return geoBuild->createMedium(CbmMedium); } // ------------------------------------------------------------------------- // ----- Private method InitMedia ---------------------------------------- void ecal::InitMedia() { - Info("InitMedia", "Initializing media."); - InitMedium("SensVacuum"); - InitMedium("ECALVacuum"); - InitMedium("Lead"); - InitMedium("Scintillator"); - InitMedium("Tyvek"); - InitMedium("ECALAir"); - InitMedium("ECALFiber"); - InitMedium("ECALSteel"); - InitMedium("ECALTileEdging"); + Info("InitMedia", "Initializing media."); + InitMedium("SensVacuum"); + InitMedium("ECALVacuum"); + InitMedium("Lead"); + InitMedium("Scintillator"); + InitMedium("Tyvek"); + InitMedium("ECALAir"); + InitMedium("ECALFiber"); + InitMedium("ECALSteel"); + InitMedium("ECALTileEdging"); } // ------------------------------------------------------------------------- // ----- Private method ConstructTile ------------------------------------ void ecal::ConstructTile(Int_t type, Int_t material) { - switch (material) - { - case 0: if (fScTiles[type]!=NULL) return; break; - case 1: if (fPbTiles[type]!=NULL) return; break; - case 2: if (fTvTiles[type]!=NULL) return; break; - default: Error("ConstructTile", "Can't construct a tile of type %d.", material); - } - Double_t thickness; - TGeoVolume* hole; - TGeoVolume* fiber; - TGeoTranslation** tr; - TGeoTranslation* tm; - Int_t nh=fNH[type]; - Int_t i; - Int_t j; - TString nm; - TString nm1; - TString nm2; - TString medium; - Double_t x; - Double_t y; - TGeoBBox* tile; - TGeoVolume* tilev; - TGeoBBox* edging; - TGeoVolume* edgingv; - Double_t* buf=NULL; - - switch (material) - { - case 0: thickness=fThicknessScin/2.0; break; - case 1: thickness=fThicknessLead/2.0; break; - case 2: thickness=fThicknessTyvk/2.0; break; - default: Error("ConstructTile", "Can't construct a tile of type %d.", material); - } - - if (thickness<=0.0) return; - // Holes in the tiles - if (fHoleRad>0) - { - nm1="ECALHole_"; nm1+=material; - nm2="ECALFiber_"; nm2+=material; - if (fHoleVol[material]==NULL) - { - TGeoTube* holetube=new TGeoTube(0, fHoleRad, thickness); - fHoleVol[material]=new TGeoVolume(nm1.Data(), holetube, gGeoManager->GetMedium("ECALAir")); + switch (material) { + case 0: + if (fScTiles[type] != NULL) + return; + break; + case 1: + if (fPbTiles[type] != NULL) + return; + break; + case 2: + if (fTvTiles[type] != NULL) + return; + break; + default: + Error("ConstructTile", "Can't construct a tile of type %d.", material); } - hole=fHoleVol[material]; - // Fibers in holes - if (fFiberRad>0) - { - if (fFiberVol[material]==NULL) + Double_t thickness; + TGeoVolume* hole; + TGeoVolume* fiber; + TGeoTranslation** tr; + TGeoTranslation* tm; + Int_t nh = fNH[type]; + Int_t i; + Int_t j; + TString nm; + TString nm1; + TString nm2; + TString medium; + Double_t x; + Double_t y; + TGeoBBox* tile; + TGeoVolume* tilev; + TGeoBBox* edging; + TGeoVolume* edgingv; + Double_t* buf = NULL; + + switch (material) { + case 0: + thickness = fThicknessScin / 2.0; + break; + case 1: + thickness = fThicknessLead / 2.0; + break; + case 2: + thickness = fThicknessTyvk / 2.0; + break; + default: + Error("ConstructTile", "Can't construct a tile of type %d.", material); + } + + if (thickness <= 0.0) + return; + // Holes in the tiles + if (fHoleRad > 0) { + nm1 = "ECALHole_"; + nm1 += material; + nm2 = "ECALFiber_"; + nm2 += material; + if (fHoleVol[material] == NULL) { + TGeoTube* holetube = new TGeoTube(0, fHoleRad, thickness); + fHoleVol[material] = new TGeoVolume(nm1.Data(), holetube, gGeoManager->GetMedium("ECALAir")); + } + hole = fHoleVol[material]; + // Fibers in holes + if (fFiberRad > 0) { + if (fFiberVol[material] == NULL) { + TGeoTube* fibertube = new TGeoTube(0, fFiberRad, thickness); + fFiberVol[material] = new TGeoVolume(nm2.Data(), fibertube, gGeoManager->GetMedium("ECALFiber")); + gGeoManager->Node(nm2.Data(), 1, nm1.Data(), 0.0, 0.0, 0.0, 0, kTRUE, buf, 0); + } + fiber = fFiberVol[material]; + // TODO: Cerenkoff !!! + // AddSensitiveVolume(fiber); + } + } + /* + if (fHolePos[type]==NULL) { - TGeoTube* fibertube=new TGeoTube(0, fFiberRad, thickness); - fFiberVol[material]=new TGeoVolume(nm2.Data(), fibertube, gGeoManager->GetMedium("ECALFiber")); - gGeoManager->Node(nm2.Data(), 1, nm1.Data(), 0.0, 0.0, 0.0, 0, kTRUE, buf, 0); + tr=new TGeoTranslation*[nh*nh]; + for(i=0;iAddTransformation(tm); + tr[j*nh+i]=tm; + } + fHolePos[type]=tr; } - fiber=fFiberVol[material]; - // TODO: Cerenkoff !!! - //AddSensitiveVolume(fiber); + tr=fHolePos[type]; + */ + /** Building tile **/ + switch (material) { + case 0: + nm = "ScTile"; + medium = "Scintillator"; + break; + case 1: + nm = "LeadTile"; + medium = "Lead"; + break; + case 2: + nm = "TvTile"; + medium = "Tyvek"; + break; + default: + Error("ConstructTile", "Can't construct a tile of type %d.", material); } - } -/* - if (fHolePos[type]==NULL) - { - tr=new TGeoTranslation*[nh*nh]; - for(i=0;iAddTransformation(tm); - tr[j*nh+i]=tm; + nm += type; + if (material == 0) + tile = new TGeoBBox(fXCell[type] / 2.0, fYCell[type] / 2.0, thickness); + else + tile = new TGeoBBox(fXCell[type] / 2.0 + fEdging, fYCell[type] / 2.0 + fEdging, thickness); + tilev = new TGeoVolume(nm, tile, gGeoManager->GetMedium(medium)); + if (fHoleRad > 0) { + nm1 = "ECALHole_"; + nm1 += material; + for (i = 0; i < nh; i++) + for (j = 0; j < nh; j++) { + x = (i - nh / 2 + 0.5) * fXCell[type] / nh; + y = (j - nh / 2 + 0.5) * fYCell[type] / nh; + gGeoManager->Node(nm1.Data(), j * nh + i + 1, nm.Data(), x, y, 0.0, 0, kTRUE, buf, 0); + } + // clear fiber + if (nh % 2 == 0 && fCF[type] != 0) + gGeoManager->Node(nm1.Data(), j * nh + i + 1, nm.Data(), 0.0, 0.0, 0.0, 0, kTRUE, buf, 0); } - fHolePos[type]=tr; - } - tr=fHolePos[type]; -*/ - /** Building tile **/ - switch (material) - { - case 0: nm="ScTile"; medium="Scintillator"; break; - case 1: nm="LeadTile"; medium="Lead"; break; - case 2: nm="TvTile"; medium="Tyvek"; break; - default: Error("ConstructTile", "Can't construct a tile of type %d.", material); - } - - nm+=type; - if (material==0) - tile=new TGeoBBox(fXCell[type]/2.0, fYCell[type]/2.0, thickness); - else - tile=new TGeoBBox(fXCell[type]/2.0+fEdging, fYCell[type]/2.0+fEdging, thickness); - tilev=new TGeoVolume(nm, tile, gGeoManager->GetMedium(medium)); - if (fHoleRad>0) - { - nm1="ECALHole_"; nm1+=material; - for(i=0;iNode(nm1.Data(), j*nh+i+1, nm.Data(), x, y, 0.0, 0, kTRUE, buf, 0); + /* + if (fHoleRad>0) + { + for(i=0;iAddNode(hole, j*nh+i+1, tr[j*nh+i]); + // Clear Fiber + if (nh%2==0) + tilev->AddNode(hole, j*nh+i+1); + } + */ + /** Adding edging to scintillator **/ + if (material == 0) { + AddSensitiveVolume(tilev); + edging = new TGeoBBox(fXCell[type] / 2.0 + fEdging, fYCell[type] / 2.0 + fEdging, thickness); + + edgingv = new TGeoVolume(nm + "_edging", edging, gGeoManager->GetMedium("ECALTileEdging")); + edgingv->AddNode(tilev, 1); + fScTiles[cMaxModuleType - 1] = tilev; + fTileEdging[cMaxModuleType - 1] = edgingv; + } else { + if (material == 1) // Lead + fPbTiles[type] = tilev; + else + fTvTiles[type] = tilev; + return; } - // clear fiber - if (nh%2==0&&fCF[type]!=0) - gGeoManager->Node(nm1.Data(), j*nh+i+1, nm.Data(), 0.0, 0.0, 0.0, 0, kTRUE, buf, 0); - - } -/* - if (fHoleRad>0) - { - for(i=0;iAddNode(hole, j*nh+i+1, tr[j*nh+i]); - // Clear Fiber - if (nh%2==0) - tilev->AddNode(hole, j*nh+i+1); - } -*/ - /** Adding edging to scintillator **/ - if (material==0) - { - AddSensitiveVolume(tilev); - edging=new TGeoBBox(fXCell[type]/2.0+fEdging, fYCell[type]/2.0+fEdging, thickness); - - edgingv=new TGeoVolume(nm+"_edging", edging, gGeoManager->GetMedium("ECALTileEdging")); - edgingv->AddNode(tilev, 1); - fScTiles[cMaxModuleType-1]=tilev; - fTileEdging[cMaxModuleType-1]=edgingv; - } - else - { - if (material==1) //Lead - fPbTiles[type]=tilev; - else - fTvTiles[type]=tilev; - return; - } } // ------------------------------------------------------------------------- // ----- Private method ConstructTileSimple ------------------------------ void ecal::ConstructTileSimple(Int_t type, Int_t material) { - switch (material) - { - case 0: if (fScTiles[type]!=NULL) return; break; - case 1: if (fPbTiles[type]!=NULL) return; break; - case 2: if (fTvTiles[type]!=NULL) return; break; - default: Error("ConstructTileSimple", "Can't construct a tile of type %d.", material); - } - Double_t thickness; - TGeoVolume* hole; - TGeoVolume* fiber; - TGeoTranslation** tr; - TGeoTranslation* tm; - Int_t nh=fNH[type]; - Int_t i; - Int_t j; - TString nm; - TString nm1; - TString nm2; - TString medium; - Double_t x; - Double_t y; - TGeoBBox* tile; - TGeoVolume* tilev; - TGeoBBox* edging; - TGeoVolume* edgingv; - Double_t* buf=NULL; - - switch (material) - { - case 0: thickness=fThicknessScin/2.0; break; - case 1: thickness=fThicknessLead/2.0; break; - case 2: thickness=fThicknessTyvk/2.0; break; - default: Error("ConstructTile", "Can't construct a tile of type %d.", material); - } - - if (thickness<=0.0) return; - /** Building tile **/ - switch (material) - { - case 0: nm="ScTile"; medium="Scintillator"; break; - case 1: nm="LeadTile"; medium="Lead"; break; - case 2: nm="TvTile"; medium="Tyvek"; break; - default: Error("ConstructTile", "Can't construct a tile of type %d.", material); - } - - nm+=type; - tile=new TGeoBBox(fModuleSize/type/2.0, fModuleSize/type/2.0, thickness); - tilev=new TGeoVolume(nm, tile, gGeoManager->GetMedium(medium)); - /** Adding edging to scintillator **/ - if (material==0) - { - AddSensitiveVolume(tilev); - fScTiles[cMaxModuleType-1]=tilev; - fTileEdging[cMaxModuleType-1]=tilev; - } - else - { - if (material==1) //Lead - fPbTiles[type]=tilev; - else - fTvTiles[type]=tilev; - return; - } + switch (material) { + case 0: + if (fScTiles[type] != NULL) + return; + break; + case 1: + if (fPbTiles[type] != NULL) + return; + break; + case 2: + if (fTvTiles[type] != NULL) + return; + break; + default: + Error("ConstructTileSimple", "Can't construct a tile of type %d.", material); + } + Double_t thickness; + TGeoVolume* hole; + TGeoVolume* fiber; + TGeoTranslation** tr; + TGeoTranslation* tm; + Int_t nh = fNH[type]; + Int_t i; + Int_t j; + TString nm; + TString nm1; + TString nm2; + TString medium; + Double_t x; + Double_t y; + TGeoBBox* tile; + TGeoVolume* tilev; + TGeoBBox* edging; + TGeoVolume* edgingv; + Double_t* buf = NULL; + + switch (material) { + case 0: + thickness = fThicknessScin / 2.0; + break; + case 1: + thickness = fThicknessLead / 2.0; + break; + case 2: + thickness = fThicknessTyvk / 2.0; + break; + default: + Error("ConstructTile", "Can't construct a tile of type %d.", material); + } + + if (thickness <= 0.0) + return; + /** Building tile **/ + switch (material) { + case 0: + nm = "ScTile"; + medium = "Scintillator"; + break; + case 1: + nm = "LeadTile"; + medium = "Lead"; + break; + case 2: + nm = "TvTile"; + medium = "Tyvek"; + break; + default: + Error("ConstructTile", "Can't construct a tile of type %d.", material); + } + + nm += type; + tile = new TGeoBBox(fModuleSize / type / 2.0, fModuleSize / type / 2.0, thickness); + tilev = new TGeoVolume(nm, tile, gGeoManager->GetMedium(medium)); + /** Adding edging to scintillator **/ + if (material == 0) { + AddSensitiveVolume(tilev); + fScTiles[cMaxModuleType - 1] = tilev; + fTileEdging[cMaxModuleType - 1] = tilev; + } else { + if (material == 1) // Lead + fPbTiles[type] = tilev; + else + fTvTiles[type] = tilev; + return; + } } // ------------------------------------------------------------------------- // ----- Public method GetCellCoordInf ---------------------------------------- -Bool_t ecal::GetCellCoordInf(Int_t fVolID, Float_t &x, Float_t &y, Int_t& tenergy) +Bool_t ecal::GetCellCoordInf(Int_t fVolID, Float_t& x, Float_t& y, Int_t& tenergy) { - static ecalInf* inf=NULL; - if (inf==NULL) - { - inf=ecalInf::GetInstance(NULL); - if (inf==NULL) - { - cerr << "ecal::GetCellCoordInf(): Can't get geometry information." << endl; - return kFALSE; + static ecalInf* inf = NULL; + if (inf == NULL) { + inf = ecalInf::GetInstance(NULL); + if (inf == NULL) { + cerr << "ecal::GetCellCoordInf(): Can't get geometry information." << endl; + return kFALSE; + } } - } - Int_t volid=fVolID; - Int_t cell=volid%100-1; volid=volid-cell-1; volid/=100; - Int_t mx=volid%100; volid-=mx; volid/=100; - Int_t my=volid%100; volid-=my; volid/=100; - Int_t type=inf->GetType(mx, my); - Int_t cx=cell%type; - Int_t cy=cell/type; -// cout << "->" << mx << ", " << my << ", " << cell << endl; - static Float_t modulesize=inf->GetVariableStrict("modulesize"); - static Float_t xcalosize=inf->GetEcalSize(0); - static Float_t ycalosize=inf->GetEcalSize(1); - static Float_t dx=inf->GetVariableStrict("xpos"); - static Float_t dy=inf->GetVariableStrict("ypos"); - x=mx*modulesize-xcalosize/2.0+cx*modulesize/type+1.0; x+=dx; - y=my*modulesize-ycalosize/2.0+cy*modulesize/type+1.0; y+=dy; - tenergy=0; - -// cerr << fVolID << " --- " << x << ", " << y << endl; - return kFALSE; + Int_t volid = fVolID; + Int_t cell = volid % 100 - 1; + volid = volid - cell - 1; + volid /= 100; + Int_t mx = volid % 100; + volid -= mx; + volid /= 100; + Int_t my = volid % 100; + volid -= my; + volid /= 100; + Int_t type = inf->GetType(mx, my); + Int_t cx = cell % type; + Int_t cy = cell / type; + // cout << "->" << mx << ", " << my << ", " << cell << endl; + static Float_t modulesize = inf->GetVariableStrict("modulesize"); + static Float_t xcalosize = inf->GetEcalSize(0); + static Float_t ycalosize = inf->GetEcalSize(1); + static Float_t dx = inf->GetVariableStrict("xpos"); + static Float_t dy = inf->GetVariableStrict("ypos"); + x = mx * modulesize - xcalosize / 2.0 + cx * modulesize / type + 1.0; + x += dx; + y = my * modulesize - ycalosize / 2.0 + cy * modulesize / type + 1.0; + y += dy; + tenergy = 0; + + // cerr << fVolID << " --- " << x << ", " << y << endl; + return kFALSE; } // ------------------------------------------------------------------------------ -Bool_t ecal::GetCellCoord(Int_t fVolID, Float_t &x, Float_t &y, Int_t& tenergy) +Bool_t ecal::GetCellCoord(Int_t fVolID, Float_t& x, Float_t& y, Int_t& tenergy) { - return GetCellCoordInf(fVolID, x, y, tenergy); + return GetCellCoordInf(fVolID, x, y, tenergy); } -Bool_t ecal::GetCellCoordForPy(Int_t fVolID, TVector3 &all) +Bool_t ecal::GetCellCoordForPy(Int_t fVolID, TVector3& all) { - Float_t x,y; - Int_t tenergy; - Bool_t rc = GetCellCoordInf(fVolID, x, y, tenergy); - static ecalInf* inf=NULL; - if (inf==NULL) - { - inf=ecalInf::GetInstance(NULL); - if (inf==NULL) - { - cerr << "ecal::GetCellCoordInf(): Can't get geometry information." << endl; - return kFALSE; + Float_t x, y; + Int_t tenergy; + Bool_t rc = GetCellCoordInf(fVolID, x, y, tenergy); + static ecalInf* inf = NULL; + if (inf == NULL) { + inf = ecalInf::GetInstance(NULL); + if (inf == NULL) { + cerr << "ecal::GetCellCoordInf(): Can't get geometry information." << endl; + return kFALSE; + } } - } - all=TVector3(x,y,inf->GetZPos()); - return kTRUE; + all = TVector3(x, y, inf->GetZPos()); + return kTRUE; } diff --git a/ecal/ecal.h b/ecal/ecal.h index 8020415320..748e44642c 100644 --- a/ecal/ecal.h +++ b/ecal/ecal.h @@ -4,20 +4,16 @@ ** Defines the active detector ECAL with geometry coded here. **/ - #ifndef ECALDETAILED_H #define ECALDETAILED_H - -#include "ecalPoint.h" -#include "ecalStructure.h" -#include "ecalInf.h" - #include "FairDetector.h" - #include "TClonesArray.h" #include "TLorentzVector.h" #include "TVector3.h" +#include "ecalInf.h" +#include "ecalPoint.h" +#include "ecalStructure.h" #include @@ -27,241 +23,239 @@ class TGeoTranslation; class ecalLightMap; #define kNumberOfECALSensitiveVolumes 6 -const Int_t cMaxModuleType=5; +const Int_t cMaxModuleType = 5; class ecal : public FairDetector { -public: - - /** Default constructor **/ - ecal(); - - - /** Standard constructor. - *@param name detetcor name - *@param active sensitivity flag - **/ - ecal(const char* name, Bool_t active, - const char* fileGeo="ecal_Detailed.geo"); - - - /** Destructor **/ - virtual ~ecal(); - - - /** Virtual method ProcessHits - ** - ** Defines the action to be taken when a step is inside the - ** active volume. Creates ecal and adds them to the - ** collection. - *@param vol Pointer to the active volume - **/ - virtual Bool_t ProcessHits(FairVolume* vol = NULL); - - - /** Virtual method Construct geometry - ** - ** Constructs the ECAL geometry - **/ - virtual void ConstructGeometry(); - - virtual void EndOfEvent(); - virtual void BeginEvent(); - virtual void Reset(); - virtual void Print() const; - virtual void CopyClones(TClonesArray* cl1, TClonesArray* cl2, Int_t offset); - virtual void Register(); - virtual void ChangeHit(ecalPoint* oldHit=NULL); - virtual void FinishPrimary(); - - virtual void Initialize(); - - /** Accessor to the hit collection **/ - virtual TClonesArray* GetCollection(Int_t iColl) const; - virtual void SetSpecialPhysicsCuts(); - - /** Get cell coordinates according - ** to parameter container **/ - static Bool_t GetCellCoord(Int_t fVolumeID, Float_t &x, Float_t &y, Int_t& tenergy); - /** Get cell coordinates according - ** to current ecalInf **/ - static Bool_t GetCellCoordInf(Int_t fVolumeID, Float_t &x, Float_t &y, Int_t& tenergy); - // Get cell for python - static Bool_t GetCellCoordForPy(Int_t fVolID, TVector3 &all); -protected: - ecalPoint* AddHit(Int_t trackID, Int_t detID, TVector3 pos, - TVector3 mom, Double_t time, Double_t length, - Double_t eLoss, Int_t pdgcode); - ecalPoint* AddLiteHit(Int_t trackID, Int_t detID, Double32_t time, Double32_t eLoss); - -private: - Bool_t FillLitePoint(Int_t volnum); - void FillWallPoint(); - /** Private method ResetParameters - ** - ** Resets the private members for the track parameters - **/ - void ResetParameters(); - void SetEcalCuts(Int_t medium); - ecalPoint* FindHit(Int_t VolId, Int_t TrackId); - -private: - ecalInf* fInf; //! - Option_t* fDebug; //! - - /** returns type of volume **/ - Int_t GetVolType(Int_t volnum); - /** Track information to be stored until the track leaves the - active volume. **/ - /** track index **/ - Int_t fTrackID; //! - /** volume id **/ - Int_t fVolumeID; //! - /** position **/ - TLorentzVector fPos; //! - /** momentum **/ - TLorentzVector fMom; //! - /** time **/ - Double32_t fTime; //! - /** length **/ - Double32_t fLength; //! - /** energy loss **/ - Double32_t fELoss; //! - /** **/ - Int_t fPosIndex; //! - - /** MC point collection on ECAL wall **/ - TClonesArray* fEcalCollection; //! - /** MC point collection inside ECAL **/ - TClonesArray* fLiteCollection; //! - /** ECAL geometry parameters **/ - /** x,y,z size of outer ECAL box [cm] **/ - Float_t fEcalSize[3]; //! - /** Use simple geometry. - ** Try to be as compatible to ecal in physics as possible **/ - Int_t fSimpleGeo; //! - /** Size of the ECAL in modules **/ - Int_t fXSize; //! - Int_t fYSize; //! - /** Position of calorimeter center **/ - Float_t fDX; //! - Float_t fDY; //! - /** Size of calorimeter module [cm] **/ - Float_t fModuleSize; //! - /** Z-position of ECAL from the target [cm] **/ - Float_t fZEcal; //! - /** Semiaxises of keeping volume for ecal **/ - Float_t fSemiX; - Float_t fSemiY; - /** thickness of one lead layer [cm] **/ - Float_t fThicknessLead; //! - /** thickness of one scintillator layer [cm] **/ - Float_t fThicknessScin; //! - /** thickness of one tyvek layer [cm] **/ - Float_t fThicknessTyvk; //! - /** total thickness of one layer [cm] **/ - Float_t fThicknessLayer; //! - /** total thickness of steel layer [cm] **/ - Float_t fThicknessSteel; //! - /** Thickness of tile edging [cm] **/ - Float_t fEdging; //! - /** Radius of holes in the calorimeter [cm] **/ - Float_t fHoleRad; //! - /** Radius of fibers in calorimeter [cm] **/ - Float_t fFiberRad; //! - /** XY Size of cell **/ - Float_t fXCell[cMaxModuleType]; //! - Float_t fYCell[cMaxModuleType]; //! - /** Number of holes in modules **/ - Int_t fNH[cMaxModuleType]; //! - Int_t fCF[cMaxModuleType]; //! - /** Names of light maps **/ - TString fLightMapNames[cMaxModuleType]; //! - /** Light maps **/ - ecalLightMap* fLightMaps[cMaxModuleType]; //! - /** number of layers per cell **/ - Int_t fNLayers; //! - /** Lenght of calorimeter module **/ - Float_t fModuleLenght; //! - /** scall factor for fCellSize and fThicknessLayer **/ - Float_t fGeoScale; //! - /** Number of columns in ECAL1 **/ - Int_t fNColumns1; //! - /** Number of rows in ECAL1 **/ - Int_t fNRows1; //! - /** Number of columns in ECAL2 **/ - Int_t fNColumns2; //! - /** Number of rows in ECAL2 **/ - Int_t fNRows2; //! - /** max number of columns in ECAL1 or ECAL2 **/ - Int_t fNColumns; //! - /** max number of rows in ECAL1 or ECAL2 **/ - Int_t fNRows; //! - /** Max number of ECAL cells **/ - Int_t fVolIdMax; //! - /** Number of first hit for current primary **/ - Int_t fFirstNumber; //! - /** Map of volumes in ECAL - ** fVolArr[0]==code of sensivite wall - ** fVolArr[1]==code of PS Lead - ** fVolArr[2]==code of PS Scin - ** fVolArr[4]==code of Lead - ** fVolArr[3]==code of Tyveec - ** fVolArr[5]==code of scintillator - **/ - Int_t fVolArr[kNumberOfECALSensitiveVolumes]; //! - - /** Construct a raw of modules **/ - TGeoVolume* ConstructRaw(Int_t number); - /** Construct a module with given type **/ - void ConstructModule(Int_t type); - /** Construct a cell with given type **/ - void ConstructCell(Int_t type); - /** Construct a tile with given type **/ - void ConstructTile(Int_t type, Int_t material); - /** Next method for simplified geometry **/ - /** Construct a module with given type **/ - void ConstructModuleSimple(Int_t type); - /** Construct a cell with given type **/ - void ConstructCellSimple(Int_t type); - /** Construct a tile with given type **/ - void ConstructTileSimple(Int_t type, Int_t material); - TGeoVolume* fModules[cMaxModuleType]; //! Calorimeter Modules - TGeoVolume* fCells[cMaxModuleType]; //! Calorimeter Cells - TGeoVolume* fScTiles[cMaxModuleType]; //! Pb tiles - TGeoVolume* fTileEdging[cMaxModuleType]; //! Edging of scintillator tiles - TGeoVolume* fPbTiles[cMaxModuleType]; //! Scintillator tiles - TGeoVolume* fTvTiles[cMaxModuleType]; //! Tyvek sheets - TGeoVolume* fHoleVol[3]; //! Hole volume - TGeoVolume* fFiberVol[3]; //! Fiber volume - TGeoVolume* fSteelTapes[2]; //! Steel tapes - TGeoTranslation** fHolePos[cMaxModuleType]; //! Positions of holes - Int_t fModulesWithType[cMaxModuleType]; //! Number of mudules with type - std::list > fRawNumber; //! List of constructed raws - - /** Volume ID of calorimeter structure **/ - Int_t fStructureId; //! - /** Initialize medium with given name **/ - Int_t InitMedium(const char* name); - /** Initialize all calorimter media **/ - void InitMedia(); - - ecal(const ecal&); - ecal& operator=(const ecal&); - - ClassDef(ecal,1) - + public: + /** Default constructor **/ + ecal(); + + /** Standard constructor. + *@param name detetcor name + *@param active sensitivity flag + **/ + ecal(const char* name, Bool_t active, const char* fileGeo = "ecal_Detailed.geo"); + + /** Destructor **/ + virtual ~ecal(); + + /** Virtual method ProcessHits + ** + ** Defines the action to be taken when a step is inside the + ** active volume. Creates ecal and adds them to the + ** collection. + *@param vol Pointer to the active volume + **/ + virtual Bool_t ProcessHits(FairVolume* vol = NULL); + + /** Virtual method Construct geometry + ** + ** Constructs the ECAL geometry + **/ + virtual void ConstructGeometry(); + + virtual void EndOfEvent(); + virtual void BeginEvent(); + virtual void Reset(); + virtual void Print() const; + virtual void CopyClones(TClonesArray* cl1, TClonesArray* cl2, Int_t offset); + virtual void Register(); + virtual void ChangeHit(ecalPoint* oldHit = NULL); + virtual void FinishPrimary(); + + virtual void Initialize(); + + /** Accessor to the hit collection **/ + virtual TClonesArray* GetCollection(Int_t iColl) const; + virtual void SetSpecialPhysicsCuts(); + + /** Get cell coordinates according + ** to parameter container **/ + static Bool_t GetCellCoord(Int_t fVolumeID, Float_t& x, Float_t& y, Int_t& tenergy); + /** Get cell coordinates according + ** to current ecalInf **/ + static Bool_t GetCellCoordInf(Int_t fVolumeID, Float_t& x, Float_t& y, Int_t& tenergy); + // Get cell for python + static Bool_t GetCellCoordForPy(Int_t fVolID, TVector3& all); + + protected: + ecalPoint* AddHit(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t time, + Double_t length, + Double_t eLoss, + Int_t pdgcode); + ecalPoint* AddLiteHit(Int_t trackID, Int_t detID, Double32_t time, Double32_t eLoss); + + private: + Bool_t FillLitePoint(Int_t volnum); + void FillWallPoint(); + /** Private method ResetParameters + ** + ** Resets the private members for the track parameters + **/ + void ResetParameters(); + void SetEcalCuts(Int_t medium); + ecalPoint* FindHit(Int_t VolId, Int_t TrackId); + + private: + ecalInf* fInf; //! + Option_t* fDebug; //! + + /** returns type of volume **/ + Int_t GetVolType(Int_t volnum); + /** Track information to be stored until the track leaves the + active volume. **/ + /** track index **/ + Int_t fTrackID; //! + /** volume id **/ + Int_t fVolumeID; //! + /** position **/ + TLorentzVector fPos; //! + /** momentum **/ + TLorentzVector fMom; //! + /** time **/ + Double32_t fTime; //! + /** length **/ + Double32_t fLength; //! + /** energy loss **/ + Double32_t fELoss; //! + /** **/ + Int_t fPosIndex; //! + + /** MC point collection on ECAL wall **/ + TClonesArray* fEcalCollection; //! + /** MC point collection inside ECAL **/ + TClonesArray* fLiteCollection; //! + /** ECAL geometry parameters **/ + /** x,y,z size of outer ECAL box [cm] **/ + Float_t fEcalSize[3]; //! + /** Use simple geometry. + ** Try to be as compatible to ecal in physics as possible **/ + Int_t fSimpleGeo; //! + /** Size of the ECAL in modules **/ + Int_t fXSize; //! + Int_t fYSize; //! + /** Position of calorimeter center **/ + Float_t fDX; //! + Float_t fDY; //! + /** Size of calorimeter module [cm] **/ + Float_t fModuleSize; //! + /** Z-position of ECAL from the target [cm] **/ + Float_t fZEcal; //! + /** Semiaxises of keeping volume for ecal **/ + Float_t fSemiX; + Float_t fSemiY; + /** thickness of one lead layer [cm] **/ + Float_t fThicknessLead; //! + /** thickness of one scintillator layer [cm] **/ + Float_t fThicknessScin; //! + /** thickness of one tyvek layer [cm] **/ + Float_t fThicknessTyvk; //! + /** total thickness of one layer [cm] **/ + Float_t fThicknessLayer; //! + /** total thickness of steel layer [cm] **/ + Float_t fThicknessSteel; //! + /** Thickness of tile edging [cm] **/ + Float_t fEdging; //! + /** Radius of holes in the calorimeter [cm] **/ + Float_t fHoleRad; //! + /** Radius of fibers in calorimeter [cm] **/ + Float_t fFiberRad; //! + /** XY Size of cell **/ + Float_t fXCell[cMaxModuleType]; //! + Float_t fYCell[cMaxModuleType]; //! + /** Number of holes in modules **/ + Int_t fNH[cMaxModuleType]; //! + Int_t fCF[cMaxModuleType]; //! + /** Names of light maps **/ + TString fLightMapNames[cMaxModuleType]; //! + /** Light maps **/ + ecalLightMap* fLightMaps[cMaxModuleType]; //! + /** number of layers per cell **/ + Int_t fNLayers; //! + /** Lenght of calorimeter module **/ + Float_t fModuleLenght; //! + /** scall factor for fCellSize and fThicknessLayer **/ + Float_t fGeoScale; //! + /** Number of columns in ECAL1 **/ + Int_t fNColumns1; //! + /** Number of rows in ECAL1 **/ + Int_t fNRows1; //! + /** Number of columns in ECAL2 **/ + Int_t fNColumns2; //! + /** Number of rows in ECAL2 **/ + Int_t fNRows2; //! + /** max number of columns in ECAL1 or ECAL2 **/ + Int_t fNColumns; //! + /** max number of rows in ECAL1 or ECAL2 **/ + Int_t fNRows; //! + /** Max number of ECAL cells **/ + Int_t fVolIdMax; //! + /** Number of first hit for current primary **/ + Int_t fFirstNumber; //! + /** Map of volumes in ECAL + ** fVolArr[0]==code of sensivite wall + ** fVolArr[1]==code of PS Lead + ** fVolArr[2]==code of PS Scin + ** fVolArr[4]==code of Lead + ** fVolArr[3]==code of Tyveec + ** fVolArr[5]==code of scintillator + **/ + Int_t fVolArr[kNumberOfECALSensitiveVolumes]; //! + + /** Construct a raw of modules **/ + TGeoVolume* ConstructRaw(Int_t number); + /** Construct a module with given type **/ + void ConstructModule(Int_t type); + /** Construct a cell with given type **/ + void ConstructCell(Int_t type); + /** Construct a tile with given type **/ + void ConstructTile(Int_t type, Int_t material); + /** Next method for simplified geometry **/ + /** Construct a module with given type **/ + void ConstructModuleSimple(Int_t type); + /** Construct a cell with given type **/ + void ConstructCellSimple(Int_t type); + /** Construct a tile with given type **/ + void ConstructTileSimple(Int_t type, Int_t material); + TGeoVolume* fModules[cMaxModuleType]; //! Calorimeter Modules + TGeoVolume* fCells[cMaxModuleType]; //! Calorimeter Cells + TGeoVolume* fScTiles[cMaxModuleType]; //! Pb tiles + TGeoVolume* fTileEdging[cMaxModuleType]; //! Edging of scintillator tiles + TGeoVolume* fPbTiles[cMaxModuleType]; //! Scintillator tiles + TGeoVolume* fTvTiles[cMaxModuleType]; //! Tyvek sheets + TGeoVolume* fHoleVol[3]; //! Hole volume + TGeoVolume* fFiberVol[3]; //! Fiber volume + TGeoVolume* fSteelTapes[2]; //! Steel tapes + TGeoTranslation** fHolePos[cMaxModuleType]; //! Positions of holes + Int_t fModulesWithType[cMaxModuleType]; //! Number of mudules with type + std::list> fRawNumber; //! List of constructed raws + + /** Volume ID of calorimeter structure **/ + Int_t fStructureId; //! + /** Initialize medium with given name **/ + Int_t InitMedium(const char* name); + /** Initialize all calorimter media **/ + void InitMedia(); + + ecal(const ecal&); + ecal& operator=(const ecal&); + + ClassDef(ecal, 1) }; inline void ecal::ResetParameters() { - fTrackID = fVolumeID = 0; - fPos.SetXYZM(0.0, 0.0, 0.0, 0.0); - fMom.SetXYZM(0.0, 0.0, 0.0, 0.0); - fTime = fLength = fELoss = 0; - fPosIndex = 0; + fTrackID = fVolumeID = 0; + fPos.SetXYZM(0.0, 0.0, 0.0, 0.0); + fMom.SetXYZM(0.0, 0.0, 0.0, 0.0); + fTime = fLength = fELoss = 0; + fPosIndex = 0; }; - #endif diff --git a/ecal/ecalAnalysisMaterial.cxx b/ecal/ecalAnalysisMaterial.cxx index 604cbeb397..2f404dfab3 100644 --- a/ecal/ecalAnalysisMaterial.cxx +++ b/ecal/ecalAnalysisMaterial.cxx @@ -1,141 +1,136 @@ #include "ecalAnalysisMaterial.h" +#include "FairRadLenPoint.h" #include "FairRootManager.h" #include "ShipMCTrack.h" -#include "FairRadLenPoint.h" - - -#include "TTree.h" #include "TClonesArray.h" #include "TLorentzVector.h" +#include "TTree.h" #include -using std::cout; using std::cerr; +using std::cout; using std::endl; using std::list; /** Loop procedure **/ void ecalAnalysisMaterial::Exec(Option_t* option) { - fEvent++; - if (fVerbose>0) - Info("Exec", "Event %d.", fEvent); - InitTree(); - ShipMCTrack* tr; - FairRadLenPoint* p; - Int_t i; - Int_t k; - Int_t n; - Double_t z=3535; - TVector3 newp; - TVector3 oldp(0.0, 0.0, 0.0); - TVector3 d; - if (fMC->GetEntriesFast()!=1) - { - cout << "Size of MC points arrays differs from one" << endl; - } - tr=(ShipMCTrack*)fMC->At(0); - fX=tr->GetPx(); - fY=tr->GetPy(); - fZ=tr->GetPz(); - fX*=z/fZ; - fY*=z/fZ; - fZ*=z/fZ; -// if (TMath::Abs(fX)>594||TMath::Abs(fY)>474) return; -// if (TMath::Abs(fX)<42&&TMath::Abs(fY)<42) return; - n=fRadLen->GetEntriesFast(); - fX0=0; fIntL=0; - for(i=0;i<400;i++) fX0z[i]=0; - for(i=0;iAt(i); - newp=p->GetPositionOut(); -// cout << d.Mag() << " " << p->GetRadLength() << " " << newp.Z() << " " << fX0 << endl; - if (newp.Z()>3535) break; - k=newp.Z()/10; - d=newp-oldp; -// cout << p->GetLength() << " " << p->GetRadLength() << " " << fEvent << " " <GetXOut() << " " << p->GetYOut() << " " << p->GetZOut() << endl; - fX0+=d.Mag()/p->GetRadLength(); - fX0z[k]+=d.Mag()/p->GetRadLength(); - oldp=newp; - } - fTree->Fill(); + fEvent++; + if (fVerbose > 0) + Info("Exec", "Event %d.", fEvent); + InitTree(); + ShipMCTrack* tr; + FairRadLenPoint* p; + Int_t i; + Int_t k; + Int_t n; + Double_t z = 3535; + TVector3 newp; + TVector3 oldp(0.0, 0.0, 0.0); + TVector3 d; + if (fMC->GetEntriesFast() != 1) { + cout << "Size of MC points arrays differs from one" << endl; + } + tr = (ShipMCTrack*)fMC->At(0); + fX = tr->GetPx(); + fY = tr->GetPy(); + fZ = tr->GetPz(); + fX *= z / fZ; + fY *= z / fZ; + fZ *= z / fZ; + // if (TMath::Abs(fX)>594||TMath::Abs(fY)>474) return; + // if (TMath::Abs(fX)<42&&TMath::Abs(fY)<42) return; + n = fRadLen->GetEntriesFast(); + fX0 = 0; + fIntL = 0; + for (i = 0; i < 400; i++) + fX0z[i] = 0; + for (i = 0; i < n; i++) { + p = (FairRadLenPoint*)fRadLen->At(i); + newp = p->GetPositionOut(); + // cout << d.Mag() << " " << p->GetRadLength() << " " << newp.Z() << " " << fX0 << endl; + if (newp.Z() > 3535) + break; + k = newp.Z() / 10; + d = newp - oldp; + // cout << p->GetLength() << " " << p->GetRadLength() << " " << fEvent << " " <GetXOut() + // << " " << p->GetYOut() << " " << p->GetZOut() << endl; + fX0 += d.Mag() / p->GetRadLength(); + fX0z[k] += d.Mag() / p->GetRadLength(); + oldp = newp; + } + fTree->Fill(); } - /** Initializes tree **/ void ecalAnalysisMaterial::InitTree() { - if (fTree) return; - fTree=new TTree("rad","Radiation lenght tree"); - fTree->Branch("ev", &fEvent, "ev/I"); - fTree->Branch("x", &fX, "x/D"); - fTree->Branch("y", &fY, "Y/D"); - fTree->Branch("z", &fZ, "z/D"); - fTree->Branch("x0", &fX0, "x0/D"); - fTree->Branch("x0z", &fX0z, "x0z[400]/D"); - fTree->Branch("intl", &fIntL, "intl/D"); + if (fTree) + return; + fTree = new TTree("rad", "Radiation lenght tree"); + fTree->Branch("ev", &fEvent, "ev/I"); + fTree->Branch("x", &fX, "x/D"); + fTree->Branch("y", &fY, "Y/D"); + fTree->Branch("z", &fZ, "z/D"); + fTree->Branch("x0", &fX0, "x0/D"); + fTree->Branch("x0z", &fX0z, "x0z[400]/D"); + fTree->Branch("intl", &fIntL, "intl/D"); } ecalAnalysisMaterial::ecalAnalysisMaterial() - : FairTask(), - fTree(NULL), - fEvent(0), - fX(0.), - fY(0.), - fZ(0.), - fX0(0.), - fIntL(0.), - fMC(NULL), - fRadLen(NULL) -{ -} + : FairTask() + , fTree(NULL) + , fEvent(0) + , fX(0.) + , fY(0.) + , fZ(0.) + , fX0(0.) + , fIntL(0.) + , fMC(NULL) + , fRadLen(NULL) +{} ecalAnalysisMaterial::ecalAnalysisMaterial(const char* name, const Int_t iVerbose) - : FairTask(name, iVerbose), - fTree(NULL), - fEvent(0), - fX(0.), - fY(0.), - fZ(0.), - fX0(0.), - fIntL(0.), - fMC(NULL), - fRadLen(NULL) -{ -} + : FairTask(name, iVerbose) + , fTree(NULL) + , fEvent(0) + , fX(0.) + , fY(0.) + , fZ(0.) + , fX0(0.) + , fIntL(0.) + , fMC(NULL) + , fRadLen(NULL) +{} /** Initing routine **/ InitStatus ecalAnalysisMaterial::Init() { - FairRootManager* fManager=FairRootManager::Instance(); - if (!fManager) - { - Fatal("Init", "Can't find a Root Manager."); - return kFATAL; - } - fMC=(TClonesArray*)fManager->GetObject("MCTrack"); - if (!fMC) - { - Fatal("Init", "Can't find an array of MC tracks."); - return kFATAL; - } - fRadLen=(TClonesArray*)fManager->GetObject("RadLen"); - if (!fRadLen) - { - Fatal("Init", "Can't find an array of radiation length points."); - return kFATAL; - } - fTree=NULL; + FairRootManager* fManager = FairRootManager::Instance(); + if (!fManager) { + Fatal("Init", "Can't find a Root Manager."); + return kFATAL; + } + fMC = (TClonesArray*)fManager->GetObject("MCTrack"); + if (!fMC) { + Fatal("Init", "Can't find an array of MC tracks."); + return kFATAL; + } + fRadLen = (TClonesArray*)fManager->GetObject("RadLen"); + if (!fRadLen) { + Fatal("Init", "Can't find an array of radiation length points."); + return kFATAL; + } + fTree = NULL; - return kSUCCESS; + return kSUCCESS; } /** Finishing routine **/ void ecalAnalysisMaterial::Finish() { - if (fTree) - fTree->Write(); + if (fTree) + fTree->Write(); } diff --git a/ecal/ecalAnalysisMaterial.h b/ecal/ecalAnalysisMaterial.h index 3c7a1144dc..072b87d766 100644 --- a/ecal/ecalAnalysisMaterial.h +++ b/ecal/ecalAnalysisMaterial.h @@ -2,7 +2,6 @@ #define ECALANALYSISMATERIAL_H #include "FairTask.h" - #include "TString.h" #include @@ -10,52 +9,52 @@ class TTree; class TClonesArray; - class ecalAnalysisMaterial : public FairTask { -public: - ecalAnalysisMaterial(const char* name, const Int_t iVerbose=0); -public: - /** Default constructor **/ - ecalAnalysisMaterial(); - - /** Initing routine **/ - virtual InitStatus Init(); - - /** Loop procedure **/ - virtual void Exec(Option_t* option); - - /** Finishing routine **/ - virtual void Finish(); - - /** Destructor **/ - virtual ~ecalAnalysisMaterial() {}; -private: - /** Initialize a tree **/ - void InitTree(); - /** Out tree **/ - TTree* fTree; //! - - /** Event number **/ - Int_t fEvent; - /** Information particle **/ - Double_t fX; - Double_t fY; - Double_t fZ; - Double_t fX0; - Double_t fX0z[400]; - Double_t fIntL; - - - /** MC tracks array **/ - TClonesArray* fMC; //! - /** Array of radlen points**/ - TClonesArray* fRadLen; //! - - ecalAnalysisMaterial(const ecalAnalysisMaterial&); - ecalAnalysisMaterial& operator=(const ecalAnalysisMaterial&); - - ClassDef(ecalAnalysisMaterial,1) + public: + ecalAnalysisMaterial(const char* name, const Int_t iVerbose = 0); + + public: + /** Default constructor **/ + ecalAnalysisMaterial(); + + /** Initing routine **/ + virtual InitStatus Init(); + + /** Loop procedure **/ + virtual void Exec(Option_t* option); + + /** Finishing routine **/ + virtual void Finish(); + + /** Destructor **/ + virtual ~ecalAnalysisMaterial() {}; + + private: + /** Initialize a tree **/ + void InitTree(); + /** Out tree **/ + TTree* fTree; //! + + /** Event number **/ + Int_t fEvent; + /** Information particle **/ + Double_t fX; + Double_t fY; + Double_t fZ; + Double_t fX0; + Double_t fX0z[400]; + Double_t fIntL; + + /** MC tracks array **/ + TClonesArray* fMC; //! + /** Array of radlen points**/ + TClonesArray* fRadLen; //! + + ecalAnalysisMaterial(const ecalAnalysisMaterial&); + ecalAnalysisMaterial& operator=(const ecalAnalysisMaterial&); + + ClassDef(ecalAnalysisMaterial, 1) }; #endif diff --git a/ecal/ecalAnalysisSimple.cxx b/ecal/ecalAnalysisSimple.cxx index a0350f6269..e361cb6b5b 100644 --- a/ecal/ecalAnalysisSimple.cxx +++ b/ecal/ecalAnalysisSimple.cxx @@ -1,16 +1,14 @@ #include "ecalAnalysisSimple.h" #include "FairRootManager.h" - -#include "ecalStructure.h" +#include "TClonesArray.h" +#include "TTree.h" #include "ecalCell.h" #include "ecalPoint.h" +#include "ecalStructure.h" -#include "TTree.h" -#include "TClonesArray.h" - -#include #include +#include #include using namespace std; @@ -18,143 +16,140 @@ using namespace std; /** Loop procedure **/ void ecalAnalysisSimple::Exec(Option_t* option) { - Int_t n=fTracks->GetEntries(); - Int_t i; - ecalPoint* t; - ecalCell* cell; - ecalCell* mcell; - TVector3 m; - list cells; - list::const_iterator p; -// TVector3 m1; - - fEv++; - InitTree(); - - for(i=0;iAt(i); - fX=t->GetX(); - fY=t->GetY(); - t->Momentum(m); - fP=m.Mag(); - fPX=m.Px(); - fPY=m.Py(); - fPZ=m.Pz(); - -// m1=m.Unit(); - cell=fStr->GetCell(fX, fY); - if (!cell) continue; - mcell=cell; - cell->GetNeighborsList(cells); - for(p=cells.begin();p!=cells.end();++p) - if ((*p)->GetEnergy()>mcell->GetEnergy()) - mcell=(*p); - - mcell->GetNeighborsList(cells); - for(p=cells.begin();p!=cells.end();++p) - if ((*p)->GetEnergy()>mcell->GetEnergy()) - break; - - if (p!=cells.end()) continue; - - fCX=mcell->GetCenterX(); - fCY=mcell->GetCenterY(); - fCE=mcell->GetEnergy(); - fCellNum=mcell->GetCellNumber(); - fADC=mcell->ADC(); - fOE=fCE; - for(p=cells.begin();p!=cells.end();++p) - fOE+=(*p)->GetEnergy(); - - fTree->Fill(); - } - + Int_t n = fTracks->GetEntries(); + Int_t i; + ecalPoint* t; + ecalCell* cell; + ecalCell* mcell; + TVector3 m; + list cells; + list::const_iterator p; + // TVector3 m1; + + fEv++; + InitTree(); + + for (i = 0; i < n; i++) { + t = (ecalPoint*)fTracks->At(i); + fX = t->GetX(); + fY = t->GetY(); + t->Momentum(m); + fP = m.Mag(); + fPX = m.Px(); + fPY = m.Py(); + fPZ = m.Pz(); + + // m1=m.Unit(); + cell = fStr->GetCell(fX, fY); + if (!cell) + continue; + mcell = cell; + cell->GetNeighborsList(cells); + for (p = cells.begin(); p != cells.end(); ++p) + if ((*p)->GetEnergy() > mcell->GetEnergy()) + mcell = (*p); + + mcell->GetNeighborsList(cells); + for (p = cells.begin(); p != cells.end(); ++p) + if ((*p)->GetEnergy() > mcell->GetEnergy()) + break; + + if (p != cells.end()) + continue; + + fCX = mcell->GetCenterX(); + fCY = mcell->GetCenterY(); + fCE = mcell->GetEnergy(); + fCellNum = mcell->GetCellNumber(); + fADC = mcell->ADC(); + fOE = fCE; + for (p = cells.begin(); p != cells.end(); ++p) + fOE += (*p)->GetEnergy(); + + fTree->Fill(); + } } void ecalAnalysisSimple::InitTree() { - if (fTree) return; - fTree=new TTree("calib", "calib"); - fTree->Branch("px", &fPX, "px/D"); - fTree->Branch("py", &fPY, "py/D"); - fTree->Branch("pz", &fPZ, "pz/D"); - fTree->Branch("p" , &fP , "p/D"); - fTree->Branch("x" , &fX , "x/D"); - fTree->Branch("y" , &fY , "y/D"); - fTree->Branch("cx", &fCX, "cx/D"); - fTree->Branch("cy", &fCY, "cy/D"); - fTree->Branch("ce", &fCE, "ce/D"); - fTree->Branch("oe", &fOE, "oe/D"); - fTree->Branch("ev", &fEv, "ev/I"); - fTree->Branch("cn", &fCellNum, "cn/I"); - fTree->Branch("adc", &fADC, "adc/I"); + if (fTree) + return; + fTree = new TTree("calib", "calib"); + fTree->Branch("px", &fPX, "px/D"); + fTree->Branch("py", &fPY, "py/D"); + fTree->Branch("pz", &fPZ, "pz/D"); + fTree->Branch("p", &fP, "p/D"); + fTree->Branch("x", &fX, "x/D"); + fTree->Branch("y", &fY, "y/D"); + fTree->Branch("cx", &fCX, "cx/D"); + fTree->Branch("cy", &fCY, "cy/D"); + fTree->Branch("ce", &fCE, "ce/D"); + fTree->Branch("oe", &fOE, "oe/D"); + fTree->Branch("ev", &fEv, "ev/I"); + fTree->Branch("cn", &fCellNum, "cn/I"); + fTree->Branch("adc", &fADC, "adc/I"); } ecalAnalysisSimple::ecalAnalysisSimple(const char* name, const Int_t iVerbose) - : FairTask(name, iVerbose), - fTree(NULL), - fX(0.), - fY(0.), - fCX(0.), - fCY(0.), - fP(0.), - fCE(0.), - fOE(0.), - fPX(0.), - fPY(0.), - fPZ(0.), - fEv(0), - fCellNum(0), - fADC(0), - fStr(NULL), - fTracks(NULL) -{ -} + : FairTask(name, iVerbose) + , fTree(NULL) + , fX(0.) + , fY(0.) + , fCX(0.) + , fCY(0.) + , fP(0.) + , fCE(0.) + , fOE(0.) + , fPX(0.) + , fPY(0.) + , fPZ(0.) + , fEv(0) + , fCellNum(0) + , fADC(0) + , fStr(NULL) + , fTracks(NULL) +{} ecalAnalysisSimple::ecalAnalysisSimple() - : FairTask(), - fTree(NULL), - fX(0.), - fY(0.), - fCX(0.), - fCY(0.), - fP(0.), - fCE(0.), - fOE(0.), - fPX(0.), - fPY(0.), - fPZ(0.), - fEv(0), - fCellNum(0), - fADC(0), - fStr(NULL), - fTracks(NULL) -{ -} + : FairTask() + , fTree(NULL) + , fX(0.) + , fY(0.) + , fCX(0.) + , fCY(0.) + , fP(0.) + , fCE(0.) + , fOE(0.) + , fPX(0.) + , fPY(0.) + , fPZ(0.) + , fEv(0) + , fCellNum(0) + , fADC(0) + , fStr(NULL) + , fTracks(NULL) +{} /** Initing routine **/ InitStatus ecalAnalysisSimple::Init() { - FairRootManager* fManager=FairRootManager::Instance(); - fStr=(ecalStructure*)fManager->GetObject("EcalStructure"); - if (!fStr) - { - Fatal("Init()", "Can't find calorimeter structure. "); - return kFATAL; - } - fTracks=(TClonesArray*)fManager->GetObject("EcalPoint"); - if (!fTracks) - { - Fatal("Init()", "Can't find array of reconstructed tracks. "); - return kFATAL; - } - return kSUCCESS; + FairRootManager* fManager = FairRootManager::Instance(); + fStr = (ecalStructure*)fManager->GetObject("EcalStructure"); + if (!fStr) { + Fatal("Init()", "Can't find calorimeter structure. "); + return kFATAL; + } + fTracks = (TClonesArray*)fManager->GetObject("EcalPoint"); + if (!fTracks) { + Fatal("Init()", "Can't find array of reconstructed tracks. "); + return kFATAL; + } + return kSUCCESS; } /** Finishing routine **/ void ecalAnalysisSimple::Finish() { - if (fTree) - fTree->Write(); + if (fTree) + fTree->Write(); } diff --git a/ecal/ecalAnalysisSimple.h b/ecal/ecalAnalysisSimple.h index df8cc0d695..552511537b 100644 --- a/ecal/ecalAnalysisSimple.h +++ b/ecal/ecalAnalysisSimple.h @@ -2,7 +2,6 @@ #define ECALANALYSISCALIB_H #include "FairTask.h" - #include "TString.h" #include @@ -13,47 +12,47 @@ class TClonesArray; class ecalAnalysisSimple : public FairTask { -public: - ecalAnalysisSimple(const char* name, const Int_t iVerbose); - - /** Default constructor **/ - ecalAnalysisSimple(); - - /** Initing routine **/ - virtual InitStatus Init(); - - /** Loop procedure **/ - virtual void Exec(Option_t* option); - - /** Finishing routine **/ - virtual void Finish(); - - /** Destructor **/ - virtual ~ecalAnalysisSimple() {}; - -private: - TTree* fTree; - Double_t fX; - Double_t fY; - Double_t fCX; - Double_t fCY; - Double_t fP; - Double_t fCE; - Double_t fOE; - Double_t fPX; - Double_t fPY; - Double_t fPZ; - Int_t fEv; - Int_t fCellNum; - Int_t fADC; - void InitTree(); - ecalStructure* fStr; - TClonesArray* fTracks; - - ecalAnalysisSimple(const ecalAnalysisSimple&); - ecalAnalysisSimple operator=(const ecalAnalysisSimple&); - - ClassDef(ecalAnalysisSimple,1) + public: + ecalAnalysisSimple(const char* name, const Int_t iVerbose); + + /** Default constructor **/ + ecalAnalysisSimple(); + + /** Initing routine **/ + virtual InitStatus Init(); + + /** Loop procedure **/ + virtual void Exec(Option_t* option); + + /** Finishing routine **/ + virtual void Finish(); + + /** Destructor **/ + virtual ~ecalAnalysisSimple() {}; + + private: + TTree* fTree; + Double_t fX; + Double_t fY; + Double_t fCX; + Double_t fCY; + Double_t fP; + Double_t fCE; + Double_t fOE; + Double_t fPX; + Double_t fPY; + Double_t fPZ; + Int_t fEv; + Int_t fCellNum; + Int_t fADC; + void InitTree(); + ecalStructure* fStr; + TClonesArray* fTracks; + + ecalAnalysisSimple(const ecalAnalysisSimple&); + ecalAnalysisSimple operator=(const ecalAnalysisSimple&); + + ClassDef(ecalAnalysisSimple, 1) }; #endif diff --git a/ecal/ecalCell.cxx b/ecal/ecalCell.cxx index b6af8d2d68..9da1751004 100644 --- a/ecal/ecalCell.cxx +++ b/ecal/ecalCell.cxx @@ -11,49 +11,46 @@ using std::cout; using std::endl; -using std::map; using std::list; +using std::map; //----------------------------------------------------------------------------- Int_t ecalCell::CountNeighbors(const std::list& lst) const { - Int_t c=0; - list::const_iterator p=lst.begin(); - for(;p!=lst.end();++p) - if (find(fNeighbors.begin(), fNeighbors.end(), *p)!=fNeighbors.end()) - ++c; + Int_t c = 0; + list::const_iterator p = lst.begin(); + for (; p != lst.end(); ++p) + if (find(fNeighbors.begin(), fNeighbors.end(), *p) != fNeighbors.end()) + ++c; - return c; + return c; } //----------------------------------------------------------------------------- void ecalCell::GetClusterEnergy(Float_t& EcalEnergy) { - EcalEnergy=-1; - EcalEnergy=GetEnergy(); - list::const_iterator p; - for(p=fNeighbors.begin();p!=fNeighbors.end();++p) - { - EcalEnergy+=(*p)->GetEnergy(); - } + EcalEnergy = -1; + EcalEnergy = GetEnergy(); + list::const_iterator p; + for (p = fNeighbors.begin(); p != fNeighbors.end(); ++p) { + EcalEnergy += (*p)->GetEnergy(); + } } //----------------------------------------------------------------------------- // Get list of 8 neighbors void ecalCell::Create5x5Cluster() { - list c3; - list c; - list::const_iterator p; - list::const_iterator p2; - - GetNeighborsList(c3); - for(p=c3.begin();p!=c3.end();++p) - { - (*p)->GetNeighborsList(c); - for(p2=c.begin();p2!=c.end();++p2) - if (find(f5x5Cluster.begin(), f5x5Cluster.end(), *p2)==f5x5Cluster.end()) - f5x5Cluster.push_back(*p2); - } + list c3; + list c; + list::const_iterator p; + list::const_iterator p2; + + GetNeighborsList(c3); + for (p = c3.begin(); p != c3.end(); ++p) { + (*p)->GetNeighborsList(c); + for (p2 = c.begin(); p2 != c.end(); ++p2) + if (find(f5x5Cluster.begin(), f5x5Cluster.end(), *p2) == f5x5Cluster.end()) + f5x5Cluster.push_back(*p2); + } } - diff --git a/ecal/ecalCell.h b/ecal/ecalCell.h index bfeb157840..c6fe9e6694 100644 --- a/ecal/ecalCell.h +++ b/ecal/ecalCell.h @@ -9,108 +9,123 @@ #include "TObject.h" +#include #include #include -#include class ecalCell : public TObject { -public: - ecalCell(Int_t cellnumber, Float_t x1=0, Float_t y1=0, Float_t x2=0, Float_t y2=0, Char_t type=0, Float_t energy=0) - : TObject(), fNumber(cellnumber), fX1(x1), fY1(y1), fX2(x2), - fY2(y2), fType(type), fEnergy(energy), fADC(-1111), fNeighbors(), f5x5Cluster(),fTime(-1111) - {}; - - inline Bool_t IsInside(Float_t x, Float_t y) {return x>GetX1()&&xGetY1()&&y &neib) const - { - neib=fNeighbors; - } - inline void SetNeighborsList(std::list &neib) - { - fNeighbors=neib; - } - - // 5x5 cluster stuff - inline void Get5x5Cluster(std::list& cls) - { - if (f5x5Cluster.size()==0) Create5x5Cluster(); - cls=f5x5Cluster; - } - - inline void SetEnergy(Float_t energy) {fEnergy=energy;} - inline void SetADC(Short_t adc) {fADC=adc;} - /** Reset all energies in cell **/ - void ResetEnergyFast(); - inline void AddEnergy(Float_t energy) {fEnergy+=energy;} - - // code=0 for "3x3" cluster - void GetClusterEnergy(Float_t& EcalEnergy); - - inline void SetCoord(Float_t x1, Float_t y1, Float_t x2, Float_t y2) - { fX1=x1; fY1=y1; fX2=x2; fY2=y2; } - inline void SetType(Char_t type) {fType=type;} - /** returns number of neighbors in lst with cell **/ - Int_t CountNeighbors(const std::list& lst) const; -private: - /** cell number within the module **/ - Int_t fNumber; - /** left edge of the cell **/ - Float_t fX1; - /** bottom edge of the cell **/ - Float_t fY1; - /** right edge of the cell **/ - Float_t fX2; - /** upper edge of the cell **/ - Float_t fY2; - /** type of cell **/ - Char_t fType; - /** energy in the calorimeter cell **/ - Float_t fEnergy; - /** ADC counts read **/ - Short_t fADC; - - - /** list of neighbor cells **/ - std::list fNeighbors; - /** 5x5 cluster **/ - std::list f5x5Cluster; - void Create5x5Cluster(); - - /** Time of cell to fire **/ - Double_t fTime; - - ClassDef(ecalCell,1); + public: + ecalCell(Int_t cellnumber, + Float_t x1 = 0, + Float_t y1 = 0, + Float_t x2 = 0, + Float_t y2 = 0, + Char_t type = 0, + Float_t energy = 0) + : TObject() + , fNumber(cellnumber) + , fX1(x1) + , fY1(y1) + , fX2(x2) + , fY2(y2) + , fType(type) + , fEnergy(energy) + , fADC(-1111) + , fNeighbors() + , f5x5Cluster() + , fTime(-1111) {}; + + inline Bool_t IsInside(Float_t x, Float_t y) { return x > GetX1() && x < GetX2() && y > GetY1() && y < GetY2(); } + // getters + inline Char_t GetType() const { return fType; } + inline Float_t X1() const { return fX1; } + inline Float_t Y1() const { return fY1; } + inline Float_t X2() const { return fX2; } + inline Float_t Y2() const { return fY2; } + inline Float_t GetX1() const { return fX1; } + inline Float_t GetY1() const { return fY1; } + inline Float_t GetX2() const { return fX2; } + inline Float_t GetY2() const { return fY2; } + inline Float_t GetCenterX() const { return (fX1 + fX2) / 2.0; } + inline Float_t GetCenterY() const { return (fY1 + fY2) / 2.0; } + inline Short_t ADC() const { return fADC; } + inline Short_t GetADC() const { return fADC; } + + inline Int_t GetCellNumber() const { return fNumber; } + + inline Float_t GetEnergy() const { return fEnergy; } + Float_t GetTime() const { return fTime; } + void SetTime(Float_t time) { fTime = time; } + + // Neighbours stuff + // Get list of 8 neighbors + inline void GetNeighborsList(std::list& neib) const { neib = fNeighbors; } + inline void SetNeighborsList(std::list& neib) { fNeighbors = neib; } + + // 5x5 cluster stuff + inline void Get5x5Cluster(std::list& cls) + { + if (f5x5Cluster.size() == 0) + Create5x5Cluster(); + cls = f5x5Cluster; + } + + inline void SetEnergy(Float_t energy) { fEnergy = energy; } + inline void SetADC(Short_t adc) { fADC = adc; } + /** Reset all energies in cell **/ + void ResetEnergyFast(); + inline void AddEnergy(Float_t energy) { fEnergy += energy; } + + // code=0 for "3x3" cluster + void GetClusterEnergy(Float_t& EcalEnergy); + + inline void SetCoord(Float_t x1, Float_t y1, Float_t x2, Float_t y2) + { + fX1 = x1; + fY1 = y1; + fX2 = x2; + fY2 = y2; + } + inline void SetType(Char_t type) { fType = type; } + /** returns number of neighbors in lst with cell **/ + Int_t CountNeighbors(const std::list& lst) const; + + private: + /** cell number within the module **/ + Int_t fNumber; + /** left edge of the cell **/ + Float_t fX1; + /** bottom edge of the cell **/ + Float_t fY1; + /** right edge of the cell **/ + Float_t fX2; + /** upper edge of the cell **/ + Float_t fY2; + /** type of cell **/ + Char_t fType; + /** energy in the calorimeter cell **/ + Float_t fEnergy; + /** ADC counts read **/ + Short_t fADC; + + /** list of neighbor cells **/ + std::list fNeighbors; + /** 5x5 cluster **/ + std::list f5x5Cluster; + void Create5x5Cluster(); + + /** Time of cell to fire **/ + Double_t fTime; + + ClassDef(ecalCell, 1); }; inline void ecalCell::ResetEnergyFast() { - fEnergy=0; - fADC=-1111; - fTime=-1111; + fEnergy = 0; + fADC = -1111; + fTime = -1111; } #endif diff --git a/ecal/ecalCellMC.cxx b/ecal/ecalCellMC.cxx index 57e5d25793..ce7c3b5c82 100644 --- a/ecal/ecalCellMC.cxx +++ b/ecal/ecalCellMC.cxx @@ -11,68 +11,85 @@ using std::cout; using std::endl; -using std::map; using std::list; +using std::map; //----------------------------------------------------------------------------- ecalCellMC::ecalCellMC(Int_t cellnumber, Float_t x1, Float_t y1, Float_t x2, Float_t y2, Char_t type, Float_t energy) - : ecalCell(cellnumber, x1, y1, x2, y2, type, energy), - fTrackEnergy(), - fTrackTime() -{ -} + : ecalCell(cellnumber, x1, y1, x2, y2, type, energy) + , fTrackEnergy() + , fTrackTime() +{} //----------------------------------------------------------------------------- Float_t ecalCellMC::GetTrackTime(Int_t num) const { - map::const_iterator p=fTrackTime.find(num); - if (p==fTrackTime.end()) return 0; else return p->second; + map::const_iterator p = fTrackTime.find(num); + if (p == fTrackTime.end()) + return 0; + else + return p->second; } - //----------------------------------------------------------------------------- Float_t ecalCellMC::GetTrackEnergy(Int_t num) const { - map::const_iterator p=fTrackEnergy.find(num); - if (p==fTrackEnergy.end()) return 0; else return p->second; + map::const_iterator p = fTrackEnergy.find(num); + if (p == fTrackEnergy.end()) + return 0; + else + return p->second; } //----------------------------------------------------------------------------- void ecalCellMC::ResetEnergy() { - ResetEnergyFast(); - fTrackEnergy.clear(); - fTrackTime.clear(); + ResetEnergyFast(); + fTrackEnergy.clear(); + fTrackTime.clear(); } //----------------------------------------------------------------------------- Float_t ecalCellMC::GetTrackClusterEnergy(Int_t num) { - Float_t energy=GetTrackEnergy(num); - list cls; GetNeighborsList(cls); - list::const_iterator p=cls.begin(); - for(;p!=cls.end();++p) - energy+=((ecalCellMC*)(*p))->GetTrackEnergy(num); - return energy; + Float_t energy = GetTrackEnergy(num); + list cls; + GetNeighborsList(cls); + list::const_iterator p = cls.begin(); + for (; p != cls.end(); ++p) + energy += ((ecalCellMC*)(*p))->GetTrackEnergy(num); + return energy; } // Don't use slow methods except in emergency!!! //----------------------------------------------------------------------------- void ecalCellMC::GetTrackEnergySlow(Int_t n, Int_t& trackid, Double_t& energy_dep) { - map::const_iterator p=fTrackEnergy.begin(); - if (n>=fTrackEnergy.size()) {trackid=-1111; energy_dep=-1111; return; } - Int_t i=0; - for(i=0;ifirst; energy_dep=p->second; + map::const_iterator p = fTrackEnergy.begin(); + if (n >= fTrackEnergy.size()) { + trackid = -1111; + energy_dep = -1111; + return; + } + Int_t i = 0; + for (i = 0; i < n; i++) + (++p); + trackid = p->first; + energy_dep = p->second; } // Don't use slow methods except in emergency!!! //----------------------------------------------------------------------------- void ecalCellMC::GetTrackTimeSlow(Int_t n, Int_t& trackid, Float_t& time) { - map::const_iterator p=fTrackTime.begin(); - if (n>=fTrackTime.size()) {trackid=-1111; time=-1111; return; } - Int_t i=0; - for(i=0;ifirst; time=p->second; + map::const_iterator p = fTrackTime.begin(); + if (n >= fTrackTime.size()) { + trackid = -1111; + time = -1111; + return; + } + Int_t i = 0; + for (i = 0; i < n; i++) + (++p); + trackid = p->first; + time = p->second; } diff --git a/ecal/ecalCellMC.h b/ecal/ecalCellMC.h index 7204cc8a67..d7889c240b 100644 --- a/ecal/ecalCellMC.h +++ b/ecal/ecalCellMC.h @@ -11,61 +11,67 @@ #include "ecalCell.h" +#include #include #include -#include class ecalCellMC : public ecalCell { -public: - ecalCellMC(Int_t cellnumber, Float_t x1=0, Float_t y1=0, Float_t x2=0, Float_t y2=0, Char_t type=0, Float_t energy=0); - - Float_t GetTrackEnergy(Int_t num) const; - Float_t GetTrackTime(Int_t num) const; - - /** Reset all energies in cell **/ - void ResetEnergy(); - - inline void SetTrackEnergy(Int_t num, Float_t energy, Float_t time=-1111) - {fTrackEnergy[num]=energy; fTrackTime[num]=time; } - inline void AddTrackEnergy(Int_t num, Float_t energy, Float_t time=-1111) - { - fTrackEnergy[num]+=energy; - if (time==-1111) return; - std::map::const_iterator p=fTrackTime.find(num); - if (p==fTrackTime.end()) fTrackTime[num]=time; - else - if (fTrackTime[num]>time) fTrackTime[num]=time; - } - // same for tracks - Float_t GetTrackClusterEnergy(Int_t num); - - // For python users - Int_t TrackEnergySize() const {return fTrackEnergy.size();} - Int_t TrackTimeSize() const {return fTrackEnergy.size();} - // Don't use slow methods except in emergency!!! - void GetTrackEnergySlow(Int_t n, Int_t& trackid, Double_t& energy_dep); - void GetTrackTimeSlow(Int_t n, Int_t& trackid, Float_t& time); - - inline std::map::const_iterator GetTrackEnergyBegin() const - {return fTrackEnergy.begin();} - inline std::map::const_iterator GetTrackEnergyEnd() const - {return fTrackEnergy.end();} - - inline std::map::const_iterator GetTrackTimeBegin() const - {return fTrackTime.begin();} - inline std::map::const_iterator GetTrackTimeEnd() const - {return fTrackTime.end();} - -private: - /** map **/ - std::map fTrackEnergy; - - /** map**/ - std::map fTrackTime; - - ClassDef(ecalCellMC,1); + public: + ecalCellMC(Int_t cellnumber, + Float_t x1 = 0, + Float_t y1 = 0, + Float_t x2 = 0, + Float_t y2 = 0, + Char_t type = 0, + Float_t energy = 0); + + Float_t GetTrackEnergy(Int_t num) const; + Float_t GetTrackTime(Int_t num) const; + + /** Reset all energies in cell **/ + void ResetEnergy(); + + inline void SetTrackEnergy(Int_t num, Float_t energy, Float_t time = -1111) + { + fTrackEnergy[num] = energy; + fTrackTime[num] = time; + } + inline void AddTrackEnergy(Int_t num, Float_t energy, Float_t time = -1111) + { + fTrackEnergy[num] += energy; + if (time == -1111) + return; + std::map::const_iterator p = fTrackTime.find(num); + if (p == fTrackTime.end()) + fTrackTime[num] = time; + else if (fTrackTime[num] > time) + fTrackTime[num] = time; + } + // same for tracks + Float_t GetTrackClusterEnergy(Int_t num); + + // For python users + Int_t TrackEnergySize() const { return fTrackEnergy.size(); } + Int_t TrackTimeSize() const { return fTrackEnergy.size(); } + // Don't use slow methods except in emergency!!! + void GetTrackEnergySlow(Int_t n, Int_t& trackid, Double_t& energy_dep); + void GetTrackTimeSlow(Int_t n, Int_t& trackid, Float_t& time); + + inline std::map::const_iterator GetTrackEnergyBegin() const { return fTrackEnergy.begin(); } + inline std::map::const_iterator GetTrackEnergyEnd() const { return fTrackEnergy.end(); } + + inline std::map::const_iterator GetTrackTimeBegin() const { return fTrackTime.begin(); } + inline std::map::const_iterator GetTrackTimeEnd() const { return fTrackTime.end(); } + + private: + /** map **/ + std::map fTrackEnergy; + + /** map**/ + std::map fTrackTime; + + ClassDef(ecalCellMC, 1); }; - #endif diff --git a/ecal/ecalCluster.cxx b/ecal/ecalCluster.cxx index 41182388b5..37ec44eea4 100644 --- a/ecal/ecalCluster.cxx +++ b/ecal/ecalCluster.cxx @@ -1,10 +1,9 @@ #include "ecalCluster.h" +#include "TMath.h" #include "ecalCell.h" #include "ecalMaximum.h" -#include "TMath.h" - #include #include @@ -12,104 +11,109 @@ using namespace std; /** An empty constructor **/ ecalCluster::ecalCluster() - : TObject(), - fNum(0), - fSize(0), - fMaxs(0), - fEnergy(0.), - fPreCalibrated(-1111.), - fMoment(0.), - fMomentX(0.), - fMomentY(0.), - fX(0.), - fY(0.), - fChi2(0.), - fStatus(0), - fCellNums(), - fPeakNums(), - fPreEnergy(), - fMaximums(NULL) -{ -} + : TObject() + , fNum(0) + , fSize(0) + , fMaxs(0) + , fEnergy(0.) + , fPreCalibrated(-1111.) + , fMoment(0.) + , fMomentX(0.) + , fMomentY(0.) + , fX(0.) + , fY(0.) + , fChi2(0.) + , fStatus(0) + , fCellNums() + , fPeakNums() + , fPreEnergy() + , fMaximums(NULL) +{} /** A more advanced constructor. Should use this. **/ ecalCluster::ecalCluster(Int_t num, const std::list& cluster, const std::list& maximums) - : TObject(), - fNum(num), - fSize(0), - fMaxs(0), - fEnergy(0.), - fPreCalibrated(-1111.), - fMoment(0.), - fMomentX(0.), - fMomentY(0.), - fX(0.), - fY(0.), - fChi2(0.), - fStatus(0), - fCellNums(), - fPeakNums(), - fPreEnergy(), - fMaximums(NULL) + : TObject() + , fNum(num) + , fSize(0) + , fMaxs(0) + , fEnergy(0.) + , fPreCalibrated(-1111.) + , fMoment(0.) + , fMomentX(0.) + , fMomentY(0.) + , fX(0.) + , fY(0.) + , fChi2(0.) + , fStatus(0) + , fCellNums() + , fPeakNums() + , fPreEnergy() + , fMaximums(NULL) { - std::list cls; - list::const_iterator p=cluster.begin(); - list::const_iterator pm; - Double_t e; - Double_t x; - Double_t y; - Double_t r; - Int_t i; + std::list cls; + list::const_iterator p = cluster.begin(); + list::const_iterator pm; + Double_t e; + Double_t x; + Double_t y; + Double_t r; + Int_t i; - fMaxs=maximums.size(); - fEnergy=0; - fX=0; - fY=0; - for(;p!=cluster.end();++p) - { - cls.push_back(*p); - e=(*p)->GetEnergy(); - x=(*p)->GetCenterX(); - y=(*p)->GetCenterY(); - fX+=x*e; fY+=y*e; - fEnergy+=e; - } - fSize=cls.size(); + fMaxs = maximums.size(); + fEnergy = 0; + fX = 0; + fY = 0; + for (; p != cluster.end(); ++p) { + cls.push_back(*p); + e = (*p)->GetEnergy(); + x = (*p)->GetCenterX(); + y = (*p)->GetCenterY(); + fX += x * e; + fY += y * e; + fEnergy += e; + } + fSize = cls.size(); - cls.sort(ecalClusterSortProcess()); - cls.reverse(); - fX/=fEnergy; - fY/=fEnergy; - fChi2=-1111.0; + cls.sort(ecalClusterSortProcess()); + cls.reverse(); + fX /= fEnergy; + fY /= fEnergy; + fChi2 = -1111.0; - fCellNums.Set(fSize); - fPeakNums.Set(fMaxs); - fPreEnergy.Set(fMaxs); + fCellNums.Set(fSize); + fPeakNums.Set(fMaxs); + fPreEnergy.Set(fMaxs); - fMomentX=0; fMomentY=0; fMoment=0; - for(p=cls.begin();p!=cls.end();++p) - { - /** Still not clear about next 3 variables **/ - e=(*p)->GetEnergy(); - x=fX-(*p)->GetCenterX(); x*=x; - y=fY-(*p)->GetCenterY(); y*=y; - fMomentX+=x*e; fMomentY+=y*e; fMoment+=(x+y)*e; - } - fMomentX/=fEnergy; fMomentY/=fEnergy; fMoment/=fEnergy; + fMomentX = 0; + fMomentY = 0; + fMoment = 0; + for (p = cls.begin(); p != cls.end(); ++p) { + /** Still not clear about next 3 variables **/ + e = (*p)->GetEnergy(); + x = fX - (*p)->GetCenterX(); + x *= x; + y = fY - (*p)->GetCenterY(); + y *= y; + fMomentX += x * e; + fMomentY += y * e; + fMoment += (x + y) * e; + } + fMomentX /= fEnergy; + fMomentY /= fEnergy; + fMoment /= fEnergy; - i=0; - for(p=cls.begin();p!=cls.end();++p) - fCellNums[i++]=(*p)->GetCellNumber(); - i=0; - fMaximums=new ecalMaximum*[fMaxs]; - for(pm=maximums.begin();pm!=maximums.end();++pm) - { - fMaximums[i]=(*pm); - fPeakNums[i++]=(*pm)->Cell()->GetCellNumber(); - } + i = 0; + for (p = cls.begin(); p != cls.end(); ++p) + fCellNums[i++] = (*p)->GetCellNumber(); + i = 0; + fMaximums = new ecalMaximum*[fMaxs]; + for (pm = maximums.begin(); pm != maximums.end(); ++pm) { + fMaximums[i] = (*pm); + fPeakNums[i++] = (*pm)->Cell()->GetCellNumber(); + } } /** An virtual destructor **/ ecalCluster::~ecalCluster() { - delete [] fMaximums; + delete[] fMaximums; } diff --git a/ecal/ecalCluster.h b/ecal/ecalCluster.h index eaa1e6250f..1b925cbfb8 100644 --- a/ecal/ecalCluster.h +++ b/ecal/ecalCluster.h @@ -1,105 +1,107 @@ #ifndef ECALCLUSTER_H #define ECALCLUSTER_H -#include "TObject.h" -#include "TArrayI.h" #include "TArrayD.h" -#include - +#include "TArrayI.h" +#include "TObject.h" #include "ecalCell.h" +#include + class ecalMaximum; struct ecalClusterSortProcess : public std::binary_function { - inline Bool_t operator()(const ecalCell* left, const ecalCell* right) const - { - if (left->GetEnergy()GetEnergy()) - return kTRUE; - return kFALSE; - } + inline Bool_t operator()(const ecalCell* left, const ecalCell* right) const + { + if (left->GetEnergy() < right->GetEnergy()) + return kTRUE; + return kFALSE; + } }; /** A temporary cluster needed for debugging of cluster finder procedure **/ class ecalCluster : public TObject { -friend class ecalClusterFinder; -public: - /** An empty constructor **/ - ecalCluster(); - /** A more advanced constructor. Should use this. **/ - ecalCluster(Int_t num, const std::list& cluster, const std::list& maximums); - /** Number of cluster in event **/ - inline Int_t Number() const {return fNum;} - /** Size of cluster **/ - inline Int_t Size() const {return fSize;} - /** Number of maximums in cluster **/ - inline Int_t Maxs() const {return fMaxs;} - /** Energy of cluster **/ - inline Double_t Energy() const {return fEnergy;} - /** Calibrated energy of the cluster with assumption of normal incident angle **/ - inline Double_t PreCalibrated() const {return fPreCalibrated;} - /** Second moment **/ - inline Double_t Moment() const {return fMoment;} - /** Moment over X axis **/ - inline Double_t MomentX() const {return fMomentX;} - /** Moment over Y axis **/ - inline Double_t MomentY() const {return fMomentY;} - /** Coordinates of cluster centre of gravity **/ - inline Double_t X() const {return fX;} - inline Double_t Y() const {return fY;} - /** \chi^2 of cluster after fitting **/ - inline Double_t Chi2() const {return fChi2;} - /** Status of the cluster: -1 --- rejected, 0 --- new, 1 --- reconstructed **/ - inline Short_t Status() const {return fStatus;} - inline void SetStatus(Short_t st) {fStatus=st;} + friend class ecalClusterFinder; + + public: + /** An empty constructor **/ + ecalCluster(); + /** A more advanced constructor. Should use this. **/ + ecalCluster(Int_t num, const std::list& cluster, const std::list& maximums); + /** Number of cluster in event **/ + inline Int_t Number() const { return fNum; } + /** Size of cluster **/ + inline Int_t Size() const { return fSize; } + /** Number of maximums in cluster **/ + inline Int_t Maxs() const { return fMaxs; } + /** Energy of cluster **/ + inline Double_t Energy() const { return fEnergy; } + /** Calibrated energy of the cluster with assumption of normal incident angle **/ + inline Double_t PreCalibrated() const { return fPreCalibrated; } + /** Second moment **/ + inline Double_t Moment() const { return fMoment; } + /** Moment over X axis **/ + inline Double_t MomentX() const { return fMomentX; } + /** Moment over Y axis **/ + inline Double_t MomentY() const { return fMomentY; } + /** Coordinates of cluster centre of gravity **/ + inline Double_t X() const { return fX; } + inline Double_t Y() const { return fY; } + /** \chi^2 of cluster after fitting **/ + inline Double_t Chi2() const { return fChi2; } + /** Status of the cluster: -1 --- rejected, 0 --- new, 1 --- reconstructed **/ + inline Short_t Status() const { return fStatus; } + inline void SetStatus(Short_t st) { fStatus = st; } + + /** Getters for cells and peaks **/ + inline Int_t CellNum(Int_t i) const { return fCellNums[i]; } + inline Int_t PeakNum(Int_t i) const { return fPeakNums[i]; } + inline Double_t PreEnergy(Int_t i) const { return fPreEnergy[i]; } + inline ecalMaximum* Maximum(Int_t i) const { return fMaximums[i]; } + /** An virtual destructor **/ + virtual ~ecalCluster(); - /** Getters for cells and peaks **/ - inline Int_t CellNum(Int_t i) const {return fCellNums[i];} - inline Int_t PeakNum(Int_t i) const {return fPeakNums[i];} - inline Double_t PreEnergy(Int_t i) const {return fPreEnergy[i];} - inline ecalMaximum* Maximum(Int_t i) const {return fMaximums[i];} - /** An virtual destructor **/ - virtual ~ecalCluster(); -private: - /** Cluster number **/ - Int_t fNum; - /** Cluster size in cells - ** A separate variable. fCells not stored **/ - Int_t fSize; - /** Number of maximums in cluster **/ - Int_t fMaxs; - /** Energy of cluster **/ - Double_t fEnergy; - /** Calibrated energy of the cluster with assumption of normal incident angle **/ - Double_t fPreCalibrated; - /** Second moment **/ - Double_t fMoment; - /** Moment over X axis **/ - Double_t fMomentX; - /** Moment over Y axis **/ - Double_t fMomentY; - /** Coordinates of cluster centre of gravity **/ - Double_t fX; - Double_t fY; - /** \chi^2 after fitting **/ - Double_t fChi2; - /** Status of the cluster: -1 --- rejected, 0 --- new, 1 --- reconstructed **/ - Short_t fStatus; + private: + /** Cluster number **/ + Int_t fNum; + /** Cluster size in cells + ** A separate variable. fCells not stored **/ + Int_t fSize; + /** Number of maximums in cluster **/ + Int_t fMaxs; + /** Energy of cluster **/ + Double_t fEnergy; + /** Calibrated energy of the cluster with assumption of normal incident angle **/ + Double_t fPreCalibrated; + /** Second moment **/ + Double_t fMoment; + /** Moment over X axis **/ + Double_t fMomentX; + /** Moment over Y axis **/ + Double_t fMomentY; + /** Coordinates of cluster centre of gravity **/ + Double_t fX; + Double_t fY; + /** \chi^2 after fitting **/ + Double_t fChi2; + /** Status of the cluster: -1 --- rejected, 0 --- new, 1 --- reconstructed **/ + Short_t fStatus; - /** Serial numbers of cells in cluster **/ - TArrayI fCellNums; - /** Serial numbers of peaks in cluster **/ - TArrayI fPeakNums; - /** An energy deposition in peak areas (preclusters) **/ - TArrayD fPreEnergy; - /** Serial numbers of maximums in system **/ - ecalMaximum** fMaximums; //! + /** Serial numbers of cells in cluster **/ + TArrayI fCellNums; + /** Serial numbers of peaks in cluster **/ + TArrayI fPeakNums; + /** An energy deposition in peak areas (preclusters) **/ + TArrayD fPreEnergy; + /** Serial numbers of maximums in system **/ + ecalMaximum** fMaximums; //! - ecalCluster(const ecalCluster&); - ecalCluster& operator=(const ecalCluster&); + ecalCluster(const ecalCluster&); + ecalCluster& operator=(const ecalCluster&); - ClassDef(ecalCluster, 2) + ClassDef(ecalCluster, 2) }; #endif diff --git a/ecal/ecalClusterCalibration.cxx b/ecal/ecalClusterCalibration.cxx index fa83d4c8ff..8611cee8dc 100644 --- a/ecal/ecalClusterCalibration.cxx +++ b/ecal/ecalClusterCalibration.cxx @@ -1,85 +1,81 @@ #include "ecalClusterCalibration.h" #include "FairRootManager.h" - #include "TFormula.h" -#include #include +#include #include using namespace std; /** --- Default constructor --------------------------------------------------- **/ ecalClusterCalibration::ecalClusterCalibration() - : FairTask("EcalClusterCalibration", 0) + : FairTask("EcalClusterCalibration", 0) { - Int_t i; + Int_t i; - for(i=0;i<10;i++) - fStraightCalibration[i]=fCalibration[i]=NULL; + for (i = 0; i < 10; i++) + fStraightCalibration[i] = fCalibration[i] = NULL; } /** --- Standard constructor. Use this ---------------------------------------- **/ ecalClusterCalibration::ecalClusterCalibration(const char* name, Int_t iVerbose) - : FairTask(name, iVerbose) + : FairTask(name, iVerbose) { - Int_t i; + Int_t i; - for(i=0;i<10;i++) - fStraightCalibration[i]=fCalibration[i]=NULL; + for (i = 0; i < 10; i++) + fStraightCalibration[i] = fCalibration[i] = NULL; } /** --- Calibration if only cluster energy is known --------------------------- **/ Double_t ecalClusterCalibration::Calibrate(Int_t celltype, Double_t energy) { - if (fStraightCalibration[celltype]==NULL) - { - Error("Calibrate", "No straight calibration for celltype %d.", celltype); - return -1111; - } - return fStraightCalibration[celltype]->Eval(energy); + if (fStraightCalibration[celltype] == NULL) { + Error("Calibrate", "No straight calibration for celltype %d.", celltype); + return -1111; + } + return fStraightCalibration[celltype]->Eval(energy); } /** --- Calibration if theta and cluster energy is known ---------------------- **/ Double_t ecalClusterCalibration::Calibrate(Int_t celltype, Double_t energy, Double_t theta) { - if (fCalibration[celltype]==NULL) - { - Error("Calibrate", "No calibration for celltype %d.", celltype); - return -1111; - } - return fCalibration[celltype]->Eval(energy, theta); + if (fCalibration[celltype] == NULL) { + Error("Calibrate", "No calibration for celltype %d.", celltype); + return -1111; + } + return fCalibration[celltype]->Eval(energy, theta); } /** --- Initialization of the task -------------------------------------------- **/ InitStatus ecalClusterCalibration::Init() { - FairRootManager* manager=FairRootManager::Instance(); - if (!manager) - { - Fatal("Init()", "Can't find IOManager."); - return kFATAL; - } + FairRootManager* manager = FairRootManager::Instance(); + if (!manager) { + Fatal("Init()", "Can't find IOManager."); + return kFATAL; + } - manager->Register(GetName(), "ECAL", this, kFALSE); + manager->Register(GetName(), "ECAL", this, kFALSE); - return kSUCCESS; + return kSUCCESS; } /** --- Executed task --------------------------------------------------------- **/ void ecalClusterCalibration::Exec(Option_t* option) { - ; + ; } /** --- Finish task ----------------------------------------------------------- **/ void ecalClusterCalibration::Finish() { - ; + ; } /** --- Destructor ------------------------------------------------------------ **/ ecalClusterCalibration::~ecalClusterCalibration() { - ; + ; } diff --git a/ecal/ecalClusterCalibration.h b/ecal/ecalClusterCalibration.h index aa2ecb41fd..73fb8be600 100644 --- a/ecal/ecalClusterCalibration.h +++ b/ecal/ecalClusterCalibration.h @@ -12,46 +12,43 @@ class TFormula; class ecalClusterCalibration : public FairTask { -public: - /** Default constructor **/ - ecalClusterCalibration(); - /** Standard constructor. Use this **/ - ecalClusterCalibration(const char* name, Int_t iVerbose=0); - /** Destructor **/ - virtual ~ecalClusterCalibration(); - /** Initialization of the task **/ - virtual InitStatus Init(); - ecalClusterCalibration* InitPython() {return this;} - /** Executed task **/ - virtual void Exec(Option_t* option); - /** Finish task **/ - virtual void Finish(); - - void SetStraightCalibration(Int_t celltype, TFormula* f) - {fStraightCalibration[celltype]=f;} - void SetCalibration(Int_t celltype, TFormula* f) - {fCalibration[celltype]=f;} - - TFormula* StraightCalibration(Int_t celltype) const - {return fStraightCalibration[celltype];} - TFormula* Calibration(Int_t celltype) const - {return fCalibration[celltype];} - - /** Calibration if only cluster energy is known **/ - Double_t Calibrate(Int_t celltype, Double_t energy); - /** Calibration if theta and cluster energy is known **/ - Double_t Calibrate(Int_t celltype, Double_t energy, Double_t theta); -private: - // Calibration if only energy deposition in cluster. - // One formula for each cell type - TFormula* fStraightCalibration[10]; //! - // Calibration if the vertex is known - TFormula* fCalibration[10]; //! - - ecalClusterCalibration(const ecalClusterCalibration&); - ecalClusterCalibration& operator=(const ecalClusterCalibration&); - - ClassDef(ecalClusterCalibration, 1); + public: + /** Default constructor **/ + ecalClusterCalibration(); + /** Standard constructor. Use this **/ + ecalClusterCalibration(const char* name, Int_t iVerbose = 0); + /** Destructor **/ + virtual ~ecalClusterCalibration(); + /** Initialization of the task **/ + virtual InitStatus Init(); + ecalClusterCalibration* InitPython() { return this; } + /** Executed task **/ + virtual void Exec(Option_t* option); + /** Finish task **/ + virtual void Finish(); + + void SetStraightCalibration(Int_t celltype, TFormula* f) { fStraightCalibration[celltype] = f; } + void SetCalibration(Int_t celltype, TFormula* f) { fCalibration[celltype] = f; } + + TFormula* StraightCalibration(Int_t celltype) const { return fStraightCalibration[celltype]; } + TFormula* Calibration(Int_t celltype) const { return fCalibration[celltype]; } + + /** Calibration if only cluster energy is known **/ + Double_t Calibrate(Int_t celltype, Double_t energy); + /** Calibration if theta and cluster energy is known **/ + Double_t Calibrate(Int_t celltype, Double_t energy, Double_t theta); + + private: + // Calibration if only energy deposition in cluster. + // One formula for each cell type + TFormula* fStraightCalibration[10]; //! + // Calibration if the vertex is known + TFormula* fCalibration[10]; //! + + ecalClusterCalibration(const ecalClusterCalibration&); + ecalClusterCalibration& operator=(const ecalClusterCalibration&); + + ClassDef(ecalClusterCalibration, 1); }; #endif diff --git a/ecal/ecalClusterFinder.cxx b/ecal/ecalClusterFinder.cxx index 2ef721ada1..37020928b5 100644 --- a/ecal/ecalClusterFinder.cxx +++ b/ecal/ecalClusterFinder.cxx @@ -1,17 +1,15 @@ #include "ecalClusterFinder.h" -#include "TClonesArray.h" - #include "FairRootManager.h" #include "FairTrackParam.h" - -#include "ecalStructure.h" +#include "TClonesArray.h" #include "ecalCell.h" -#include "ecalInf.h" #include "ecalCluster.h" -#include "ecalPreCluster.h" -#include "ecalMaximum.h" #include "ecalClusterCalibration.h" +#include "ecalInf.h" +#include "ecalMaximum.h" +#include "ecalPreCluster.h" +#include "ecalStructure.h" #include #include @@ -21,70 +19,67 @@ using namespace std; /** Exec a task **/ void ecalClusterFinder::Exec(Option_t* option) { - fEv++; + fEv++; - ClearPreClusters(); - FormPreClusters(); - FormClusters(); + ClearPreClusters(); + FormPreClusters(); + FormClusters(); } InitStatus ecalClusterFinder::Init() { - FairRootManager* io=FairRootManager::Instance(); - if (!io) - { - Fatal("Init", "Can't find IOManager."); - return kFATAL; - } - fStr=(ecalStructure*)io->GetObject("EcalStructure"); - if (!fStr) - { - Fatal("Init()", "Can't find calorimeter structure in the system."); - return kFATAL; - } - fInf=fStr->GetEcalInf(); - fMaximums=(TClonesArray*)io->GetObject("EcalMaximums"); - if (!fMaximums) - { - Fatal("Init", "Can't find array of calorimeter maximums in the system."); - return kFATAL; - } - fCalib=(ecalClusterCalibration*)io->GetObject("ecalClusterCalibration"); - if (!fCalib) - { - Fatal("Init", "Can't find ecalClusterCalibration in the system."); - return kFATAL; - } - - fClusters=new TClonesArray("ecalCluster", 2000); - io->Register("EcalClusters", "ECAL", fClusters, kTRUE); - fEv=0; - return kSUCCESS; + FairRootManager* io = FairRootManager::Instance(); + if (!io) { + Fatal("Init", "Can't find IOManager."); + return kFATAL; + } + fStr = (ecalStructure*)io->GetObject("EcalStructure"); + if (!fStr) { + Fatal("Init()", "Can't find calorimeter structure in the system."); + return kFATAL; + } + fInf = fStr->GetEcalInf(); + fMaximums = (TClonesArray*)io->GetObject("EcalMaximums"); + if (!fMaximums) { + Fatal("Init", "Can't find array of calorimeter maximums in the system."); + return kFATAL; + } + fCalib = (ecalClusterCalibration*)io->GetObject("ecalClusterCalibration"); + if (!fCalib) { + Fatal("Init", "Can't find ecalClusterCalibration in the system."); + return kFATAL; + } + + fClusters = new TClonesArray("ecalCluster", 2000); + io->Register("EcalClusters", "ECAL", fClusters, kTRUE); + fEv = 0; + return kSUCCESS; } -TClonesArray* ecalClusterFinder::InitPython(ecalStructure* structure, TClonesArray* maximums, ecalClusterCalibration* calib) +TClonesArray* ecalClusterFinder::InitPython(ecalStructure* structure, + TClonesArray* maximums, + ecalClusterCalibration* calib) { - fMaximums=maximums; - fStr=structure; - fCalib=calib; - fClusters=new TClonesArray("ecalCluster", 2000); - return fClusters; + fMaximums = maximums; + fStr = structure; + fCalib = calib; + fClusters = new TClonesArray("ecalCluster", 2000); + return fClusters; } /** Finish a task **/ void ecalClusterFinder::Finish() { - ; + ; } /** Destructor **/ ecalClusterFinder::~ecalClusterFinder() { - if (fClusters) - { - fClusters->Delete(); - delete fClusters; - } + if (fClusters) { + fClusters->Delete(); + delete fClusters; + } } /** Form a preclusters. @@ -92,159 +87,160 @@ ecalClusterFinder::~ecalClusterFinder() ** A cluster is a group of preclusters with common cells. **/ void ecalClusterFinder::FormPreClusters() { - Int_t nm=fMaximums->GetEntriesFast(); - Int_t i=0; - ecalMaximum* max; - list all; - list::const_iterator p; - list::const_iterator p2; - list cls; - list cls2; - ecalCell* cell; - ecalCell* min; - Double_t e; - Double_t ecls; - ecalPreCluster* precluster; - - - for(;iAt(i); - if (max==NULL) continue; - /** Remove maximums matched with charged tracks **/ - if (max->Mark()!=0) continue; - cell=max->Cell(); - ecls=cell->GetEnergy(); -// cout << ecls << endl; - /** Remove low energy maximums **/ - if (eclsGetNeighborsList(all); - cls.clear(); - for(p=all.begin();p!=all.end();++p) - { - (*p)->GetNeighborsList(cls2); - for(p2=cls2.begin();p2!=cls2.end();++p2) - if (find(cls.begin(), cls.end(), *p2)==cls.end()) cls.push_back(*p2); + Int_t nm = fMaximums->GetEntriesFast(); + Int_t i = 0; + ecalMaximum* max; + list all; + list::const_iterator p; + list::const_iterator p2; + list cls; + list cls2; + ecalCell* cell; + ecalCell* min; + Double_t e; + Double_t ecls; + ecalPreCluster* precluster; + + for (; i < nm; i++) { + max = (ecalMaximum*)fMaximums->At(i); + if (max == NULL) + continue; + /** Remove maximums matched with charged tracks **/ + if (max->Mark() != 0) + continue; + cell = max->Cell(); + ecls = cell->GetEnergy(); + // cout << ecls << endl; + /** Remove low energy maximums **/ + if (ecls < fMinMaxE) + continue; + /* + cell->GetNeighborsList(all); + cls.clear(); + for(p=all.begin();p!=all.end();++p) + { + (*p)->GetNeighborsList(cls2); + for(p2=cls2.begin();p2!=cls2.end();++p2) + if (find(cls.begin(), cls.end(), *p2)==cls.end()) cls.push_back(*p2); + } + */ + cell->Get5x5Cluster(cls); + ecls = 0.0; + for (p = cls.begin(); p != cls.end(); ++p) + ecls += (*p)->GetEnergy(); + // cout << ":" << ecls << endl; + /** Remove low energy clusters **/ + if (ecls < fMinClusterE) + continue; + precluster = new ecalPreCluster(cls, max); + fPreClusters.push_back(precluster); } -*/ - cell->Get5x5Cluster(cls); - ecls=0.0; - for(p=cls.begin();p!=cls.end();++p) - ecls+=(*p)->GetEnergy(); -// cout << ":" << ecls << endl; - /** Remove low energy clusters **/ - if (eclsDelete(); - Int_t fN=0; - list::const_iterator p1=fPreClusters.begin(); - list::const_iterator p2; - list cluster; - list maxs; - list::const_iterator pc; - list::const_iterator pc1; - UInt_t oldsize; - Int_t MaxSize=0; - Int_t Maximums=0; - Int_t max; - Int_t type; - - if (fVerbose>9) - { - Info("FormClusters", "Total %d preclusters found.", (Int_t)fPreClusters.size()); - } - for(;p1!=fPreClusters.end();++p1) - if ((*p1)->fMark==0) - { - cluster.clear(); oldsize=0; maxs.clear(); - cluster=(*p1)->fCells; maxs.push_back((*p1)->fMax); type=(*p1)->fMaximum->GetType(); - max=1; - while(cluster.size()!=oldsize) - { - oldsize=cluster.size(); - p2=p1; - for(++p2;p2!=fPreClusters.end();++p2) - if ((*p2)->fMark==0) - { - pc=cluster.begin(); - for(;pc!=cluster.end();++pc) - { - pc1=find((*p2)->fCells.begin(), (*p2)->fCells.end(), (*pc)); - if (pc1==(*p2)->fCells.end()) continue; - break; - } - if (pc!=cluster.end()) - { - (*p2)->fMark=1; - pc=(*p2)->fCells.begin(); - for(;pc!=(*p2)->fCells.end();++pc) - if (find(cluster.begin(), cluster.end(), (*pc))==cluster.end()) - cluster.push_back(*pc); - maxs.push_back((*p2)->fMax); - max++; - } - } + /** ecalCluster needs a destructor call :-( **/ + fClusters->Delete(); + Int_t fN = 0; + list::const_iterator p1 = fPreClusters.begin(); + list::const_iterator p2; + list cluster; + list maxs; + list::const_iterator pc; + list::const_iterator pc1; + UInt_t oldsize; + Int_t MaxSize = 0; + Int_t Maximums = 0; + Int_t max; + Int_t type; + + if (fVerbose > 9) { + Info("FormClusters", "Total %d preclusters found.", (Int_t)fPreClusters.size()); + } + for (; p1 != fPreClusters.end(); ++p1) + if ((*p1)->fMark == 0) { + cluster.clear(); + oldsize = 0; + maxs.clear(); + cluster = (*p1)->fCells; + maxs.push_back((*p1)->fMax); + type = (*p1)->fMaximum->GetType(); + max = 1; + while (cluster.size() != oldsize) { + oldsize = cluster.size(); + p2 = p1; + for (++p2; p2 != fPreClusters.end(); ++p2) + if ((*p2)->fMark == 0) { + pc = cluster.begin(); + for (; pc != cluster.end(); ++pc) { + pc1 = find((*p2)->fCells.begin(), (*p2)->fCells.end(), (*pc)); + if (pc1 == (*p2)->fCells.end()) + continue; + break; + } + if (pc != cluster.end()) { + (*p2)->fMark = 1; + pc = (*p2)->fCells.begin(); + for (; pc != (*p2)->fCells.end(); ++pc) + if (find(cluster.begin(), cluster.end(), (*pc)) == cluster.end()) + cluster.push_back(*pc); + maxs.push_back((*p2)->fMax); + max++; + } + } + } + (*p1)->fMark = 1; + if ((Int_t)cluster.size() > MaxSize) + MaxSize = cluster.size(); + if (max > Maximums) + Maximums = max; + ecalCluster* cls = new ((*fClusters)[fN]) ecalCluster(fN, cluster, maxs); + fN++; + cls->fPreCalibrated = fCalib->Calibrate(type, cls->fEnergy); + } + if (fVerbose > 0) { + Info("FormClusters", "Total %d clusters formed.", fN); + Info("FormClusters", "Maximum size of cluster is %d cells.", MaxSize); + Info("FormClusters", "Maximum number of photons per cluster is %d.", Maximums); } - (*p1)->fMark=1; - if ((Int_t)cluster.size()>MaxSize) - MaxSize=cluster.size(); - if (max>Maximums) Maximums=max; - ecalCluster* cls=new ((*fClusters)[fN]) ecalCluster(fN, cluster, maxs); fN++; - cls->fPreCalibrated=fCalib->Calibrate(type, cls->fEnergy); - } - if (fVerbose>0) - { - Info("FormClusters", "Total %d clusters formed.", fN); - Info("FormClusters", "Maximum size of cluster is %d cells.", MaxSize); - Info("FormClusters", "Maximum number of photons per cluster is %d.", Maximums); - } } /** Clear a preclusters list **/ void ecalClusterFinder::ClearPreClusters() { - list::const_iterator p=fPreClusters.begin(); - for(;p!=fPreClusters.end();++p) - delete (*p); - fPreClusters.clear(); + list::const_iterator p = fPreClusters.begin(); + for (; p != fPreClusters.end(); ++p) + delete (*p); + fPreClusters.clear(); } /** Standard constructor **/ ecalClusterFinder::ecalClusterFinder(const char* name, const Int_t verbose) - : FairTask(name, verbose), - fEv(0), - fMaximums(NULL), - fClusters(NULL), - fStr(NULL), - fInf(NULL), - fPreClusters(), - fMinClusterE(0.03), - fMinMaxE(0.015) + : FairTask(name, verbose) + , fEv(0) + , fMaximums(NULL) + , fClusters(NULL) + , fStr(NULL) + , fInf(NULL) + , fPreClusters() + , fMinClusterE(0.03) + , fMinMaxE(0.015) { - ; + ; } - /** Only to comply with frame work. **/ ecalClusterFinder::ecalClusterFinder() - : FairTask(), - fEv(0), - fMaximums(NULL), - fClusters(NULL), - fStr(NULL), - fInf(NULL), - fPreClusters(), - fMinClusterE(0.03), - fMinMaxE(0.015) + : FairTask() + , fEv(0) + , fMaximums(NULL) + , fClusters(NULL) + , fStr(NULL) + , fInf(NULL) + , fPreClusters() + , fMinClusterE(0.03) + , fMinMaxE(0.015) { - ; + ; } diff --git a/ecal/ecalClusterFinder.h b/ecal/ecalClusterFinder.h index d025baa2dc..a878c4dda7 100644 --- a/ecal/ecalClusterFinder.h +++ b/ecal/ecalClusterFinder.h @@ -5,6 +5,7 @@ #define ECALCLUSTERFINDER_H #include "FairTask.h" + #include class TClonesArray; @@ -15,69 +16,70 @@ class ecalPreCluster; class ecalMaximum; class ecalClusterCalibration; -class ecalClusterFinder: public FairTask +class ecalClusterFinder : public FairTask { -public: - /** Standard constructor **/ - ecalClusterFinder(const char* name, const Int_t verbose); - /** Only to comply with frame work. **/ - ecalClusterFinder(); - - /** Destructor **/ - virtual ~ecalClusterFinder(); - - /** Finish a task **/ - virtual void Finish(); - - /** Exec a task **/ - virtual void Exec(Option_t* option); - - /** Initialization **/ - virtual InitStatus Init(); - TClonesArray* InitPython(ecalStructure* structure, TClonesArray* maximums, ecalClusterCalibration* calib); - - Double_t MinMaxE() const {return fMinMaxE;} - Double_t MinClusterE() const {return fMinClusterE;} - - /** Minimum precluster uncalibrated energy **/ - void SetMinMaxE(Double_t minmaxe=0.015) {fMinMaxE=minmaxe;} - /** Minimum uncalibrated energy of precluster maximum for consideration **/ - void SetMinClusterE(Double_t minmaxe=0.03) {fMinClusterE=minmaxe;} -private: - /** Form clusters from precluster **/ - void FormClusters(); - /** Form a preclusters **/ - void FormPreClusters(); - /** Clear a preclusters list **/ - void ClearPreClusters(); - /** Current event **/ - Int_t fEv; - - /** Array of maximums in calorimeter. - ** Maximums belong to charged tracks excluded. **/ - TClonesArray* fMaximums; //! - /** An array of clusters **/ - TClonesArray* fClusters; //! - /** A calorimeter structure **/ - ecalStructure* fStr; //! - /** Cluster calibration object for photons **/ - ecalClusterCalibration* fCalib; //! - /** An information about calorimeter **/ - ecalInf* fInf; //! - - /** A list of preclusters - ** May be better use TClonesArray? **/ - std::list fPreClusters; //! - - /** Minimum precluster uncalibrated energy **/ - Double_t fMinClusterE; - /** Minimum uncalibrated energy of precluster maximum for consideration **/ - Double_t fMinMaxE; - - ecalClusterFinder(const ecalClusterFinder&); - ecalClusterFinder& operator=(const ecalClusterFinder&); - - ClassDef(ecalClusterFinder, 1) + public: + /** Standard constructor **/ + ecalClusterFinder(const char* name, const Int_t verbose); + /** Only to comply with frame work. **/ + ecalClusterFinder(); + + /** Destructor **/ + virtual ~ecalClusterFinder(); + + /** Finish a task **/ + virtual void Finish(); + + /** Exec a task **/ + virtual void Exec(Option_t* option); + + /** Initialization **/ + virtual InitStatus Init(); + TClonesArray* InitPython(ecalStructure* structure, TClonesArray* maximums, ecalClusterCalibration* calib); + + Double_t MinMaxE() const { return fMinMaxE; } + Double_t MinClusterE() const { return fMinClusterE; } + + /** Minimum precluster uncalibrated energy **/ + void SetMinMaxE(Double_t minmaxe = 0.015) { fMinMaxE = minmaxe; } + /** Minimum uncalibrated energy of precluster maximum for consideration **/ + void SetMinClusterE(Double_t minmaxe = 0.03) { fMinClusterE = minmaxe; } + + private: + /** Form clusters from precluster **/ + void FormClusters(); + /** Form a preclusters **/ + void FormPreClusters(); + /** Clear a preclusters list **/ + void ClearPreClusters(); + /** Current event **/ + Int_t fEv; + + /** Array of maximums in calorimeter. + ** Maximums belong to charged tracks excluded. **/ + TClonesArray* fMaximums; //! + /** An array of clusters **/ + TClonesArray* fClusters; //! + /** A calorimeter structure **/ + ecalStructure* fStr; //! + /** Cluster calibration object for photons **/ + ecalClusterCalibration* fCalib; //! + /** An information about calorimeter **/ + ecalInf* fInf; //! + + /** A list of preclusters + ** May be better use TClonesArray? **/ + std::list fPreClusters; //! + + /** Minimum precluster uncalibrated energy **/ + Double_t fMinClusterE; + /** Minimum uncalibrated energy of precluster maximum for consideration **/ + Double_t fMinMaxE; + + ecalClusterFinder(const ecalClusterFinder&); + ecalClusterFinder& operator=(const ecalClusterFinder&); + + ClassDef(ecalClusterFinder, 1) }; #endif diff --git a/ecal/ecalContFact.cxx b/ecal/ecalContFact.cxx index 933267dfc5..e16bbe053a 100644 --- a/ecal/ecalContFact.cxx +++ b/ecal/ecalContFact.cxx @@ -1,46 +1,44 @@ #include "ecalContFact.h" - #include "FairRuntimeDb.h" #include - -//static ecalContFact gecalContFact; +// static ecalContFact gecalContFact; ecalContFact::ecalContFact() - : FairContFact() + : FairContFact() { - /** Constructor (called when the library is loaded) */ - fName="ecalContFact"; - fTitle="Factory for parameter containers in libecal"; - setAllContainers(); - FairRuntimeDb::instance()->addContFactory(this); + /** Constructor (called when the library is loaded) */ + fName = "ecalContFact"; + fTitle = "Factory for parameter containers in libecal"; + setAllContainers(); + FairRuntimeDb::instance()->addContFactory(this); } void ecalContFact::setAllContainers() { - /** Creates the Container objects with all accepted - contexts and adds them to - the list of containers for the ecal library. - */ - - /* FairContainer* p= new FairContainer("ecalGeoPar", - "ecal Geometry Parameters", - "TestDefaultContext"); - p->addContext("TestNonDefaultContext"); - - containers->Add(p); -*/ + /** Creates the Container objects with all accepted + contexts and adds them to + the list of containers for the ecal library. + */ + + /* FairContainer* p= new FairContainer("ecalGeoPar", + "ecal Geometry Parameters", + "TestDefaultContext"); + p->addContext("TestNonDefaultContext"); + + containers->Add(p); + */ } FairParSet* ecalContFact::createContainer(FairContainer* c) { - /** Calls the constructor of the corresponding parameter container. - For an actual context, which is not an empty string and not - the default context - of this container, the name is concatinated with the context. - */ + /** Calls the constructor of the corresponding parameter container. + For an actual context, which is not an empty string and not + the default context + of this container, the name is concatinated with the context. + */ /* const char* name=c->GetName(); FairParSet* p=NULL; @@ -50,5 +48,5 @@ FairParSet* ecalContFact::createContainer(FairContainer* c) } return p; */ - return 0; + return 0; } diff --git a/ecal/ecalContFact.h b/ecal/ecalContFact.h index 51583766c5..8e4654346d 100644 --- a/ecal/ecalContFact.h +++ b/ecal/ecalContFact.h @@ -9,11 +9,12 @@ class ecalContFact : public FairContFact { private: void setAllContainers(); + public: ecalContFact(); ~ecalContFact() {} FairParSet* createContainer(FairContainer*); - ClassDef( ecalContFact,0) // Factory for all ecal parameter containers + ClassDef(ecalContFact, 0) // Factory for all ecal parameter containers }; #endif diff --git a/ecal/ecalDigi.cxx b/ecal/ecalDigi.cxx index 19168a316a..2394c3150c 100644 --- a/ecal/ecalDigi.cxx +++ b/ecal/ecalDigi.cxx @@ -1,130 +1,129 @@ #include "ecalDigi.h" -#include "ecalStructure.h" - #include "FairRootManager.h" - +#include "TMath.h" #include "TRandom.h" #include "TSystem.h" -#include "TMath.h" +#include "ecalStructure.h" -#include #include +#include #include using namespace std; /** --- Default constructor --------------------------------------------------- **/ ecalDigi::ecalDigi() - : FairTask(), - fPedestal(80), - fADCMax(16384), - fADCNoise(1.0e-3), - fADCChannel(1.0e-3), - fStr(NULL), fChannelMap() + : FairTask() + , fPedestal(80) + , fADCMax(16384) + , fADCNoise(1.0e-3) + , fADCChannel(1.0e-3) + , fStr(NULL) + , fChannelMap() { - fChannelMap.clear(); + fChannelMap.clear(); } /** --- Standard constructor. Use this ---------------------------------------- **/ ecalDigi::ecalDigi(const char* name, Int_t iVerbose) - : FairTask(name, iVerbose), - fPedestal(80), - fADCMax(16384), - fADCChannel(1.0e-3), - fADCNoise(1.0e-3), - fStr(NULL), fChannelMap() + : FairTask(name, iVerbose) + , fPedestal(80) + , fADCMax(16384) + , fADCChannel(1.0e-3) + , fADCNoise(1.0e-3) + , fStr(NULL) + , fChannelMap() { - fChannelMap.clear(); + fChannelMap.clear(); } /** --- Ugly load of map channel number -> ADC channel from the file ---------- **/ void ecalDigi::LoadChannelMap(const char* filename) { - map tmp; - TString fname=filename; gSystem->ExpandPathName(fname); - ifstream f(fname); - Int_t ch; - Int_t i=0; - Float_t adc; - - tmp.clear(); - for(;;) - { - f >> ch; if (f.eof()) break; - f >> adc; if (f.eof()) break; - tmp[ch]=adc; - i++; - } - if (fVerbose>999) - Info("LoadChannelMap", "%d records read", i); - f.close(); - SetChannelMap(tmp); + map tmp; + TString fname = filename; + gSystem->ExpandPathName(fname); + ifstream f(fname); + Int_t ch; + Int_t i = 0; + Float_t adc; + + tmp.clear(); + for (;;) { + f >> ch; + if (f.eof()) + break; + f >> adc; + if (f.eof()) + break; + tmp[ch] = adc; + i++; + } + if (fVerbose > 999) + Info("LoadChannelMap", "%d records read", i); + f.close(); + SetChannelMap(tmp); } /** --- Initialization of the task -------------------------------------------- **/ InitStatus ecalDigi::Init() { - FairRootManager* manager=FairRootManager::Instance(); - if (!manager) - { - Fatal("Init()", "Can't find IOManager."); - return kFATAL; - } + FairRootManager* manager = FairRootManager::Instance(); + if (!manager) { + Fatal("Init()", "Can't find IOManager."); + return kFATAL; + } - fStr=(ecalStructure*)manager->GetObject("EcalStructure"); - if (!fStr) - { - Fatal("Init()", "Can't find calorimeter structure in the system."); - return kFATAL; - } + fStr = (ecalStructure*)manager->GetObject("EcalStructure"); + if (!fStr) { + Fatal("Init()", "Can't find calorimeter structure in the system."); + return kFATAL; + } - return kSUCCESS; + return kSUCCESS; } void ecalDigi::InitPython(ecalStructure* structure) { - fStr=structure; + fStr = structure; } /** --- Executed task --------------------------------------------------------- **/ void ecalDigi::Exec(Option_t* option) { - ecalCell* cell; - list cells; - fStr->GetCells(cells); - list::const_iterator p=cells.begin(); - Short_t adc; - - for(;p!=cells.end();++p) - { - cell=(*p); - if (fChannelMap.empty()) - adc=(Short_t)(gRandom->Gaus(cell->GetEnergy(), fADCNoise)/fADCChannel+fPedestal); - else - if (fChannelMap.find(cell->GetCellNumber())==fChannelMap.end()) - { - Error("Exec", "Channel %d not found in map. Using default value!", cell->GetCellNumber()); - //TODO: Should we insert Fatal here? - adc=(Short_t)(gRandom->Gaus(cell->GetEnergy(), fADCNoise)/fADCChannel+fPedestal); - } - else - { - adc=(Short_t)(gRandom->Gaus(cell->GetEnergy(), fADCNoise)/fChannelMap[cell->GetCellNumber()]+fPedestal); + ecalCell* cell; + list cells; + fStr->GetCells(cells); + list::const_iterator p = cells.begin(); + Short_t adc; + + for (; p != cells.end(); ++p) { + cell = (*p); + if (fChannelMap.empty()) + adc = (Short_t)(gRandom->Gaus(cell->GetEnergy(), fADCNoise) / fADCChannel + fPedestal); + else if (fChannelMap.find(cell->GetCellNumber()) == fChannelMap.end()) { + Error("Exec", "Channel %d not found in map. Using default value!", cell->GetCellNumber()); + // TODO: Should we insert Fatal here? + adc = (Short_t)(gRandom->Gaus(cell->GetEnergy(), fADCNoise) / fADCChannel + fPedestal); + } else { + adc = + (Short_t)(gRandom->Gaus(cell->GetEnergy(), fADCNoise) / fChannelMap[cell->GetCellNumber()] + fPedestal); + } + if (adc > fADCMax) + adc = fADCMax; + cell->SetEnergy(-1111); + cell->SetADC(adc); } - if (adc>fADCMax) adc=fADCMax; - cell->SetEnergy(-1111); - cell->SetADC(adc); - } } /** --- Finish task ----------------------------------------------------------- **/ void ecalDigi::Finish() { - ; + ; } /** --- Destructor ------------------------------------------------------------ **/ ecalDigi::~ecalDigi() { - ; + ; } diff --git a/ecal/ecalDigi.h b/ecal/ecalDigi.h index 49882dc3d4..de1e5463c9 100644 --- a/ecal/ecalDigi.h +++ b/ecal/ecalDigi.h @@ -12,55 +12,55 @@ class ecalStructure; class ecalDigi : public FairTask { -public: - /** Default constructor **/ - ecalDigi(); - /** Standard constructor. Use this **/ - ecalDigi(const char* name, Int_t iVerbose); - /** Destructor **/ - virtual ~ecalDigi(); - /** Initialization of the task **/ - virtual InitStatus Init(); - void InitPython(ecalStructure* structure); - /** Executed task **/ - virtual void Exec(Option_t* option); - /** Finish task **/ - virtual void Finish(); + public: + /** Default constructor **/ + ecalDigi(); + /** Standard constructor. Use this **/ + ecalDigi(const char* name, Int_t iVerbose); + /** Destructor **/ + virtual ~ecalDigi(); + /** Initialization of the task **/ + virtual InitStatus Init(); + void InitPython(ecalStructure* structure); + /** Executed task **/ + virtual void Exec(Option_t* option); + /** Finish task **/ + virtual void Finish(); + void SetPedestal(Short_t ped = 80) { fPedestal = ped; } + void SetADCMax(Short_t adcmax = 16384) { fADCMax = adcmax; } + void SetADCNoise(Float_t adcnoise = 1.0e-3) { fADCNoise = adcnoise; } + void SetADCChannel(Float_t adcchannel = 1.0e-3) { fADCChannel = adcchannel; } - void SetPedestal(Short_t ped=80) {fPedestal=ped;} - void SetADCMax(Short_t adcmax=16384) {fADCMax=adcmax;} - void SetADCNoise(Float_t adcnoise=1.0e-3) {fADCNoise=adcnoise;} - void SetADCChannel(Float_t adcchannel=1.0e-3) {fADCChannel=adcchannel;} + // Map: channel number -> ADC channel in GeV + void SetChannelMap(std::map map) { fChannelMap = map; } + // TODO: An ugly way, need database here + void LoadChannelMap(const char* filename); - //Map: channel number -> ADC channel in GeV - void SetChannelMap(std::map map) {fChannelMap=map;} - //TODO: An ugly way, need database here - void LoadChannelMap(const char* filename); + Short_t GetPedestal() const { return fPedestal; } + Short_t GetADCMax() const { return fADCMax; } + Float_t GetADCNoise() const { return fADCNoise; } + Float_t GetADCChannel() const { return fADCChannel; } - Short_t GetPedestal() const {return fPedestal;} - Short_t GetADCMax() const {return fADCMax;} - Float_t GetADCNoise() const {return fADCNoise;} - Float_t GetADCChannel() const {return fADCChannel;} -private: - // Pedestal - Short_t fPedestal; - // ADC maximum - Short_t fADCMax; - // ADC Noise - Float_t fADCNoise; - // ADC channel (in energy deposition in _SCINTILLATOR_) - Float_t fADCChannel; - // Calorimeter structure - ecalStructure* fStr; //! + private: + // Pedestal + Short_t fPedestal; + // ADC maximum + Short_t fADCMax; + // ADC Noise + Float_t fADCNoise; + // ADC channel (in energy deposition in _SCINTILLATOR_) + Float_t fADCChannel; + // Calorimeter structure + ecalStructure* fStr; //! - // May be better use Float_t*? - std::map fChannelMap; //! Map: channel number -> ADC channel in GeV + // May be better use Float_t*? + std::map fChannelMap; //! Map: channel number -> ADC channel in GeV - ecalDigi(const ecalDigi&); - ecalDigi& operator=(const ecalDigi&); + ecalDigi(const ecalDigi&); + ecalDigi& operator=(const ecalDigi&); - ClassDef(ecalDigi, 1); + ClassDef(ecalDigi, 1); }; #endif diff --git a/ecal/ecalDrawer.cxx b/ecal/ecalDrawer.cxx index c13fcfa014..ce6a17701f 100644 --- a/ecal/ecalDrawer.cxx +++ b/ecal/ecalDrawer.cxx @@ -1,206 +1,225 @@ #include "ecalDrawer.h" #include "FairRootManager.h" - -#include "ShipMCTrack.h" #include "FairTrackParam.h" - -#include "ecalStructure.h" -#include "ecalInf.h" +#include "ShipMCTrack.h" +#include "TASImage.h" +#include "TClonesArray.h" +#include "TText.h" +#include "TTree.h" #include "ecalCell.h" -#include "ecalPoint.h" +#include "ecalCellMC.h" #include "ecalCluster.h" +#include "ecalInf.h" #include "ecalMaximum.h" -#include "ecalCellMC.h" - -#include "TTree.h" -#include "TClonesArray.h" -#include "TASImage.h" -#include "TText.h" - -#include +#include "ecalPoint.h" +#include "ecalStructure.h" #include +#include using namespace std; class ecalDrawerItem { -public: - ecalDrawerItem(ecalCell* cell, Float_t r, Float_t g, Float_t b) - : fCell(cell), fR(r), fG(g), fB(b) {}; - ecalCell* fCell; - Float_t fR; - Float_t fG; - Float_t fB; + public: + ecalDrawerItem(ecalCell* cell, Float_t r, Float_t g, Float_t b) + : fCell(cell) + , fR(r) + , fG(g) + , fB(b) {}; + ecalCell* fCell; + Float_t fR; + Float_t fG; + Float_t fB; }; void ecalDrawer::Exec(Option_t* option) { - DrawImage(); - fEventN++; + DrawImage(); + fEventN++; } void ecalDrawer::PutPixel(Int_t x, Int_t y, Float_t r, Float_t g, Float_t b) { - if (x<0||x>=fCX) return; - if (y<0||y>=fCY) return; - if (r<0||r>1)return; - if (g<0||g>1)return; - if (b<0||b>1)return; - Int_t ri=(Int_t)(255.0*r); - Int_t gi=(Int_t)(255.0*g); - Int_t bi=(Int_t)(255.0*b); - static char color[10]; - sprintf(color, "#%.2X%.2X%.2X", ri, gi, bi); - fC->PutPixel(x, y, color); + if (x < 0 || x >= fCX) + return; + if (y < 0 || y >= fCY) + return; + if (r < 0 || r > 1) + return; + if (g < 0 || g > 1) + return; + if (b < 0 || b > 1) + return; + Int_t ri = (Int_t)(255.0 * r); + Int_t gi = (Int_t)(255.0 * g); + Int_t bi = (Int_t)(255.0 * b); + static char color[10]; + sprintf(color, "#%.2X%.2X%.2X", ri, gi, bi); + fC->PutPixel(x, y, color); } void ecalDrawer::PutPixel(Int_t x, Int_t y, const char* color) { - if (x<0||x>=fCX) return; - if (y<0||y>=fCY) return; - fC->PutPixel(x, fCY-y-1, color); + if (x < 0 || x >= fCX) + return; + if (y < 0 || y >= fCY) + return; + fC->PutPixel(x, fCY - y - 1, color); } /** draw cell with filled color. fEdging used as egding of cell **/ void ecalDrawer::DrawCell(ecalCell* cell, Float_t r, Float_t g, Float_t b) { - Int_t ri=(Int_t)(255.0*r); - Int_t gi=(Int_t)(255.0*g); - Int_t bi=(Int_t)(255.0*b); - static char color[10]; - sprintf(color, "#%.2X%.2X%.2X", ri, gi, bi); - DrawCell(cell, color); + Int_t ri = (Int_t)(255.0 * r); + Int_t gi = (Int_t)(255.0 * g); + Int_t bi = (Int_t)(255.0 * b); + static char color[10]; + sprintf(color, "#%.2X%.2X%.2X", ri, gi, bi); + DrawCell(cell, color); } void ecalDrawer::DrawCell(ecalCell* cell, const char* color) { - Int_t xi1=(Int_t)((cell->X1()/fInf->GetEcalSize(0))*fCX+fCX/2.0); - Int_t xi2=(Int_t)((cell->X2()/fInf->GetEcalSize(0))*fCX+fCX/2.0); - Int_t yi1=(Int_t)((cell->Y1()/fInf->GetEcalSize(1))*fCY+fCY/2.0); - Int_t yi2=(Int_t)((cell->Y2()/fInf->GetEcalSize(1))*fCY+fCY/2.0); - for(Int_t x=xi1;x<=xi2;x++) - for(Int_t y=yi1;y<=yi2;y++) - if (x==xi1||y==yi1||x==xi2||y==yi2) - PutPixel(x, y, fEdging); - else - PutPixel(x, y, color); - + Int_t xi1 = (Int_t)((cell->X1() / fInf->GetEcalSize(0)) * fCX + fCX / 2.0); + Int_t xi2 = (Int_t)((cell->X2() / fInf->GetEcalSize(0)) * fCX + fCX / 2.0); + Int_t yi1 = (Int_t)((cell->Y1() / fInf->GetEcalSize(1)) * fCY + fCY / 2.0); + Int_t yi2 = (Int_t)((cell->Y2() / fInf->GetEcalSize(1)) * fCY + fCY / 2.0); + for (Int_t x = xi1; x <= xi2; x++) + for (Int_t y = yi1; y <= yi2; y++) + if (x == xi1 || y == yi1 || x == xi2 || y == yi2) + PutPixel(x, y, fEdging); + else + PutPixel(x, y, color); } void ecalDrawer::DrawMark(Double_t x, Double_t y, const char* color, Int_t type) { - Int_t xi=(Int_t)((x/fInf->GetEcalSize(0))*fCX+fCX/2.0); - Int_t yi=(Int_t)((y/fInf->GetEcalSize(1))*fCY+fCY/2.0); - PutPixel(xi-1, yi-1, color); - PutPixel(xi , yi-1, color); - PutPixel(xi+1, yi-1, color); - PutPixel(xi-1, yi , color); - PutPixel(xi , yi , color); - PutPixel(xi+1, yi , color); - PutPixel(xi-1, yi+1, color); - PutPixel(xi , yi+1, color); - PutPixel(xi+1, yi+1, color); - if (type==1) return; - PutPixel(xi-2, yi-2, color); - PutPixel(xi+2, yi-2, color); - PutPixel(xi-2, yi+2, color); - PutPixel(xi+2, yi+2, color); - PutPixel(xi , yi-2, color); - PutPixel(xi-2, yi , color); - PutPixel(xi , yi+2, color); - PutPixel(xi+2, yi , color); - PutPixel(xi , yi-3, color); - PutPixel(xi-3, yi , color); - PutPixel(xi , yi+3, color); - PutPixel(xi+3, yi , color); + Int_t xi = (Int_t)((x / fInf->GetEcalSize(0)) * fCX + fCX / 2.0); + Int_t yi = (Int_t)((y / fInf->GetEcalSize(1)) * fCY + fCY / 2.0); + PutPixel(xi - 1, yi - 1, color); + PutPixel(xi, yi - 1, color); + PutPixel(xi + 1, yi - 1, color); + PutPixel(xi - 1, yi, color); + PutPixel(xi, yi, color); + PutPixel(xi + 1, yi, color); + PutPixel(xi - 1, yi + 1, color); + PutPixel(xi, yi + 1, color); + PutPixel(xi + 1, yi + 1, color); + if (type == 1) + return; + PutPixel(xi - 2, yi - 2, color); + PutPixel(xi + 2, yi - 2, color); + PutPixel(xi - 2, yi + 2, color); + PutPixel(xi + 2, yi + 2, color); + PutPixel(xi, yi - 2, color); + PutPixel(xi - 2, yi, color); + PutPixel(xi, yi + 2, color); + PutPixel(xi + 2, yi, color); + PutPixel(xi, yi - 3, color); + PutPixel(xi - 3, yi, color); + PutPixel(xi, yi + 3, color); + PutPixel(xi + 3, yi, color); } void ecalDrawer::DrawImage() { - TString name=fNamePrefix; - if (fEventN<10) name+="0"; - if (fEventN<100) name+="0"; - if (fEventN<1000) name+="0"; - name+=fEventN; - fC->FillRectangle("#000000", 0, 0, fCX, fCY); - fEdging="#FFFFFF"; - DrawCells(); - DrawMC(); -// DrawTracks(); -// DrawPhotons(); - /** some beauty **/ - /* - PutPixel((Int_t)(fCX/2.0+ 0), (Int_t)(fCY/2.0+ 0), "#FFFFFF"); - PutPixel((Int_t)(fCX/2.0+ 0), (Int_t)(fCY/2.0+ 1), "#FFFFFF"); - PutPixel((Int_t)(fCX/2.0+ 0), (Int_t)(fCY/2.0+ 3), "#FFFFFF"); - PutPixel((Int_t)(fCX/2.0+ 0), (Int_t)(fCY/2.0+ 4), "#FFFFFF"); - PutPixel((Int_t)(fCX/2.0+ 1), (Int_t)(fCY/2.0+ 2), "#FFFFFF"); - PutPixel((Int_t)(fCX/2.0+ 2), (Int_t)(fCY/2.0+ 0), "#FFFFFF"); - PutPixel((Int_t)(fCX/2.0+ 2), (Int_t)(fCY/2.0+ 1), "#FFFFFF"); - PutPixel((Int_t)(fCX/2.0+ 2), (Int_t)(fCY/2.0+ 3), "#FFFFFF"); - PutPixel((Int_t)(fCX/2.0+ 2), (Int_t)(fCY/2.0+ 4), "#FFFFFF"); - PutPixel((Int_t)(fCX/2.0+ 4), (Int_t)(fCY/2.0+ 0), "#FFFFFF"); - PutPixel((Int_t)(fCX/2.0+ 4), (Int_t)(fCY/2.0+ 3), "#FFFFFF"); - PutPixel((Int_t)(fCX/2.0+ 4), (Int_t)(fCY/2.0+ 4), "#FFFFFF"); - PutPixel((Int_t)(fCX/2.0+ 5), (Int_t)(fCY/2.0+ 0), "#FFFFFF"); - PutPixel((Int_t)(fCX/2.0+ 5), (Int_t)(fCY/2.0+ 2), "#FFFFFF"); - PutPixel((Int_t)(fCX/2.0+ 6), (Int_t)(fCY/2.0+ 1), "#FFFFFF"); - PutPixel((Int_t)(fCX/2.0+ 6), (Int_t)(fCY/2.0+ 2), "#FFFFFF"); - PutPixel((Int_t)(fCX/2.0+ 6), (Int_t)(fCY/2.0+ 3), "#FFFFFF"); - PutPixel((Int_t)(fCX/2.0+ 6), (Int_t)(fCY/2.0+ 4), "#FFFFFF"); - PutPixel((Int_t)(fCX/2.0+ 8), (Int_t)(fCY/2.0+ 0), "#FFFFFF"); - PutPixel((Int_t)(fCX/2.0+ 8), (Int_t)(fCY/2.0+ 1), "#FFFFFF"); - PutPixel((Int_t)(fCX/2.0+ 8), (Int_t)(fCY/2.0+ 2), "#FFFFFF"); - PutPixel((Int_t)(fCX/2.0+ 8), (Int_t)(fCY/2.0+ 3), "#FFFFFF"); - PutPixel((Int_t)(fCX/2.0+ 8), (Int_t)(fCY/2.0+ 4), "#FFFFFF"); - PutPixel((Int_t)(fCX/2.0+ 9), (Int_t)(fCY/2.0+ 1), "#FFFFFF"); - PutPixel((Int_t)(fCX/2.0+ 9), (Int_t)(fCY/2.0+ 6), "#FFFFFF"); - PutPixel((Int_t)(fCX/2.0+10), (Int_t)(fCY/2.0+ 2), "#FFFFFF"); - PutPixel((Int_t)(fCX/2.0+10), (Int_t)(fCY/2.0+ 6), "#FFFFFF"); - PutPixel((Int_t)(fCX/2.0+11), (Int_t)(fCY/2.0+ 0), "#FFFFFF"); - PutPixel((Int_t)(fCX/2.0+11), (Int_t)(fCY/2.0+ 1), "#FFFFFF"); - PutPixel((Int_t)(fCX/2.0+11), (Int_t)(fCY/2.0+ 2), "#FFFFFF"); - PutPixel((Int_t)(fCX/2.0+11), (Int_t)(fCY/2.0+ 3), "#FFFFFF"); - PutPixel((Int_t)(fCX/2.0+11), (Int_t)(fCY/2.0+ 4), "#FFFFFF"); - */ - fC->WriteImage(name+".png", TImage::kPng); + TString name = fNamePrefix; + if (fEventN < 10) + name += "0"; + if (fEventN < 100) + name += "0"; + if (fEventN < 1000) + name += "0"; + name += fEventN; + fC->FillRectangle("#000000", 0, 0, fCX, fCY); + fEdging = "#FFFFFF"; + DrawCells(); + DrawMC(); + // DrawTracks(); + // DrawPhotons(); + /** some beauty **/ + /* + PutPixel((Int_t)(fCX/2.0+ 0), (Int_t)(fCY/2.0+ 0), "#FFFFFF"); + PutPixel((Int_t)(fCX/2.0+ 0), (Int_t)(fCY/2.0+ 1), "#FFFFFF"); + PutPixel((Int_t)(fCX/2.0+ 0), (Int_t)(fCY/2.0+ 3), "#FFFFFF"); + PutPixel((Int_t)(fCX/2.0+ 0), (Int_t)(fCY/2.0+ 4), "#FFFFFF"); + PutPixel((Int_t)(fCX/2.0+ 1), (Int_t)(fCY/2.0+ 2), "#FFFFFF"); + PutPixel((Int_t)(fCX/2.0+ 2), (Int_t)(fCY/2.0+ 0), "#FFFFFF"); + PutPixel((Int_t)(fCX/2.0+ 2), (Int_t)(fCY/2.0+ 1), "#FFFFFF"); + PutPixel((Int_t)(fCX/2.0+ 2), (Int_t)(fCY/2.0+ 3), "#FFFFFF"); + PutPixel((Int_t)(fCX/2.0+ 2), (Int_t)(fCY/2.0+ 4), "#FFFFFF"); + PutPixel((Int_t)(fCX/2.0+ 4), (Int_t)(fCY/2.0+ 0), "#FFFFFF"); + PutPixel((Int_t)(fCX/2.0+ 4), (Int_t)(fCY/2.0+ 3), "#FFFFFF"); + PutPixel((Int_t)(fCX/2.0+ 4), (Int_t)(fCY/2.0+ 4), "#FFFFFF"); + PutPixel((Int_t)(fCX/2.0+ 5), (Int_t)(fCY/2.0+ 0), "#FFFFFF"); + PutPixel((Int_t)(fCX/2.0+ 5), (Int_t)(fCY/2.0+ 2), "#FFFFFF"); + PutPixel((Int_t)(fCX/2.0+ 6), (Int_t)(fCY/2.0+ 1), "#FFFFFF"); + PutPixel((Int_t)(fCX/2.0+ 6), (Int_t)(fCY/2.0+ 2), "#FFFFFF"); + PutPixel((Int_t)(fCX/2.0+ 6), (Int_t)(fCY/2.0+ 3), "#FFFFFF"); + PutPixel((Int_t)(fCX/2.0+ 6), (Int_t)(fCY/2.0+ 4), "#FFFFFF"); + PutPixel((Int_t)(fCX/2.0+ 8), (Int_t)(fCY/2.0+ 0), "#FFFFFF"); + PutPixel((Int_t)(fCX/2.0+ 8), (Int_t)(fCY/2.0+ 1), "#FFFFFF"); + PutPixel((Int_t)(fCX/2.0+ 8), (Int_t)(fCY/2.0+ 2), "#FFFFFF"); + PutPixel((Int_t)(fCX/2.0+ 8), (Int_t)(fCY/2.0+ 3), "#FFFFFF"); + PutPixel((Int_t)(fCX/2.0+ 8), (Int_t)(fCY/2.0+ 4), "#FFFFFF"); + PutPixel((Int_t)(fCX/2.0+ 9), (Int_t)(fCY/2.0+ 1), "#FFFFFF"); + PutPixel((Int_t)(fCX/2.0+ 9), (Int_t)(fCY/2.0+ 6), "#FFFFFF"); + PutPixel((Int_t)(fCX/2.0+10), (Int_t)(fCY/2.0+ 2), "#FFFFFF"); + PutPixel((Int_t)(fCX/2.0+10), (Int_t)(fCY/2.0+ 6), "#FFFFFF"); + PutPixel((Int_t)(fCX/2.0+11), (Int_t)(fCY/2.0+ 0), "#FFFFFF"); + PutPixel((Int_t)(fCX/2.0+11), (Int_t)(fCY/2.0+ 1), "#FFFFFF"); + PutPixel((Int_t)(fCX/2.0+11), (Int_t)(fCY/2.0+ 2), "#FFFFFF"); + PutPixel((Int_t)(fCX/2.0+11), (Int_t)(fCY/2.0+ 3), "#FFFFFF"); + PutPixel((Int_t)(fCX/2.0+11), (Int_t)(fCY/2.0+ 4), "#FFFFFF"); + */ + fC->WriteImage(name + ".png", TImage::kPng); } -void ecalDrawer::DrawLine(Double_t x1, Double_t y1, Double_t x2, Double_t y2,const char* color) +void ecalDrawer::DrawLine(Double_t x1, Double_t y1, Double_t x2, Double_t y2, const char* color) { - Int_t x1i=(Int_t)((x1/fInf->GetEcalSize(0))*fCX+fCX/2.0); - Int_t y1i=(Int_t)((y1/fInf->GetEcalSize(1))*fCY+fCY/2.0); - Int_t x2i=(Int_t)((x2/fInf->GetEcalSize(0))*fCX+fCX/2.0); - Int_t y2i=(Int_t)((y2/fInf->GetEcalSize(1))*fCY+fCY/2.0); - if (x1i<0) x1i=0; - if (x1i>=fCX) x1i=fCX-1; - if (x2i<0) x2i=0; - if (x2i>=fCX) x2i=fCX-1; - if (y1i<0) y1i=0; - if (y1i>=fCY) y1i=fCY-1; - if (y2i<0) y2i=0; - if (y2i>=fCY) y2i=fCY-1; - y1i=fCY-y1i-1; - y2i=fCY-y2i-1; - fC->DrawLine(x1i, y1i, x2i, y2i, color); + Int_t x1i = (Int_t)((x1 / fInf->GetEcalSize(0)) * fCX + fCX / 2.0); + Int_t y1i = (Int_t)((y1 / fInf->GetEcalSize(1)) * fCY + fCY / 2.0); + Int_t x2i = (Int_t)((x2 / fInf->GetEcalSize(0)) * fCX + fCX / 2.0); + Int_t y2i = (Int_t)((y2 / fInf->GetEcalSize(1)) * fCY + fCY / 2.0); + if (x1i < 0) + x1i = 0; + if (x1i >= fCX) + x1i = fCX - 1; + if (x2i < 0) + x2i = 0; + if (x2i >= fCX) + x2i = fCX - 1; + if (y1i < 0) + y1i = 0; + if (y1i >= fCY) + y1i = fCY - 1; + if (y2i < 0) + y2i = 0; + if (y2i >= fCY) + y2i = fCY - 1; + y1i = fCY - y1i - 1; + y2i = fCY - y2i - 1; + fC->DrawLine(x1i, y1i, x2i, y2i, color); } void ecalDrawer::DrawLine(Double_t x, Double_t y, const char* color, Int_t track) { - if (track==-1111) return; - Int_t i=0; - Int_t n=fPoints->GetEntriesFast(); - ecalPoint* pt; - - for(i=0;iAt(i); - if (pt->GetTrackID()==track) break; - } - if (i==n) return; - DrawLine(x, y, pt->GetX(), pt->GetY(), color); + if (track == -1111) + return; + Int_t i = 0; + Int_t n = fPoints->GetEntriesFast(); + ecalPoint* pt; + + for (i = 0; i < n; i++) { + pt = (ecalPoint*)fPoints->At(i); + if (pt->GetTrackID() == track) + break; + } + if (i == n) + return; + DrawLine(x, y, pt->GetX(), pt->GetY(), color); } /* @@ -237,423 +256,422 @@ void ecalDrawer::DrawTracks() */ Double_t ecalDrawer::GetP(ecalPoint* p) { - Double_t px=p->GetPx(); - Double_t py=p->GetPy(); - Double_t pz=p->GetPz(); + Double_t px = p->GetPx(); + Double_t py = p->GetPy(); + Double_t pz = p->GetPz(); - return TMath::Sqrt(px*px+py*py+pz*pz); + return TMath::Sqrt(px * px + py * py + pz * pz); } - /** Draw chi2 for photons **/ +/** Draw chi2 for photons **/ void ecalDrawer::DrawChi2(Float_t x, Float_t y, Float_t chi2, const char* color) { - char stri[30]; - Int_t xi=(Int_t)((x/fInf->GetEcalSize(0))*fCX+fCX/2.0); - Int_t yi=(Int_t)((y/fInf->GetEcalSize(1))*fCY+fCY/2.0); - yi-=8; - yi=fCY-yi-1; - xi-=6; - - if (chi2!=-1111) - { - sprintf(stri,"%.1f", chi2); - fC->DrawText(xi, yi, stri, 8, color, "arialbd.ttf"); - } - else - fC->DrawText(xi, yi, "-111", 8, color, "arialbd.ttf"); + char stri[30]; + Int_t xi = (Int_t)((x / fInf->GetEcalSize(0)) * fCX + fCX / 2.0); + Int_t yi = (Int_t)((y / fInf->GetEcalSize(1)) * fCY + fCY / 2.0); + yi -= 8; + yi = fCY - yi - 1; + xi -= 6; + + if (chi2 != -1111) { + sprintf(stri, "%.1f", chi2); + fC->DrawText(xi, yi, stri, 8, color, "arialbd.ttf"); + } else + fC->DrawText(xi, yi, "-111", 8, color, "arialbd.ttf"); } - void ecalDrawer::DrawEnergy(ecalPoint* p, const char* color) { - if (GetP(p)<0.01) return; - char stri[10]; - Int_t x=(Int_t)((p->GetX()/fInf->GetEcalSize(0))*fCX+fCX/2.0); - Int_t y=(Int_t)((p->GetY()/fInf->GetEcalSize(1))*fCY+fCY/2.0); - y+=9; - y=fCY-y-1; - x-=6; - - sprintf(stri,"%.2f", GetP(p)); - if (stri[0]=='0') - { - x+=2; - stri[0]=stri[1]; - stri[1]=stri[2]; - stri[2]=stri[3]; - stri[3]=stri[4]; - stri[4]=stri[5]; - stri[5]=stri[6]; - stri[6]=stri[7]; - } - fC->DrawText(x, y, stri, 8, color, "arialbd.ttf"); + if (GetP(p) < 0.01) + return; + char stri[10]; + Int_t x = (Int_t)((p->GetX() / fInf->GetEcalSize(0)) * fCX + fCX / 2.0); + Int_t y = (Int_t)((p->GetY() / fInf->GetEcalSize(1)) * fCY + fCY / 2.0); + y += 9; + y = fCY - y - 1; + x -= 6; + + sprintf(stri, "%.2f", GetP(p)); + if (stri[0] == '0') { + x += 2; + stri[0] = stri[1]; + stri[1] = stri[2]; + stri[2] = stri[3]; + stri[3] = stri[4]; + stri[4] = stri[5]; + stri[5] = stri[6]; + stri[6] = stri[7]; + } + fC->DrawText(x, y, stri, 8, color, "arialbd.ttf"); } void ecalDrawer::DrawPDG(ecalPoint* p, const char* color) { - char stri[30]; - Int_t xi=(Int_t)((p->GetX()/fInf->GetEcalSize(0))*fCX+fCX/2.0); - Int_t yi=(Int_t)((p->GetY()/fInf->GetEcalSize(1))*fCY+fCY/2.0); - yi-=8; - yi=fCY-yi-1; - xi-=6; - - sprintf(stri,"%d", p->GetPdgCode()); - fC->DrawText(xi, yi, stri, 8, color, "arialbd.ttf"); + char stri[30]; + Int_t xi = (Int_t)((p->GetX() / fInf->GetEcalSize(0)) * fCX + fCX / 2.0); + Int_t yi = (Int_t)((p->GetY() / fInf->GetEcalSize(1)) * fCY + fCY / 2.0); + yi -= 8; + yi = fCY - yi - 1; + xi -= 6; + + sprintf(stri, "%d", p->GetPdgCode()); + fC->DrawText(xi, yi, stri, 8, color, "arialbd.ttf"); } - void ecalDrawer::DrawEnergy(Float_t x, Float_t y, Float_t p, const char* color) { - if (p<0.01) return; - char stri[10]; - Int_t xi=(Int_t)((x/fInf->GetEcalSize(0))*fCX+fCX/2.0); - Int_t yi=(Int_t)((y/fInf->GetEcalSize(1))*fCY+fCY/2.0); - yi-=2; - yi=fCY-yi-1; - xi-=6; - - sprintf(stri,"%.2f", p); - fC->DrawText(xi, yi, stri, 8, color, "arialbd.ttf"); + if (p < 0.01) + return; + char stri[10]; + Int_t xi = (Int_t)((x / fInf->GetEcalSize(0)) * fCX + fCX / 2.0); + Int_t yi = (Int_t)((y / fInf->GetEcalSize(1)) * fCY + fCY / 2.0); + yi -= 2; + yi = fCY - yi - 1; + xi -= 6; + + sprintf(stri, "%.2f", p); + fC->DrawText(xi, yi, stri, 8, color, "arialbd.ttf"); } void ecalDrawer::DrawMC() { - Int_t i; - Int_t pn=fPoints->GetEntriesFast(); - ecalPoint* p; - - - for(i=0;iAt(i); - if (!p) continue; - /** gammas **/ - if (p->GetPdgCode()==22) - { - DrawMark(p->GetX(), p->GetY(), "#00FF00", 1); - DrawEnergy(p, "#00FF00"); - continue; - } - if (TMath::Abs(p->GetPdgCode())==11) - { - DrawMark(p->GetX(), p->GetY(), "#FFFF00", 1); - DrawEnergy(p, "#FFFF00"); - continue; + Int_t i; + Int_t pn = fPoints->GetEntriesFast(); + ecalPoint* p; + + for (i = 0; i < pn; i++) { + p = (ecalPoint*)fPoints->At(i); + if (!p) + continue; + /** gammas **/ + if (p->GetPdgCode() == 22) { + DrawMark(p->GetX(), p->GetY(), "#00FF00", 1); + DrawEnergy(p, "#00FF00"); + continue; + } + if (TMath::Abs(p->GetPdgCode()) == 11) { + DrawMark(p->GetX(), p->GetY(), "#FFFF00", 1); + DrawEnergy(p, "#FFFF00"); + continue; + } + /** Neutrons and antineutrons **/ + if (TMath::Abs(p->GetPdgCode()) == 2112) { + DrawMark(p->GetX(), p->GetY(), "#FF00FF", 1); + DrawEnergy(p, "#FF00FF"); + continue; + } + /** others **/ + DrawMark(p->GetX(), p->GetY(), "#FF0000", 1); + DrawEnergy(p, "#FF0000"); + DrawPDG(p, "#FF0000"); } - /** Neutrons and antineutrons **/ - if (TMath::Abs(p->GetPdgCode())==2112) - { - DrawMark(p->GetX(), p->GetY(), "#FF00FF", 1); - DrawEnergy(p, "#FF00FF"); - continue; - } - /** others **/ - DrawMark(p->GetX(), p->GetY(), "#FF0000", 1); - DrawEnergy(p, "#FF0000"); - DrawPDG(p, "#FF0000"); - } } void ecalDrawer::DrawCells() { - list::const_iterator p; - list clusters; - list maximums; - list::const_iterator cp; - ShipMCTrack* tr; - ShipMCTrack* tq; - Float_t max; - std::map::const_iterator p1; - ecalCellMC* c; - Int_t rn=fClusters->GetEntriesFast(); - Int_t i; - Int_t j; - Float_t x; - Float_t y; - Float_t dx; - Float_t dy; - Float_t rad; - Float_t phi; - - clusters.clear(); - - for(i=0;iAt(i); - for(j=0;jSize();j++) - clusters.push_back(fStr->GetHitCell(cl->CellNum(j))); - for(j=0;jMaxs();j++) - maximums.push_back(fStr->GetHitCell(cl->PeakNum(j))); - } + list::const_iterator p; + list clusters; + list maximums; + list::const_iterator cp; + ShipMCTrack* tr; + ShipMCTrack* tq; + Float_t max; + std::map::const_iterator p1; + ecalCellMC* c; + Int_t rn = fClusters->GetEntriesFast(); + Int_t i; + Int_t j; + Float_t x; + Float_t y; + Float_t dx; + Float_t dy; + Float_t rad; + Float_t phi; + + clusters.clear(); + + for (i = 0; i < rn; i++) { + ecalCluster* cl = (ecalCluster*)fClusters->At(i); + for (j = 0; j < cl->Size(); j++) + clusters.push_back(fStr->GetHitCell(cl->CellNum(j))); + for (j = 0; j < cl->Maxs(); j++) + maximums.push_back(fStr->GetHitCell(cl->PeakNum(j))); + } - for(p=fCells.begin();p!=fCells.end();++p) - { - c=(ecalCellMC*)((*p)->fCell); - (*p)->fG=c->GetEnergy(); - (*p)->fR=0; - (*p)->fB=0; - } -/* - for(p=fCells.begin();p!=fCells.end();++p) - { - c=(ecalCellMC*)((*p)->fCell); - (*p)->fG=c->GetEnergy(); - (*p)->fR=0; - (*p)->fB=0; - for(p1=c->GetTrackEnergyBegin();p1!=c->GetTrackEnergyEnd();++p1) - { - tr=(ShipMCTrack*)fMCTracks->At(p1->first); - if (tr==NULL) continue; - if (tr->GetPdgCode()==22) - (*p)->fR+=p1->second; - else - if (tr->GetMotherId()>=0) + for (p = fCells.begin(); p != fCells.end(); ++p) { + c = (ecalCellMC*)((*p)->fCell); + (*p)->fG = c->GetEnergy(); + (*p)->fR = 0; + (*p)->fB = 0; + } + /* + for(p=fCells.begin();p!=fCells.end();++p) { - tq=(ShipMCTrack*)fMCTracks->At(tr->GetMotherId()); - if (tr->GetMotherId()==22) - (*p)->fR+=p1->second; + c=(ecalCellMC*)((*p)->fCell); + (*p)->fG=c->GetEnergy(); + (*p)->fR=0; + (*p)->fB=0; + for(p1=c->GetTrackEnergyBegin();p1!=c->GetTrackEnergyEnd();++p1) + { + tr=(ShipMCTrack*)fMCTracks->At(p1->first); + if (tr==NULL) continue; + if (tr->GetPdgCode()==22) + (*p)->fR+=p1->second; + else + if (tr->GetMotherId()>=0) + { + tq=(ShipMCTrack*)fMCTracks->At(tr->GetMotherId()); + if (tr->GetMotherId()==22) + (*p)->fR+=p1->second; + } + } + if (find(clusters.begin(), clusters.end(), c)==clusters.end()) + continue; + for(i=0;iAt(i); + dx=x=c->GetCenterX(); + dy=y=c->GetCenterY(); + dx-=r->X(); + dy-=r->Y(); + if (TMath::Abs(dx)>30) continue; + if (TMath::Abs(dy)>30) continue; + rad=TMath::Sqrt(x*x+y*y); + phi=TMath::ACos(x/rad)*TMath::RadToDeg(); + if (y<0) phi=360-phi; + // (*p)->fB+=fShLib->GetResponse(dx, dy, phi, TMath::ATan(rad/fInf->GetZPos())*TMath::RadToDeg(), + c->GetType()); + } } + */ + /** Normalization **/ + max = 0; + for (p = fCells.begin(); p != fCells.end(); ++p) { + if (max < (*p)->fR) + max = (*p)->fR; + if (max < (*p)->fG) + max = (*p)->fG; + if (max < (*p)->fB) + max = (*p)->fB; } - if (find(clusters.begin(), clusters.end(), c)==clusters.end()) - continue; - for(i=0;iAt(i); - dx=x=c->GetCenterX(); - dy=y=c->GetCenterY(); - dx-=r->X(); - dy-=r->Y(); - if (TMath::Abs(dx)>30) continue; - if (TMath::Abs(dy)>30) continue; - rad=TMath::Sqrt(x*x+y*y); - phi=TMath::ACos(x/rad)*TMath::RadToDeg(); - if (y<0) phi=360-phi; -// (*p)->fB+=fShLib->GetResponse(dx, dy, phi, TMath::ATan(rad/fInf->GetZPos())*TMath::RadToDeg(), c->GetType()); - } - } -*/ - /** Normalization **/ - max=0; - for(p=fCells.begin();p!=fCells.end();++p) - { - if (max<(*p)->fR) max=(*p)->fR; - if (max<(*p)->fG) max=(*p)->fG; - if (max<(*p)->fB) max=(*p)->fB; - } - if (max>0) - for(p=fCells.begin();p!=fCells.end();++p) - { - (*p)->fR/=max; - (*p)->fG/=max; - (*p)->fB/=max; - } - - /** At the moment - ** B --- reconstructed energy - ** G --- energy deposited in cell - ** R --- energy deposited by photons and their e+/e- daughters **/ - for(p=fCells.begin();p!=fCells.end();++p) - { - Float_t l=(*p)->fG; l=TMath::Sqrt(l); - Float_t a=0; - Float_t b=((*p)->fG-(*p)->fB)/((*p)->fG+(*p)->fB); - if ((*p)->fB==0) { b=0; } - else - { - if (b<-0.7) b=-0.7; - if (b>0.7) b=0.7; + if (max > 0) + for (p = fCells.begin(); p != fCells.end(); ++p) { + (*p)->fR /= max; + (*p)->fG /= max; + (*p)->fB /= max; + } + + /** At the moment + ** B --- reconstructed energy + ** G --- energy deposited in cell + ** R --- energy deposited by photons and their e+/e- daughters **/ + for (p = fCells.begin(); p != fCells.end(); ++p) { + Float_t l = (*p)->fG; + l = TMath::Sqrt(l); + Float_t a = 0; + Float_t b = ((*p)->fG - (*p)->fB) / ((*p)->fG + (*p)->fB); + if ((*p)->fB == 0) { + b = 0; + } else { + if (b < -0.7) + b = -0.7; + if (b > 0.7) + b = 0.7; + } + LabToRGB(l, b, a, (*p)->fR, (*p)->fG, (*p)->fB); } - LabToRGB(l, b, a, (*p)->fR, (*p)->fG, (*p)->fB); - } - /** Drawing **/ - fEdging="#FFFFFF"; - for(p=fCells.begin();p!=fCells.end();++p) - if (find(clusters.begin(), clusters.end(), (*p)->fCell)==clusters.end()) - DrawCell((*p)->fCell, (*p)->fR, (*p)->fG, (*p)->fB); - fEdging="#FF0000"; - for(p=fCells.begin();p!=fCells.end();++p) - if (find(clusters.begin(), clusters.end(), (*p)->fCell)!=clusters.end()) - DrawCell((*p)->fCell, (*p)->fR, (*p)->fG, (*p)->fB); - fEdging="#00FF00"; - for(p=fCells.begin();p!=fCells.end();++p) - if (find(maximums.begin(), maximums.end(), (*p)->fCell)!=maximums.end()) - DrawCell((*p)->fCell, (*p)->fR, (*p)->fG, (*p)->fB); + /** Drawing **/ + fEdging = "#FFFFFF"; + for (p = fCells.begin(); p != fCells.end(); ++p) + if (find(clusters.begin(), clusters.end(), (*p)->fCell) == clusters.end()) + DrawCell((*p)->fCell, (*p)->fR, (*p)->fG, (*p)->fB); + fEdging = "#FF0000"; + for (p = fCells.begin(); p != fCells.end(); ++p) + if (find(clusters.begin(), clusters.end(), (*p)->fCell) != clusters.end()) + DrawCell((*p)->fCell, (*p)->fR, (*p)->fG, (*p)->fB); + fEdging = "#00FF00"; + for (p = fCells.begin(); p != fCells.end(); ++p) + if (find(maximums.begin(), maximums.end(), (*p)->fCell) != maximums.end()) + DrawCell((*p)->fCell, (*p)->fR, (*p)->fG, (*p)->fB); } /** Init **/ InitStatus ecalDrawer::Init() { - fEventN=0; - + fEventN = 0; - FairRootManager* io=FairRootManager::Instance(); - if (!io) - { - Fatal("Init", "Can't find IOManager."); - return kFATAL; - } - fMCTracks=(TClonesArray*)io->GetObject("MCTrack"); - if (!fMCTracks) - { - Fatal("Init", "Can't find array of MC tracks"); - return kFATAL; - } - fPoints=(TClonesArray*)io->GetObject("EcalPoint"); - if (!fPoints) - { - Fatal("Init", "Can't find array of Ecal Points"); - return kFATAL; - } - fStr=(ecalStructure*)io->GetObject("EcalStructure"); - if (!fStr) - { - Fatal("Init", "Can't find calorimeter structure for drawing"); - return kFATAL; - } - fClusters=(TClonesArray*)io->GetObject("EcalClusters"); - if (!fClusters) - { - Fatal("Init", "Can't find array of calorimeter clusters"); - return kFATAL; - } - fInf=fStr->GetEcalInf(); - fCX=fInf->GetXSize(); fCY=fInf->GetYSize(); - fCX*=fCellSize*4+4; fCX+=1; - fCY*=fCellSize*4+4; fCY+=1; - fC=new TASImage(fCX, fCY); - - list cells; - list::const_iterator p; - fStr->GetCells(cells); - for(p=cells.begin();p!=cells.end();++p) - fCells.push_back(new ecalDrawerItem((*p), 0.0, 0.0, 0.0)); - fTxt->SetTextFont(43); - fTxt->SetTextSizePixels(8); - fTxt->SetTextAlign(21); - return kSUCCESS; + FairRootManager* io = FairRootManager::Instance(); + if (!io) { + Fatal("Init", "Can't find IOManager."); + return kFATAL; + } + fMCTracks = (TClonesArray*)io->GetObject("MCTrack"); + if (!fMCTracks) { + Fatal("Init", "Can't find array of MC tracks"); + return kFATAL; + } + fPoints = (TClonesArray*)io->GetObject("EcalPoint"); + if (!fPoints) { + Fatal("Init", "Can't find array of Ecal Points"); + return kFATAL; + } + fStr = (ecalStructure*)io->GetObject("EcalStructure"); + if (!fStr) { + Fatal("Init", "Can't find calorimeter structure for drawing"); + return kFATAL; + } + fClusters = (TClonesArray*)io->GetObject("EcalClusters"); + if (!fClusters) { + Fatal("Init", "Can't find array of calorimeter clusters"); + return kFATAL; + } + fInf = fStr->GetEcalInf(); + fCX = fInf->GetXSize(); + fCY = fInf->GetYSize(); + fCX *= fCellSize * 4 + 4; + fCX += 1; + fCY *= fCellSize * 4 + 4; + fCY += 1; + fC = new TASImage(fCX, fCY); + + list cells; + list::const_iterator p; + fStr->GetCells(cells); + for (p = cells.begin(); p != cells.end(); ++p) + fCells.push_back(new ecalDrawerItem((*p), 0.0, 0.0, 0.0)); + fTxt->SetTextFont(43); + fTxt->SetTextSizePixels(8); + fTxt->SetTextAlign(21); + return kSUCCESS; } -Int_t ecalDrawer::InitPython(TClonesArray* mctracks, TClonesArray* ecalPoints, ecalStructure* structure, TClonesArray* clusters) +Int_t ecalDrawer::InitPython(TClonesArray* mctracks, + TClonesArray* ecalPoints, + ecalStructure* structure, + TClonesArray* clusters) { - fMCTracks=mctracks; - if (fMCTracks==NULL) return -1111; - fPoints=ecalPoints; - if (fPoints==NULL) return -1111; - fStr=structure; - if (fStr==NULL) return -1111; - fClusters=clusters; - if (fClusters==NULL) return -1111; - - fInf=fStr->GetEcalInf(); - fCX=fInf->GetXSize(); fCY=fInf->GetYSize(); - fCX*=fCellSize*4+4; fCX+=1; - fCY*=fCellSize*4+4; fCY+=1; - fC=new TASImage(fCX, fCY); - - list cells; - list::const_iterator p; - fStr->GetCells(cells); - for(p=cells.begin();p!=cells.end();++p) - fCells.push_back(new ecalDrawerItem((*p), 0.0, 0.0, 0.0)); - fTxt->SetTextFont(43); - fTxt->SetTextSizePixels(8); - fTxt->SetTextAlign(21); - - return 0; + fMCTracks = mctracks; + if (fMCTracks == NULL) + return -1111; + fPoints = ecalPoints; + if (fPoints == NULL) + return -1111; + fStr = structure; + if (fStr == NULL) + return -1111; + fClusters = clusters; + if (fClusters == NULL) + return -1111; + + fInf = fStr->GetEcalInf(); + fCX = fInf->GetXSize(); + fCY = fInf->GetYSize(); + fCX *= fCellSize * 4 + 4; + fCX += 1; + fCY *= fCellSize * 4 + 4; + fCY += 1; + fC = new TASImage(fCX, fCY); + + list cells; + list::const_iterator p; + fStr->GetCells(cells); + for (p = cells.begin(); p != cells.end(); ++p) + fCells.push_back(new ecalDrawerItem((*p), 0.0, 0.0, 0.0)); + fTxt->SetTextFont(43); + fTxt->SetTextSizePixels(8); + fTxt->SetTextAlign(21); + + return 0; } void ecalDrawer::Finish() { - ; + ; } - /** Destructor **/ ecalDrawer::~ecalDrawer() { - list::const_iterator p=fCells.begin(); - for(;p!=fCells.end();++p) - delete (*p); - delete fTxt; + list::const_iterator p = fCells.begin(); + for (; p != fCells.end(); ++p) + delete (*p); + delete fTxt; } /** Standard constructor **/ -ecalDrawer::ecalDrawer(const char *name, const Int_t iVerbose) - : FairTask(name, iVerbose), - fNamePrefix("ecal"), - fC(NULL), - fCellSize(8), - fCX(0), - fCY(0), - fMaxEnergyDep(0.), - fStr(NULL), - fInf(NULL), - fEdging(""), - fTxt(new TText()), - fCells(), - fMCTracks(NULL), - fPoints(NULL), - fClusters(NULL), - fInName("EcalReco"), - fEventN(0), - fX(0.), - fY(0.), - fZ(0.), - fMCX(0.), - fMCY(0.), - fMCZ(0.), - fMCMotherTrN(0), - fE(0.), - fMCE(0.), - fPX(0.), - fPY(0.), - fPZ(0.), - fMCPX(0.), - fMCPY(0.), - fMCPZ(0.), - fChi2(0.), - fPdgCode(0), - fR(0.) -{ -} +ecalDrawer::ecalDrawer(const char* name, const Int_t iVerbose) + : FairTask(name, iVerbose) + , fNamePrefix("ecal") + , fC(NULL) + , fCellSize(8) + , fCX(0) + , fCY(0) + , fMaxEnergyDep(0.) + , fStr(NULL) + , fInf(NULL) + , fEdging("") + , fTxt(new TText()) + , fCells() + , fMCTracks(NULL) + , fPoints(NULL) + , fClusters(NULL) + , fInName("EcalReco") + , fEventN(0) + , fX(0.) + , fY(0.) + , fZ(0.) + , fMCX(0.) + , fMCY(0.) + , fMCZ(0.) + , fMCMotherTrN(0) + , fE(0.) + , fMCE(0.) + , fPX(0.) + , fPY(0.) + , fPZ(0.) + , fMCPX(0.) + , fMCPY(0.) + , fMCPZ(0.) + , fChi2(0.) + , fPdgCode(0) + , fR(0.) +{} /** Default constructor. Requirement of ROOT system **/ ecalDrawer::ecalDrawer() - : FairTask(), - fNamePrefix("ecal"), - fC(NULL), - fCellSize(8), - fCX(0), - fCY(0), - fMaxEnergyDep(0.), - fStr(NULL), - fInf(NULL), - fEdging(""), - fTxt(new TText()), - fCells(), - fMCTracks(NULL), - fPoints(NULL), - fClusters(NULL), - fInName("EcalReco"), - fEventN(0), - fX(0.), - fY(0.), - fZ(0.), - fMCX(0.), - fMCY(0.), - fMCZ(0.), - fMCMotherTrN(0), - fE(0.), - fMCE(0.), - fPX(0.), - fPY(0.), - fPZ(0.), - fMCPX(0.), - fMCPY(0.), - fMCPZ(0.), - fChi2(0.), - fPdgCode(0), - fR(0.) -{ -} + : FairTask() + , fNamePrefix("ecal") + , fC(NULL) + , fCellSize(8) + , fCX(0) + , fCY(0) + , fMaxEnergyDep(0.) + , fStr(NULL) + , fInf(NULL) + , fEdging("") + , fTxt(new TText()) + , fCells() + , fMCTracks(NULL) + , fPoints(NULL) + , fClusters(NULL) + , fInName("EcalReco") + , fEventN(0) + , fX(0.) + , fY(0.) + , fZ(0.) + , fMCX(0.) + , fMCY(0.) + , fMCZ(0.) + , fMCMotherTrN(0) + , fE(0.) + , fMCE(0.) + , fPX(0.) + , fPY(0.) + , fPZ(0.) + , fMCPX(0.) + , fMCPY(0.) + , fMCPZ(0.) + , fChi2(0.) + , fPdgCode(0) + , fR(0.) +{} diff --git a/ecal/ecalDrawer.h b/ecal/ecalDrawer.h index c9c8e12ec2..6b660a14bf 100644 --- a/ecal/ecalDrawer.h +++ b/ecal/ecalDrawer.h @@ -8,11 +8,10 @@ #define ECALDRAWER_H #include "FairTask.h" - #include "TString.h" -#include #include +#include class TTree; class TClonesArray; @@ -25,156 +24,205 @@ class ecalCell; class ecalDrawerItem; class ecalPoint; -class ecalDrawer: public FairTask +class ecalDrawer : public FairTask { -public: - /** Default constructor. Requirement of ROOT system **/ - ecalDrawer(); - - /** Standard constructor **/ - ecalDrawer(const char *name, const Int_t iVerbose=1); - - /** Destructor **/ - virtual ~ecalDrawer(); - - /** Set prefix to name of images - ** File will be named like: prefix0000.png **/ - inline void SetNamePrefix(const char* prefix) {fNamePrefix=prefix;} - inline void SetCellSize(Int_t size) {fCellSize=size;} - - Int_t InitPython(TClonesArray* mctracks, TClonesArray* ecalPoints, ecalStructure* structure, TClonesArray* clusters); - /** Init **/ - virtual InitStatus Init(); - virtual void Exec(Option_t* option); - virtual void Finish(); -private: - TString fNamePrefix; //! - /** An image and its size **/ - TASImage* fC; //! - Int_t fCellSize; - Int_t fCX; - Int_t fCY; - - /** Normalization **/ - Double_t fMaxEnergyDep; - /** Structure and info for drawing **/ - ecalStructure* fStr; //! - ecalInf* fInf; //! - TString fEdging; //! - void PutPixel(Int_t x, Int_t y, Float_t r, Float_t g, Float_t b); - void PutPixel(Int_t x, Int_t y, const char* color); - /** type==0 for star, type==1 for square **/ - void DrawMark(Double_t x, Double_t y, const char* color, Int_t type); - /** draw cell with filled color. fEdging used as egding of cell **/ - void DrawCell(ecalCell* cell, Float_t r, Float_t g, Float_t b); - void DrawCell(ecalCell* cell, const char* color); - - void DrawLine(Double_t x, Double_t y, const char* color, Int_t track); - void DrawLine(Double_t x1, Double_t y1, Double_t x2, Double_t y2,const char* color); - /** Draw energy for given point **/ - void DrawEnergy(ecalPoint* p, const char* color); - void DrawPDG(ecalPoint* p, const char* color); - void DrawEnergy(Float_t x, Float_t y, Float_t p, const char* color); - Double_t GetP(ecalPoint* p); - - /** Draw chi2 for photons **/ - void DrawChi2(Float_t x, Float_t y, Float_t chi2, const char* color); - - TText* fTxt; //! - void DrawMC(); -// void DrawPhotons(); -// void DrawTracks(); - void DrawCells(); - - std::list fCells; //! - void DrawImage(); - - TClonesArray* fMCTracks; //! - TClonesArray* fPoints; //! - TClonesArray* fClusters; //! - TString fInName; - /** Event number **/ - Int_t fEventN; - - Double_t fX; - Double_t fY; - Double_t fZ; - Double_t fMCX; - Double_t fMCY; - Double_t fMCZ; - Int_t fMCMotherTrN; - - Double_t fE; - Double_t fMCE; - Double_t fPX; - Double_t fPY; - Double_t fPZ; - Double_t fMCPX; - Double_t fMCPY; - Double_t fMCPZ; - Double_t fChi2; - /** Pdg code. Gamma and neutron(antineutron) only **/ - Int_t fPdgCode; - /** Distance between this and closest other hit in the calorimeter **/ - Double_t fR; - - ecalDrawer(const ecalDrawer&); - ecalDrawer& operator=(const ecalDrawer&); - - ClassDef(ecalDrawer, 1) + public: + /** Default constructor. Requirement of ROOT system **/ + ecalDrawer(); + + /** Standard constructor **/ + ecalDrawer(const char* name, const Int_t iVerbose = 1); + + /** Destructor **/ + virtual ~ecalDrawer(); + + /** Set prefix to name of images + ** File will be named like: prefix0000.png **/ + inline void SetNamePrefix(const char* prefix) { fNamePrefix = prefix; } + inline void SetCellSize(Int_t size) { fCellSize = size; } + + Int_t InitPython(TClonesArray* mctracks, + TClonesArray* ecalPoints, + ecalStructure* structure, + TClonesArray* clusters); + /** Init **/ + virtual InitStatus Init(); + virtual void Exec(Option_t* option); + virtual void Finish(); + + private: + TString fNamePrefix; //! + /** An image and its size **/ + TASImage* fC; //! + Int_t fCellSize; + Int_t fCX; + Int_t fCY; + + /** Normalization **/ + Double_t fMaxEnergyDep; + /** Structure and info for drawing **/ + ecalStructure* fStr; //! + ecalInf* fInf; //! + TString fEdging; //! + void PutPixel(Int_t x, Int_t y, Float_t r, Float_t g, Float_t b); + void PutPixel(Int_t x, Int_t y, const char* color); + /** type==0 for star, type==1 for square **/ + void DrawMark(Double_t x, Double_t y, const char* color, Int_t type); + /** draw cell with filled color. fEdging used as egding of cell **/ + void DrawCell(ecalCell* cell, Float_t r, Float_t g, Float_t b); + void DrawCell(ecalCell* cell, const char* color); + + void DrawLine(Double_t x, Double_t y, const char* color, Int_t track); + void DrawLine(Double_t x1, Double_t y1, Double_t x2, Double_t y2, const char* color); + /** Draw energy for given point **/ + void DrawEnergy(ecalPoint* p, const char* color); + void DrawPDG(ecalPoint* p, const char* color); + void DrawEnergy(Float_t x, Float_t y, Float_t p, const char* color); + Double_t GetP(ecalPoint* p); + + /** Draw chi2 for photons **/ + void DrawChi2(Float_t x, Float_t y, Float_t chi2, const char* color); + + TText* fTxt; //! + void DrawMC(); + // void DrawPhotons(); + // void DrawTracks(); + void DrawCells(); + + std::list fCells; //! + void DrawImage(); + + TClonesArray* fMCTracks; //! + TClonesArray* fPoints; //! + TClonesArray* fClusters; //! + TString fInName; + /** Event number **/ + Int_t fEventN; + + Double_t fX; + Double_t fY; + Double_t fZ; + Double_t fMCX; + Double_t fMCY; + Double_t fMCZ; + Int_t fMCMotherTrN; + + Double_t fE; + Double_t fMCE; + Double_t fPX; + Double_t fPY; + Double_t fPZ; + Double_t fMCPX; + Double_t fMCPY; + Double_t fMCPZ; + Double_t fChi2; + /** Pdg code. Gamma and neutron(antineutron) only **/ + Int_t fPdgCode; + /** Distance between this and closest other hit in the calorimeter **/ + Double_t fR; + + ecalDrawer(const ecalDrawer&); + ecalDrawer& operator=(const ecalDrawer&); + + ClassDef(ecalDrawer, 1) }; /** Convert Lab color to RGB. Formulas taken from www.easyrgb.com ** ** L[0.0, 1.0], a[-0.5, 0.5], b[-0.5, 0.5] **/ inline void LabToRGB(Float_t L, Float_t a, Float_t b, Float_t& R, Float_t& G, Float_t& B) { - Float_t vY=(L+0.16)/1.16; - Float_t vX=a/5.00+vY; - Float_t vZ=vY-b/2.0; - if (vY*vY*vY>0.008856) vY=vY*vY*vY; else vY=(vY-16.0/116.0)/7.787; - if (vX*vX*vX>0.008856) vX=vX*vX*vX; else vX=(vX-16.0/116.0)/7.787; - if (vZ*vZ*vZ>0.008856) vZ=vZ*vZ*vZ; else vZ=(vZ-16.0/116.0)/7.787; - vX*=0.95047; vZ*=1.08883; - R= vX*3.2406-vY*1.5372-vZ*0.4986; - G=-vX*0.9689+vY*1.8758+vZ*0.0415; - B= vX*0.0557-vY*0.2040+vZ*1.0570; - if (R>0.0031308) R=1.055*powf(R, 1.0/2.4)-0.055; else R*=12.92; - if (G>0.0031308) G=1.055*powf(G, 1.0/2.4)-0.055; else G*=12.92; - if (B>0.0031308) B=1.055*powf(B, 1.0/2.4)-0.055; else B*=12.92; - if (R<0.0) R=0.0; - if (G<0.0) G=0.0; - if (B<0.0) B=0.0; - Float_t Ln=R*0.3+G*0.6+0.1*B; - if (Ln>L) { R*=L/Ln; G*=L/Ln; B*=L/Ln; } - if (R>1.0) { G/=R; B/=R; R=1.0; } - if (G>1.0) { R/=G; B/=G; G=1.0; } - if (B>1.0) { R/=B; G/=B; B=1.0; } + Float_t vY = (L + 0.16) / 1.16; + Float_t vX = a / 5.00 + vY; + Float_t vZ = vY - b / 2.0; + if (vY * vY * vY > 0.008856) + vY = vY * vY * vY; + else + vY = (vY - 16.0 / 116.0) / 7.787; + if (vX * vX * vX > 0.008856) + vX = vX * vX * vX; + else + vX = (vX - 16.0 / 116.0) / 7.787; + if (vZ * vZ * vZ > 0.008856) + vZ = vZ * vZ * vZ; + else + vZ = (vZ - 16.0 / 116.0) / 7.787; + vX *= 0.95047; + vZ *= 1.08883; + R = vX * 3.2406 - vY * 1.5372 - vZ * 0.4986; + G = -vX * 0.9689 + vY * 1.8758 + vZ * 0.0415; + B = vX * 0.0557 - vY * 0.2040 + vZ * 1.0570; + if (R > 0.0031308) + R = 1.055 * powf(R, 1.0 / 2.4) - 0.055; + else + R *= 12.92; + if (G > 0.0031308) + G = 1.055 * powf(G, 1.0 / 2.4) - 0.055; + else + G *= 12.92; + if (B > 0.0031308) + B = 1.055 * powf(B, 1.0 / 2.4) - 0.055; + else + B *= 12.92; + if (R < 0.0) + R = 0.0; + if (G < 0.0) + G = 0.0; + if (B < 0.0) + B = 0.0; + Float_t Ln = R * 0.3 + G * 0.6 + 0.1 * B; + if (Ln > L) { + R *= L / Ln; + G *= L / Ln; + B *= L / Ln; + } + if (R > 1.0) { + G /= R; + B /= R; + R = 1.0; + } + if (G > 1.0) { + R /= G; + B /= G; + G = 1.0; + } + if (B > 1.0) { + R /= B; + G /= B; + B = 1.0; + } } inline Float_t Hue_2_RGB(Float_t v1, Float_t v2, Float_t h) { - Float_t vh=h; - if (vh<0) vh+=1; - if (vh>1) vh-=1; - if (6*vh<1) return v1+(v2-v1)*6*vh; - if (2*vh<1) return v2; - if (3*vh<2) return (v1+(v2-v1)*(2.0/3.0-vh)*6); - return v1; + Float_t vh = h; + if (vh < 0) + vh += 1; + if (vh > 1) + vh -= 1; + if (6 * vh < 1) + return v1 + (v2 - v1) * 6 * vh; + if (2 * vh < 1) + return v2; + if (3 * vh < 2) + return (v1 + (v2 - v1) * (2.0 / 3.0 - vh) * 6); + return v1; } inline void HSLToRGB(Float_t h, Float_t s, Float_t l, Float_t& R, Float_t& G, Float_t& B) { - if (s==0) - { - R=G=B=l; - return; - } - Float_t v2; - Float_t v1; - if (l<0.5) v2=l*(1+s); else v2=(l+s)-(s*l); - v1=2*l-v2; - R=Hue_2_RGB(v1, v2, h+(1.0/3)); - G=Hue_2_RGB(v1, v2, h); - B=Hue_2_RGB(v1, v2, h-(1.0/3)); + if (s == 0) { + R = G = B = l; + return; + } + Float_t v2; + Float_t v1; + if (l < 0.5) + v2 = l * (1 + s); + else + v2 = (l + s) - (s * l); + v1 = 2 * l - v2; + R = Hue_2_RGB(v1, v2, h + (1.0 / 3)); + G = Hue_2_RGB(v1, v2, h); + B = Hue_2_RGB(v1, v2, h - (1.0 / 3)); } #endif diff --git a/ecal/ecalInf.cxx b/ecal/ecalInf.cxx index 14d732fe10..effbc64533 100644 --- a/ecal/ecalInf.cxx +++ b/ecal/ecalInf.cxx @@ -8,259 +8,253 @@ #include "FairRunAna.h" #include "FairRuntimeDb.h" - -#include "TSystem.h" #include "TMap.h" +#include "TSystem.h" -#include #include +#include #include -using std::cout; using std::cerr; +using std::cout; using std::endl; using std::string; -ecalInf* ecalInf::fInf=NULL; -Int_t ecalInf::fRefCount=0; - +ecalInf* ecalInf::fInf = NULL; +Int_t ecalInf::fRefCount = 0; ecalInf::~ecalInf() { - for(Int_t i=0;iGetenv("VMCWORKDIR"); - newname+="/geometry/"; - newname+=filename; - if (fInf!=NULL) { - if (fInf->fFileName==newname) { - fRefCount++; - return fInf; - } else { - cerr << "ecalInf: Trying create "; - cerr << "instance of ecalInf with"; - cerr << " name " << filename; - cerr << ", which is different from "; - cerr << fInf->fFileName << "." << endl; - return NULL; - } + if (filename == NULL) { + if (fInf != NULL) + fRefCount++; + return fInf; } - fInf=new ecalInf(newname); - //Is something wrong? - if (fInf->fSuccess==0) - { - delete fInf; - return NULL; - } - fRefCount++; - return fInf; + TString newname = gSystem->Getenv("VMCWORKDIR"); + newname += "/geometry/"; + newname += filename; + if (fInf != NULL) { + if (fInf->fFileName == newname) { + fRefCount++; + return fInf; + } else { + cerr << "ecalInf: Trying create "; + cerr << "instance of ecalInf with"; + cerr << " name " << filename; + cerr << ", which is different from "; + cerr << fInf->fFileName << "." << endl; + return NULL; + } + } + fInf = new ecalInf(newname); + // Is something wrong? + if (fInf->fSuccess == 0) { + delete fInf; + return NULL; + } + fRefCount++; + return fInf; } -int cmp_nocase(const string &s, const string &s2 ) +int cmp_nocase(const string& s, const string& s2) { - string::const_iterator p=s.begin(); - string::const_iterator p2=s2.begin(); - while(p!=s.end()&&p2!=s2.end()) { - if (toupper(*p)!=toupper(*p2)) return (toupper(*p)GetValue(key); - if (value==NULL) - { - cerr << "Can't find variable named \"" << key << "\""; - Fatal("GetVariableStrict","Exiting..."); - } - Double_t val; - char* err=NULL; - val=strtod(value->GetString(),&err); - if (err[0]!='\0') - { - cerr << "Can't convert variable named \"" << key ; - cerr << "\" to floating point. Value is \""; - cerr << value->GetString() << "\"." << endl; - Fatal("GetVariableStrict","Exiting..."); - } - return val; + TObjString* value = (TObjString*)fVariables->GetValue(key); + if (value == NULL) { + cerr << "Can't find variable named \"" << key << "\""; + Fatal("GetVariableStrict", "Exiting..."); + } + Double_t val; + char* err = NULL; + val = strtod(value->GetString(), &err); + if (err[0] != '\0') { + cerr << "Can't convert variable named \"" << key; + cerr << "\" to floating point. Value is \""; + cerr << value->GetString() << "\"." << endl; + Fatal("GetVariableStrict", "Exiting..."); + } + return val; } TString ecalInf::GetStringVariable(const char* key) { - TObjString* value=(TObjString*)fVariables->GetValue(key); - if (value==NULL) - { - Fatal("GetStringVariable","Can't find variable named %s.", key); - } - return value->GetString(); + TObjString* value = (TObjString*)fVariables->GetValue(key); + if (value == NULL) { + Fatal("GetStringVariable", "Can't find variable named %s.", key); + } + return value->GetString(); } - - Double_t ecalInf::GetVariable(const char* key) { - TObjString* value=(TObjString*)fVariables->GetValue(key); - if (value==NULL) - return -1111; - Double_t val; - char* err=NULL; - val=strtod(value->GetString(),&err); - if (err[0]!='\0') - return -1111; - return val; + TObjString* value = (TObjString*)fVariables->GetValue(key); + if (value == NULL) + return -1111; + Double_t val; + char* err = NULL; + val = strtod(value->GetString(), &err); + if (err[0] != '\0') + return -1111; + return val; } void ecalInf::AddVariable(const char* key, const char* value) { - TObjString* skey=(TObjString*)fVariables->FindObject(key); - //Value for this key already exists!!! - if (skey!=NULL) return; - skey=new TObjString(key); - skey->String().ToLower(); - TObjString* svalue=new TObjString(value); - fVariables->Add(skey, svalue); + TObjString* skey = (TObjString*)fVariables->FindObject(key); + // Value for this key already exists!!! + if (skey != NULL) + return; + skey = new TObjString(key); + skey->String().ToLower(); + TObjString* svalue = new TObjString(value); + fVariables->Add(skey, svalue); } //============================================================================= ecalInf::ecalInf(const char* filename) - : TObject(), - fVariables(new TMap(200)), - fEcalStr(), - fXPos(0.), - fYPos(0.), - fZPos(0.), - fNLayers(0), - fXSize(0), - fYSize(0), - fModuleSize(0.), - fLead(0.), - fScin(0.), - fTyveec(0.), - fThicknessLayer(0.), - fCellSize(0.), - fEcalSize(), - fECut(0.), - fHCut(0.), - fSemiX(0.), - fSemiY(0.), - fFastMC(-1), - fSuccess(1), - fFileName(filename) + : TObject() + , fVariables(new TMap(200)) + , fEcalStr() + , fXPos(0.) + , fYPos(0.) + , fZPos(0.) + , fNLayers(0) + , fXSize(0) + , fYSize(0) + , fModuleSize(0.) + , fLead(0.) + , fScin(0.) + , fTyveec(0.) + , fThicknessLayer(0.) + , fCellSize(0.) + , fEcalSize() + , fECut(0.) + , fHCut(0.) + , fSemiX(0.) + , fSemiY(0.) + , fFastMC(-1) + , fSuccess(1) + , fFileName(filename) { - /** - ** Constructor reads and parses the ascii file, and fill - ** the ECAL geometry container - ** - FairRunAna* ana = FairRunAna::Instance(); - if (ana!=NULL) - { - FairRuntimeDb* rtdb=ana->GetRuntimeDb(); - rtdb->getContainer("CbmGeoEcalPar"); - } - */ - std::ifstream file(filename); - Int_t linenum; - Double_t val; - string buffer; - string message; - string variable; - string value; - TObjString* str=NULL; - char** err=NULL; - char winend[2]={13, 0}; - int ssize=-1; - - if (!file) { - cerr << "ecalInf: Can't open information file " << filename << "!" << endl; - cerr << "ecalInf: Ecal will not be constructed correctly." << endl; - fSuccess=0; - return; - } - - linenum=0; - while(getline(file,buffer)) { - linenum++; - message=buffer.substr(buffer.find_first_not_of(" ")); //Skiping initial spaces - message=message.substr(0,message.find("#")); //Removing comments - // Threat windows end of strings correctly - message=message.substr(0,message.find(winend)); - if (message.empty()) continue; //This was just a comment - variable=message.substr(0,message.find("=")); - if (variable=="structure") { - while(getline(file,buffer)) { - linenum++; - if (buffer.empty()) break; - message=buffer.substr(buffer.find_first_not_of(" ")); //Skiping initial spaces - message=message.substr(0,message.find("#")); //Removing comments - message=message.substr(0,message.find_last_not_of(" ")+1); //Skiping ending spaces + /** + ** Constructor reads and parses the ascii file, and fill + ** the ECAL geometry container + ** + FairRunAna* ana = FairRunAna::Instance(); + if (ana!=NULL) + { + FairRuntimeDb* rtdb=ana->GetRuntimeDb(); + rtdb->getContainer("CbmGeoEcalPar"); + } + */ + std::ifstream file(filename); + Int_t linenum; + Double_t val; + string buffer; + string message; + string variable; + string value; + TObjString* str = NULL; + char** err = NULL; + char winend[2] = {13, 0}; + int ssize = -1; + + if (!file) { + cerr << "ecalInf: Can't open information file " << filename << "!" << endl; + cerr << "ecalInf: Ecal will not be constructed correctly." << endl; + fSuccess = 0; + return; + } + linenum = 0; + while (getline(file, buffer)) { + linenum++; + message = buffer.substr(buffer.find_first_not_of(" ")); // Skiping initial spaces + message = message.substr(0, message.find("#")); // Removing comments // Threat windows end of strings correctly - message=message.substr(0,message.find(winend)); - - if (!message.empty()) { - if (-1==ssize) - ssize=message.size(); - else - if (ssize!=(Int_t)message.size()) { - cerr << "Error in ECAL structure at line " << linenum; - cerr << "." << endl; - cerr << "Line length differs from previous one" << endl; + message = message.substr(0, message.find(winend)); + if (message.empty()) + continue; // This was just a comment + variable = message.substr(0, message.find("=")); + if (variable == "structure") { + while (getline(file, buffer)) { + linenum++; + if (buffer.empty()) + break; + message = buffer.substr(buffer.find_first_not_of(" ")); // Skiping initial spaces + message = message.substr(0, message.find("#")); // Removing comments + message = message.substr(0, message.find_last_not_of(" ") + 1); // Skiping ending spaces + + // Threat windows end of strings correctly + message = message.substr(0, message.find(winend)); + + if (!message.empty()) { + if (-1 == ssize) + ssize = message.size(); + else if (ssize != (Int_t)message.size()) { + cerr << "Error in ECAL structure at line " << linenum; + cerr << "." << endl; + cerr << "Line length differs from previous one" << endl; + fSuccess = 0; + file.close(); + return; + } + + str = new TObjString(message.c_str()); + fEcalStr.Add(str); + } + } + break; + } + if (variable == message) { + cerr << "Syntax error: File " << filename << ".Line " << linenum << "." << endl; + fSuccess = 0; + file.close(); + return; + } + variable = variable.substr(0, variable.find_first_of(" ")); + value = message.substr(message.find("=") + 1); + value = value.substr(value.find_first_not_of(" ")); // Skiping initial spaces + value = value.substr(0, value.find_first_of(" ")); + /* + value=value.substr(0,value.find_first_not_of("1234567890-+e.")); + val=strtod(value.c_str(),err); + if (err) { + cerr << "Syntax error after =: File " << filename << ".Line " << linenum << "." << endl; fSuccess=0; - file.close(); - return; - - } - - str=new TObjString(message.c_str()); - fEcalStr.Add(str); - } - } - break; - } - if (variable==message) { - cerr << "Syntax error: File " << filename << ".Line " << linenum << "." << endl; - fSuccess=0; - file.close(); - return; + file.close(); + return; + } + */ + AddVariable(variable.c_str(), value.c_str()); } - variable=variable.substr(0,variable.find_first_of(" ")); - value=message.substr(message.find("=")+1); - value=value.substr(value.find_first_not_of(" ")); //Skiping initial spaces - value=value.substr(0,value.find_first_of(" ")); -/* - value=value.substr(0,value.find_first_not_of("1234567890-+e.")); - val=strtod(value.c_str(),err); - if (err) { - cerr << "Syntax error after =: File " << filename << ".Line " << linenum << "." << endl; - fSuccess=0; - file.close(); - return; - } -*/ - AddVariable(variable.c_str(), value.c_str()); - } - file.close(); - InitVariables(); + file.close(); + InitVariables(); } Bool_t ecalInf::ExcludeParameter(TString parname) { - if (parname.CompareTo("ecalversion")==0) return kTRUE; - return kFALSE; + if (parname.CompareTo("ecalversion") == 0) + return kTRUE; + return kFALSE; } /* @@ -290,16 +284,15 @@ void ecalInf::CheckVariables() if (ExcludeParameter(key->String())==kFALSE) if (second==NULL) { - Info("CheckVariables", "Parameter %s not found in .geo file, but found in parameter file.", key->String().Data()); - } else - if (first->String()!=second->String()) + Info("CheckVariables", "Parameter %s not found in .geo file, but found in parameter file.", +key->String().Data()); } else if (first->String()!=second->String()) { - Info("CheckVariables", "Parameter %s differs in .geo file and parameter file!", key->String().Data()); - Info("CheckVariables", "%s=%s in parameter file.", key->String().Data(), first->String().Data()); - Info("CheckVariables", "%s=%s in .geo file.", key->String().Data(), second->String().Data()); + Info("CheckVariables", "Parameter %s differs in .geo file and parameter file!", key->String().Data()); + Info("CheckVariables", "%s=%s in parameter file.", key->String().Data(), first->String().Data()); + Info("CheckVariables", "%s=%s in .geo file.", key->String().Data(), second->String().Data()); } if (ExcludeParameter(key->String())==kTRUE) - AddVariable(key->String().Data(), first->String().Data()); + AddVariable(key->String().Data(), first->String().Data()); } } @@ -313,9 +306,9 @@ void ecalInf::CheckVariables() TObjString* second=(TObjString*)fEcalStr.At(i); if (second&&first->String()!=second->String()) { - Info("CheckVariables", "String %d in calorimeter structure differs in .geo file and in parameter file.", i); - Info("CheckVariables", "%s=%s in parameter file", key->String().Data(), first->String().Data()); - Info("CheckVariables", "%s=%s in .geo file", key->String().Data(), second->String().Data()); + Info("CheckVariables", "String %d in calorimeter structure differs in .geo file and in parameter file.", i); + Info("CheckVariables", "%s=%s in parameter file", key->String().Data(), first->String().Data()); + Info("CheckVariables", "%s=%s in .geo file", key->String().Data(), second->String().Data()); } } } @@ -323,86 +316,87 @@ void ecalInf::CheckVariables() */ void ecalInf::InitVariables() { - TString stri; - TObjString* str=(TObjString*)fEcalStr.At(0); - - fXPos=GetVariableStrict("xpos"); - fYPos=GetVariableStrict("ypos"); - fZPos=GetVariableStrict("zpos"); - fNLayers=(Int_t)GetVariableStrict("nlayers"); - fModuleSize=GetVariableStrict("modulesize"); - fLead=GetVariableStrict("lead"); - fScin=GetVariableStrict("scin"); - fTyveec=GetVariableStrict("tyveec"); - fEcalSize[2]=GetVariableStrict("ecalzsize"); - fECut=GetVariableStrict("ecut"); - fHCut=GetVariableStrict("hcut"); - fFastMC=(Int_t)GetVariableStrict("fastmc"); - fSemiX=GetVariableStrict("xsemiaxis"); - fSemiY=GetVariableStrict("ysemiaxis"); - - stri=""; stri+=str->GetString().Length(); - AddVariable("xsize", stri); - stri=""; stri+=fEcalStr.GetLast()+1; - AddVariable("ysize", stri); - - fXSize=(Int_t)GetVariableStrict("xsize"); - fYSize=(Int_t)GetVariableStrict("ysize"); - fThicknessLayer = 2.0*GetTyveec()+GetScin()+GetLead(); - fEcalSize[0] = GetXSize()*GetModuleSize(); - fEcalSize[1] = GetYSize()*GetModuleSize(); - stri=""; stri+=fEcalSize[0]; - AddVariable("xecalsize",stri); - stri=""; stri+=fEcalSize[1]; - AddVariable("yecalsize",stri); + TString stri; + TObjString* str = (TObjString*)fEcalStr.At(0); + + fXPos = GetVariableStrict("xpos"); + fYPos = GetVariableStrict("ypos"); + fZPos = GetVariableStrict("zpos"); + fNLayers = (Int_t)GetVariableStrict("nlayers"); + fModuleSize = GetVariableStrict("modulesize"); + fLead = GetVariableStrict("lead"); + fScin = GetVariableStrict("scin"); + fTyveec = GetVariableStrict("tyveec"); + fEcalSize[2] = GetVariableStrict("ecalzsize"); + fECut = GetVariableStrict("ecut"); + fHCut = GetVariableStrict("hcut"); + fFastMC = (Int_t)GetVariableStrict("fastmc"); + fSemiX = GetVariableStrict("xsemiaxis"); + fSemiY = GetVariableStrict("ysemiaxis"); + + stri = ""; + stri += str->GetString().Length(); + AddVariable("xsize", stri); + stri = ""; + stri += fEcalStr.GetLast() + 1; + AddVariable("ysize", stri); + + fXSize = (Int_t)GetVariableStrict("xsize"); + fYSize = (Int_t)GetVariableStrict("ysize"); + fThicknessLayer = 2.0 * GetTyveec() + GetScin() + GetLead(); + fEcalSize[0] = GetXSize() * GetModuleSize(); + fEcalSize[1] = GetYSize() * GetModuleSize(); + stri = ""; + stri += fEcalSize[0]; + AddVariable("xecalsize", stri); + stri = ""; + stri += fEcalSize[1]; + AddVariable("yecalsize", stri); } //----------------------------------------------------------------------------- void ecalInf::DumpContainer() const { - // Print out the ECAL geometry container - - if (fVariables) - { + // Print out the ECAL geometry container + + if (fVariables) { + TObjString* key; + TIterator* iter = fVariables->MakeIterator(); + while ((key = (TObjString*)iter->Next()) != NULL) { + TObjString* str = (TObjString*)fVariables->GetValue(key); + cout << key->String() << "=" << str->String() << endl; + } + } TObjString* key; - TIterator* iter=fVariables->MakeIterator(); - while((key=(TObjString*)iter->Next())!=NULL) - { - TObjString* str=(TObjString*)fVariables->GetValue(key); - cout << key->String() << "=" << str->String() << endl; + TIterator* iter = fEcalStr.MakeIterator(); + + Int_t modules = 0; + Int_t channels = 0; + Int_t i; + Int_t j; + Int_t m[10]; + char stri[2] = {0, 0}; + TString st; + for (i = 0; i < 10; i++) + m[i] = 0; + + while ((key = (TObjString*)iter->Next()) != NULL) { + st = key->String(); + cout << key->String() << endl; + for (i = 0; i < st.Length(); i++) { + stri[0] = st[i]; + j = atoi(stri); + m[j]++; + if (j) + modules++; + channels += j * j; + } } - } - TObjString* key; - TIterator* iter=fEcalStr.MakeIterator(); - - Int_t modules=0; - Int_t channels=0; - Int_t i; - Int_t j; - Int_t m[10]; - char stri[2]={0, 0}; - TString st; - for(i=0;i<10;i++) m[i]=0; - - while((key=(TObjString*)iter->Next())!=NULL) - { - st=key->String(); - cout << key->String() << endl; - for(i=0;i #include class TMap; -class ecalInf:public TObject +class ecalInf : public TObject { -public: - /** This is ROOT requirement **/ - ecalInf() : TObject(), fVariables(NULL), fEcalStr(), fXPos(0.), fYPos(0.), - fZPos(0.), fNLayers(0), fXSize(0), fYSize(0), fModuleSize(0.), fLead(0.), - fScin(0.), fTyveec(0.), fThicknessLayer(0.), fCellSize(0.), fEcalSize(), - fECut(0.), fHCut(0.), fSemiX(0.0), fSemiY(0.0), fFastMC(-1), - fSuccess(-1), fFileName("") - {}; - - static ecalInf* GetInstance(const char* filename); - /** Getters **/ - inline Double_t GetXPos() const {return fXPos;} - inline Double_t GetYPos() const {return fYPos;} - inline Double_t GetZPos() const {return fZPos;} - - inline Double_t GetModuleSize() const {return fModuleSize;} - - inline Int_t GetNLayers() const {return fNLayers;} - inline Double_t GetLead() const {return fLead;} - inline Double_t GetScin() const {return fScin;} - inline Double_t GetTyveec() const {return fTyveec;} - inline Double_t GetThicknessLayer() const {return fThicknessLayer;} - - /** Size of ECAL in super modules **/ - inline Int_t GetXSize() const {return fXSize;} - inline Int_t GetYSize() const {return fYSize;} - inline Double_t GetContainerXSemiAxiss() const {return fSemiX;} - inline Double_t GetContainerYSemiAxiss() const {return fSemiY;} - - /** Geant cuts information **/ - inline Double_t GetElectronCut() const {return fECut;} - inline Double_t GetHadronCut() const {return fHCut;} - - inline Double_t GetEcalSize(Int_t num) const { - if (num>-1&&num<3) return fEcalSize[num]; - return -1; - } - char GetType(Int_t x, Int_t y) const; //returns type of (X,Y) supercell - inline Int_t GetFastMC() const {return fFastMC;} - void DumpContainer() const; - - void FreeInstance(); - - /** key must be lower case. For example, if have in - ** geo file AaaA=90, then you should call - ** GetVariableStrict("aaaa"). - ** If variable not found, will return -1111 **/ - Double_t GetVariable(const char* key); - /** key must be lower case. For example, if have in - ** geo file AaaA=90, then you should call - ** GetVariableStrict("aaaa"). - ** If variable not found, will generate Fatal **/ - Double_t GetVariableStrict(const char* key); - TString GetStringVariable(const char* key); - - void AddVariable(const char* key, const char* value); - /** If data from Parameter file differs from ours - ** TODO: should understand a way of storring parameters in SHIP**/ - // void CheckVariables(); -protected: - - /** Text file constructor **/ - ecalInf(const char* filename); - void CalculateHoleSize(); - virtual ~ecalInf(); - - static ecalInf* fInf; - static Int_t fRefCount; - - -private: - /** Init all other variables from fVariables - ** and fEcalStr**/ - void InitVariables(); - /** Ignore a parameter during comparision **/ - Bool_t ExcludeParameter(TString parname); - /** A map containing all variables - ** This variable should be saved in parameter file **/ - TMap* fVariables; - /** Structure of ECAL as array of strings - ** This variable should be saved in parameter file **/ - TObjArray fEcalStr; - /** x-position of ECAL center [cm] **/ - Double_t fXPos; - /** y-position of ECAL center [cm] **/ - Double_t fYPos; - /** z-position of ECAL front [cm] **/ - Double_t fZPos; - - /** Number of ECAL layers **/ - Int_t fNLayers; - - /** x-size of ecal in supermodules **/ - Int_t fXSize; - /** y-size of ecal in supermodules **/ - Int_t fYSize; - - /** transverse supermodule size in cm **/ - Double_t fModuleSize; - - /**Thickness of lead in one layer [cm] **/ - Double_t fLead; - /**Thickness of scintillator in one layer [cm] **/ - Double_t fScin; - /**Thickness of tyvec in one layer [cm] **/ - Double_t fTyveec; - /**Total thickness of layer [cm] **/ - Double_t fThicknessLayer; - /**transverse size of ECAL cell for simulation [cm] **/ - Double_t fCellSize; - /**Size of ECAL container [cm] **/ - Double_t fEcalSize[3]; - /**Electron cut for ECAL **/ - Double_t fECut; - /**Hadron cut for ECAL **/ - Double_t fHCut; - /**Semiaxises keeping volume **/ - Double_t fSemiX; - Double_t fSemiY; - - /**Flag to run Fast (1) or Full (0) MC code **/ - Int_t fFastMC; - - /** 1 if evething Ok **/ - Int_t fSuccess; - - TString fFileName; - - ecalInf(const ecalInf&); - ecalInf& operator=(const ecalInf&); - - ClassDef(ecalInf,2); + public: + /** This is ROOT requirement **/ + ecalInf() + : TObject() + , fVariables(NULL) + , fEcalStr() + , fXPos(0.) + , fYPos(0.) + , fZPos(0.) + , fNLayers(0) + , fXSize(0) + , fYSize(0) + , fModuleSize(0.) + , fLead(0.) + , fScin(0.) + , fTyveec(0.) + , fThicknessLayer(0.) + , fCellSize(0.) + , fEcalSize() + , fECut(0.) + , fHCut(0.) + , fSemiX(0.0) + , fSemiY(0.0) + , fFastMC(-1) + , fSuccess(-1) + , fFileName("") {}; + + static ecalInf* GetInstance(const char* filename); + /** Getters **/ + inline Double_t GetXPos() const { return fXPos; } + inline Double_t GetYPos() const { return fYPos; } + inline Double_t GetZPos() const { return fZPos; } + + inline Double_t GetModuleSize() const { return fModuleSize; } + + inline Int_t GetNLayers() const { return fNLayers; } + inline Double_t GetLead() const { return fLead; } + inline Double_t GetScin() const { return fScin; } + inline Double_t GetTyveec() const { return fTyveec; } + inline Double_t GetThicknessLayer() const { return fThicknessLayer; } + + /** Size of ECAL in super modules **/ + inline Int_t GetXSize() const { return fXSize; } + inline Int_t GetYSize() const { return fYSize; } + inline Double_t GetContainerXSemiAxiss() const { return fSemiX; } + inline Double_t GetContainerYSemiAxiss() const { return fSemiY; } + + /** Geant cuts information **/ + inline Double_t GetElectronCut() const { return fECut; } + inline Double_t GetHadronCut() const { return fHCut; } + + inline Double_t GetEcalSize(Int_t num) const + { + if (num > -1 && num < 3) + return fEcalSize[num]; + return -1; + } + char GetType(Int_t x, Int_t y) const; // returns type of (X,Y) supercell + inline Int_t GetFastMC() const { return fFastMC; } + void DumpContainer() const; + + void FreeInstance(); + + /** key must be lower case. For example, if have in + ** geo file AaaA=90, then you should call + ** GetVariableStrict("aaaa"). + ** If variable not found, will return -1111 **/ + Double_t GetVariable(const char* key); + /** key must be lower case. For example, if have in + ** geo file AaaA=90, then you should call + ** GetVariableStrict("aaaa"). + ** If variable not found, will generate Fatal **/ + Double_t GetVariableStrict(const char* key); + TString GetStringVariable(const char* key); + + void AddVariable(const char* key, const char* value); + /** If data from Parameter file differs from ours + ** TODO: should understand a way of storring parameters in SHIP**/ + // void CheckVariables(); + protected: + /** Text file constructor **/ + ecalInf(const char* filename); + void CalculateHoleSize(); + virtual ~ecalInf(); + + static ecalInf* fInf; + static Int_t fRefCount; + + private: + /** Init all other variables from fVariables + ** and fEcalStr**/ + void InitVariables(); + /** Ignore a parameter during comparision **/ + Bool_t ExcludeParameter(TString parname); + /** A map containing all variables + ** This variable should be saved in parameter file **/ + TMap* fVariables; + /** Structure of ECAL as array of strings + ** This variable should be saved in parameter file **/ + TObjArray fEcalStr; + /** x-position of ECAL center [cm] **/ + Double_t fXPos; + /** y-position of ECAL center [cm] **/ + Double_t fYPos; + /** z-position of ECAL front [cm] **/ + Double_t fZPos; + + /** Number of ECAL layers **/ + Int_t fNLayers; + + /** x-size of ecal in supermodules **/ + Int_t fXSize; + /** y-size of ecal in supermodules **/ + Int_t fYSize; + + /** transverse supermodule size in cm **/ + Double_t fModuleSize; + + /**Thickness of lead in one layer [cm] **/ + Double_t fLead; + /**Thickness of scintillator in one layer [cm] **/ + Double_t fScin; + /**Thickness of tyvec in one layer [cm] **/ + Double_t fTyveec; + /**Total thickness of layer [cm] **/ + Double_t fThicknessLayer; + /**transverse size of ECAL cell for simulation [cm] **/ + Double_t fCellSize; + /**Size of ECAL container [cm] **/ + Double_t fEcalSize[3]; + /**Electron cut for ECAL **/ + Double_t fECut; + /**Hadron cut for ECAL **/ + Double_t fHCut; + /**Semiaxises keeping volume **/ + Double_t fSemiX; + Double_t fSemiY; + + /**Flag to run Fast (1) or Full (0) MC code **/ + Int_t fFastMC; + + /** 1 if evething Ok **/ + Int_t fSuccess; + + TString fFileName; + + ecalInf(const ecalInf&); + ecalInf& operator=(const ecalInf&); + + ClassDef(ecalInf, 2); }; inline char ecalInf::GetType(Int_t x, Int_t y) const { - /** Returns the type of the module with position (x,y) **/ - if (x<0||y<0||y>fEcalStr.GetLast()) return 0; - TObjString* str=(TObjString*)fEcalStr.At(y); - if (str->GetString().Length()GetString()[x],0}; - return atoi(stri); + /** Returns the type of the module with position (x,y) **/ + if (x < 0 || y < 0 || y > fEcalStr.GetLast()) + return 0; + TObjString* str = (TObjString*)fEcalStr.At(y); + if (str->GetString().Length() < x) + return 0; + char stri[2] = {str->GetString()[x], 0}; + return atoi(stri); } inline void ecalInf::FreeInstance() { - fRefCount--; - if (fRefCount==0) - { - delete this; - fInf=NULL; - } + fRefCount--; + if (fRefCount == 0) { + delete this; + fInf = NULL; + } } #endif diff --git a/ecal/ecalLightMap.cxx b/ecal/ecalLightMap.cxx index 5136614443..20ce058b2d 100644 --- a/ecal/ecalLightMap.cxx +++ b/ecal/ecalLightMap.cxx @@ -2,145 +2,179 @@ #include "TSystem.h" -#include #include -#include +#include #include #include +#include using namespace std; ecalLightMap::ecalLightMap(const char* fname, const char* title) - : TNamed(fname, title), - fSSide(-1111.), fS(-1111), fSize(0), fData(NULL) + : TNamed(fname, title) + , fSSide(-1111.) + , fS(-1111) + , fSize(0) + , fData(NULL) { - Init(fname); + Init(fname); } /** Read information from file **/ void ecalLightMap::Init(const char* filename) { - TString fn=filename; - gSystem->ExpandPathName(fn); - ifstream f(fn); - list lst; - string buf; - string token; - string message; - if (!f) - { - Fatal("Init","Can't open file %s.", filename); - return; - } + TString fn = filename; + gSystem->ExpandPathName(fn); + ifstream f(fn); + list lst; + string buf; + string token; + string message; + if (!f) { + Fatal("Init", "Can't open file %s.", filename); + return; + } - while(getline(f, buf)) - { - if (buf.empty()) continue; - if (buf.find_first_not_of(" ")==string::npos) continue; - //Skipping initial spaces - message=buf.substr(buf.find_first_not_of(" ")); - if (message.empty()) continue; - //Removing comments - message=message.substr(0,message.find("#")); - if (message.empty()) continue; - while(!message.empty()) - { - token=message.substr(0,message.find_first_of(" ")); - if (token.empty()) break; - lst.push_back(atof(token.c_str())); - if (token==message) break; - token=message.substr(message.find_first_of(" ")); - if (token.empty()) break; - if (token.find_first_not_of(" ")==string::npos) break; - message=token.substr(token.find_first_not_of(" ")); + while (getline(f, buf)) { + if (buf.empty()) + continue; + if (buf.find_first_not_of(" ") == string::npos) + continue; + // Skipping initial spaces + message = buf.substr(buf.find_first_not_of(" ")); + if (message.empty()) + continue; + // Removing comments + message = message.substr(0, message.find("#")); + if (message.empty()) + continue; + while (!message.empty()) { + token = message.substr(0, message.find_first_of(" ")); + if (token.empty()) + break; + lst.push_back(atof(token.c_str())); + if (token == message) + break; + token = message.substr(message.find_first_of(" ")); + if (token.empty()) + break; + if (token.find_first_not_of(" ") == string::npos) + break; + message = token.substr(token.find_first_not_of(" ")); + } } - } - f.close(); + f.close(); - list::const_iterator p=lst.begin(); - Double_t xsize; - Double_t ysize; - Double_t sqside; - Double_t l; - Double_t x; - Double_t y; - Double_t z; - Double_t v; - Int_t n; - Int_t i; + list::const_iterator p = lst.begin(); + Double_t xsize; + Double_t ysize; + Double_t sqside; + Double_t l; + Double_t x; + Double_t y; + Double_t z; + Double_t v; + Int_t n; + Int_t i; - xsize=(*p); ++p; ysize=(*p); ++p; sqside=(*p); ++p; - fS=(Int_t)((xsize+0.00001)/sqside); - fSize=fS*fS; fSSide=sqside/xsize; - fData=new Double_t[fSize]; - for(i=0;i=fSize) - { - Info("Init","Data is not selfconsistent (%f, %f), %d", x, y, fSize); + xsize = (*p); + ++p; + ysize = (*p); + ++p; + sqside = (*p); + ++p; + fS = (Int_t)((xsize + 0.00001) / sqside); + fSize = fS * fS; + fSSide = sqside / xsize; + fData = new Double_t[fSize]; + for (i = 0; i < fSize; i++) + fData[i] = -1111; + for (;;) { + if (p == lst.end()) + break; + l = (*p); + ++p; + if (p == lst.end()) + break; + x = (*p); + ++p; + if (p == lst.end()) + break; + y = (*p); + ++p; + if (p == lst.end()) + break; + z = (*p); + ++p; + if (p == lst.end()) + break; + v = (*p); + ++p; + x /= xsize; + y /= ysize; + n = GetNum(x, y); + if (n >= fSize) { + Info("Init", "Data is not selfconsistent (%f, %f), %d", x, y, fSize); + } + fData[n] = v; } - fData[n]=v; - } - lst.clear(); - FillGaps(); - Normalize(); + lst.clear(); + FillGaps(); + Normalize(); } /** Fix a light collection map **/ void ecalLightMap::FillGaps() { - Int_t i; - Int_t j; - Double_t x; - Double_t y; - Int_t n[3]; - Double_t v; - Int_t d; + Int_t i; + Int_t j; + Double_t x; + Double_t y; + Int_t n[3]; + Double_t v; + Int_t d; - for(i=0;i=0&&fData[n[j]]>=0) - { d++; v+=fData[n[j]]; } - if (d>0) - { - v/=d; fData[i]=v; - if (fData[n[0]]<=0) fData[n[0]]=v; - if (fData[n[1]]<=0) fData[n[1]]=v; - if (fData[n[2]]<=0) fData[n[2]]=v; - } - else - Info("FillGaps","No data for (%f,%f)", x, y); - } + for (i = 0; i < fSize; i++) + if (fData[i] < 0) { + x = (i % fS) * fSSide - 0.5 + fSSide / 2.0; + y = (i / fS) * fSSide - 0.5 + fSSide / 2.0; + n[0] = GetNum(x, -y); + n[1] = GetNum(-x, y); + n[2] = GetNum(-x, -y); + v = 0; + d = 0; + for (j = 0; j < 3; j++) + if (n[j] >= 0 && fData[n[j]] >= 0) { + d++; + v += fData[n[j]]; + } + if (d > 0) { + v /= d; + fData[i] = v; + if (fData[n[0]] <= 0) + fData[n[0]] = v; + if (fData[n[1]] <= 0) + fData[n[1]] = v; + if (fData[n[2]] <= 0) + fData[n[2]] = v; + } else + Info("FillGaps", "No data for (%f,%f)", x, y); + } } /** Set average efficiency of light collection to 1.0 **/ void ecalLightMap::Normalize() { - Int_t i; - Int_t n=0; - Double_t v=0; - for(i=0;i0) - { v+=fData[i]; n++; } - v/=n; - for(i=0;i0) - fData[i]/=v; + Int_t i; + Int_t n = 0; + Double_t v = 0; + for (i = 0; i < fSize; i++) + if (fData[i] > 0) { + v += fData[i]; + n++; + } + v /= n; + for (i = 0; i < fSize; i++) + if (fData[i] > 0) + fData[i] /= v; } diff --git a/ecal/ecalLightMap.h b/ecal/ecalLightMap.h index 77aa55bfa9..681fd2b674 100644 --- a/ecal/ecalLightMap.h +++ b/ecal/ecalLightMap.h @@ -5,41 +5,59 @@ class ecalLightMap : public TNamed { -public: - ecalLightMap() : TNamed(), fSSide(0.), fS(0), fSize(0), fData(NULL) {}; - ecalLightMap(const char* fname, const char* title="Light collection efficiency map"); - Double_t Data(Double_t x, Double_t y) - {Int_t n=GetNum(x,y); if (n<0) return n; return fData[n];} - Int_t GetNum(Double_t x, Double_t y) - { - Double_t lx=x+0.5; Double_t ly=y+0.5; - if (lx<0) lx=0; if (ly<0) ly=0; - if (lx>1) lx=1; if (ly>1) ly=1; - Int_t ix=(Int_t)(lx/fSSide); - Int_t iy=(Int_t)(ly/fSSide); - return iy*fS+ix; - } - virtual ~ecalLightMap() {delete fData;} -private: - /** Read information from file **/ - void Init(const char* filename); - /** Fix a light collection map **/ - void FillGaps(); - /** Set average efficiency of light collection to 1.0 **/ - void Normalize(); - /** Step of the light map **/ - Double_t fSSide; //! - /** Size of side of the light map in steps**/ - Int_t fS; //! - /** Size of the light map **/ - Int_t fSize; //! - /** Light collection efficiency map **/ - Double_t* fData; //! + public: + ecalLightMap() + : TNamed() + , fSSide(0.) + , fS(0) + , fSize(0) + , fData(NULL) {}; + ecalLightMap(const char* fname, const char* title = "Light collection efficiency map"); + Double_t Data(Double_t x, Double_t y) + { + Int_t n = GetNum(x, y); + if (n < 0) + return n; + return fData[n]; + } + Int_t GetNum(Double_t x, Double_t y) + { + Double_t lx = x + 0.5; + Double_t ly = y + 0.5; + if (lx < 0) + lx = 0; + if (ly < 0) + ly = 0; + if (lx > 1) + lx = 1; + if (ly > 1) + ly = 1; + Int_t ix = (Int_t)(lx / fSSide); + Int_t iy = (Int_t)(ly / fSSide); + return iy * fS + ix; + } + virtual ~ecalLightMap() { delete fData; } - ecalLightMap(const ecalLightMap&); - ecalLightMap& operator=(const ecalLightMap&); + private: + /** Read information from file **/ + void Init(const char* filename); + /** Fix a light collection map **/ + void FillGaps(); + /** Set average efficiency of light collection to 1.0 **/ + void Normalize(); + /** Step of the light map **/ + Double_t fSSide; //! + /** Size of side of the light map in steps**/ + Int_t fS; //! + /** Size of the light map **/ + Int_t fSize; //! + /** Light collection efficiency map **/ + Double_t* fData; //! - ClassDef(ecalLightMap, 1) + ecalLightMap(const ecalLightMap&); + ecalLightMap& operator=(const ecalLightMap&); + + ClassDef(ecalLightMap, 1) }; #endif diff --git a/ecal/ecalMatch.cxx b/ecal/ecalMatch.cxx index aeb57213a8..502d608a4f 100644 --- a/ecal/ecalMatch.cxx +++ b/ecal/ecalMatch.cxx @@ -1,13 +1,11 @@ -#include "FairRootManager.h" #include "ecalMatch.h" -#include "ecalCellMC.h" -#include "ecalStructure.h" -#include "ecalReconstructed.h" - +#include "FairRootManager.h" #include "ShipMCTrack.h" - #include "TClonesArray.h" +#include "ecalCellMC.h" +#include "ecalReconstructed.h" +#include "ecalStructure.h" #include #include @@ -15,172 +13,179 @@ using namespace std; -void ecalMatch::Exec(Option_t* option,TClonesArray* reconstructed,TClonesArray* mctracks) +void ecalMatch::Exec(Option_t* option, TClonesArray* reconstructed, TClonesArray* mctracks) { - fReconstucted=reconstructed; - fMCTracks=mctracks; - fEv++; fN=0; fRejected=0; - - Int_t n=fReconstucted->GetEntries(); - Int_t i; - ecalReconstructed* rc; - ecalCell* cell; - ecalCellMC* mccell; - list cells; - list::const_iterator p; - map e; - map e2; - map::const_iterator ep; - map::reverse_iterator rp; - ShipMCTrack* tr; - Int_t trn; - Float_t max; -// if (fVerbose>0) Info("Exec", "Event %d.", fEv); - for(i=0;iAt(i); - cell=fStr->GetHitCell(rc->CellNum()); - cells.clear(); - - if (fUse3x3) - { - cell->GetNeighborsList(cells); //3x3 without maximum - cells.push_back(cell); - } - else - cell->Get5x5Cluster(cells); - - e.clear(); e2.clear(); - //Counting energy depositions for all particles - for(p=cells.begin();p!=cells.end();++p) - { - mccell=(ecalCellMC*)(*p); - for(ep=mccell->GetTrackEnergyBegin();ep!=mccell->GetTrackEnergyEnd();++ep) - { - if (e.find(ep->first)==e.end()) - e[ep->first]=ep->second; - else - e[ep->first]+=ep->second; - } + fReconstucted = reconstructed; + fMCTracks = mctracks; + fEv++; + fN = 0; + fRejected = 0; + + Int_t n = fReconstucted->GetEntries(); + Int_t i; + ecalReconstructed* rc; + ecalCell* cell; + ecalCellMC* mccell; + list cells; + list::const_iterator p; + map e; + map e2; + map::const_iterator ep; + map::reverse_iterator rp; + ShipMCTrack* tr; + Int_t trn; + Float_t max; + // if (fVerbose>0) Info("Exec", "Event %d.", fEv); + for (i = 0; i < n; i++) { + rc = (ecalReconstructed*)fReconstucted->At(i); + cell = fStr->GetHitCell(rc->CellNum()); + cells.clear(); + + if (fUse3x3) { + cell->GetNeighborsList(cells); // 3x3 without maximum + cells.push_back(cell); + } else + cell->Get5x5Cluster(cells); + + e.clear(); + e2.clear(); + // Counting energy depositions for all particles + for (p = cells.begin(); p != cells.end(); ++p) { + mccell = (ecalCellMC*)(*p); + for (ep = mccell->GetTrackEnergyBegin(); ep != mccell->GetTrackEnergyEnd(); ++ep) { + if (e.find(ep->first) == e.end()) + e[ep->first] = ep->second; + else + e[ep->first] += ep->second; + } + } + + //...and parent photons and electrons/positrons + for (ep = e.begin(); ep != e.end(); ++ep) { + if (e2.find(ep->first) == e.end()) + e2[ep->first] = ep->second; + else + e2[ep->first] += ep->second; + if (ep->first < 0 && fVerbose == 0) + continue; + tr = (ShipMCTrack*)fMCTracks->At(ep->first); + if (tr == NULL) { + Info("Exec", "Event %d. Can't find MCTrack %d.", fEv, ep->first); + continue; + } + for (;;) { + if (tr->GetPdgCode() != 22 && TMath::Abs(tr->GetPdgCode()) != 11) + break; + trn = tr->GetMotherId(); + if (trn < 0) + break; + tr = (ShipMCTrack*)fMCTracks->At(trn); + if (tr == NULL) { + Info("Exec", "Event %d. Can't find MCTrack %d.", fEv, ep->first); + break; + } + if (tr->GetPdgCode() != 22 && TMath::Abs(tr->GetPdgCode()) != 11) + break; + if (e2.find(trn) == e2.end()) + e2[trn] = ep->second; + else + e2[trn] += ep->second; + } + } + + // Maximum location + max = -1e11; + trn = -1111; + for (rp = e2.rbegin(); rp != e2.rend(); ++rp) { + if (rp->second > max) { + max = rp->second; + trn = rp->first; + } + } + + if (trn >= 0) { + rc->SetMCTrack(trn); + fN++; + } else + fRejected++; } - //...and parent photons and electrons/positrons - for(ep=e.begin();ep!=e.end();++ep) - { - if (e2.find(ep->first)==e.end()) - e2[ep->first]=ep->second; - else - e2[ep->first]+=ep->second; - if (ep->first<0&&fVerbose==0) continue; - tr=(ShipMCTrack*)fMCTracks->At(ep->first); - if (tr==NULL) - { - Info("Exec", "Event %d. Can't find MCTrack %d.", fEv, ep->first); - continue; - } - for(;;) - { - if (tr->GetPdgCode()!=22&&TMath::Abs(tr->GetPdgCode())!=11) break; - trn=tr->GetMotherId(); - if (trn<0) break; - tr=(ShipMCTrack*)fMCTracks->At(trn); - if (tr==NULL) - { - Info("Exec", "Event %d. Can't find MCTrack %d.", fEv, ep->first); - break; - } - if (tr->GetPdgCode()!=22&&TMath::Abs(tr->GetPdgCode())!=11) break; - if (e2.find(trn)==e2.end()) - e2[trn]=ep->second; - else - e2[trn]+=ep->second; - } - } - - //Maximum location - max=-1e11; trn=-1111; - for(rp=e2.rbegin();rp!=e2.rend();++rp) - { - if (rp->second>max) - { max=rp->second; trn=rp->first;} - } - - if (trn>=0) - { - rc->SetMCTrack(trn); - fN++; - } - else - fRejected++; - } - - if (fVerbose>0) Info("Exec", "Event %d. Matched %d. Skipped %d maxs.", fEv, fN, fRejected); + if (fVerbose > 0) + Info("Exec", "Event %d. Matched %d. Skipped %d maxs.", fEv, fN, fRejected); } /** Standard constructor **/ ecalMatch::ecalMatch(const char* name, const Int_t verbose) - : FairTask(name, verbose), fEv(0), fN(0), fRejected(0), fUse3x3(0), - fReconstucted(NULL), fMCTracks(NULL), fStr(NULL) + : FairTask(name, verbose) + , fEv(0) + , fN(0) + , fRejected(0) + , fUse3x3(0) + , fReconstucted(NULL) + , fMCTracks(NULL) + , fStr(NULL) { - ; + ; } /** Only to comply with frame work. **/ ecalMatch::ecalMatch() - : FairTask(), fEv(0), fN(0), fRejected(0), fUse3x3(0), - fReconstucted(NULL), fMCTracks(NULL), fStr(NULL) + : FairTask() + , fEv(0) + , fN(0) + , fRejected(0) + , fUse3x3(0) + , fReconstucted(NULL) + , fMCTracks(NULL) + , fStr(NULL) { - ; + ; } /** Finish a task **/ void ecalMatch::Finish() { - ; + ; } /** Destructor **/ ecalMatch::~ecalMatch() { - ; + ; } InitStatus ecalMatch::Init() { - FairRootManager* io=FairRootManager::Instance(); - if (!io) - { - Fatal("Init", "Can't find IOManager."); - return kFATAL; - } - fStr=(ecalStructure*)io->GetObject("EcalStructure"); - if (!fStr) - { - Fatal("Init()", "Can't find calorimeter structure in the system."); - return kFATAL; - } - fReconstucted=(TClonesArray*)io->GetObject("EcalReco"); - if (!fReconstucted) - { - Fatal("Init", "Can't find array of reconstructed calorimeter objects in the system."); - return kFATAL; - } - fMCTracks=(TClonesArray*)io->GetObject("MCTrack"); - if (!fMCTracks) - { - Fatal("Init", "Can't find array of MC tracks in the system."); - return kFATAL; - } - - fEv=0; - return kSUCCESS; + FairRootManager* io = FairRootManager::Instance(); + if (!io) { + Fatal("Init", "Can't find IOManager."); + return kFATAL; + } + fStr = (ecalStructure*)io->GetObject("EcalStructure"); + if (!fStr) { + Fatal("Init()", "Can't find calorimeter structure in the system."); + return kFATAL; + } + fReconstucted = (TClonesArray*)io->GetObject("EcalReco"); + if (!fReconstucted) { + Fatal("Init", "Can't find array of reconstructed calorimeter objects in the system."); + return kFATAL; + } + fMCTracks = (TClonesArray*)io->GetObject("MCTrack"); + if (!fMCTracks) { + Fatal("Init", "Can't find array of MC tracks in the system."); + return kFATAL; + } + + fEv = 0; + return kSUCCESS; } void ecalMatch::InitPython(ecalStructure* str, TClonesArray* reconstructed, TClonesArray* mctracks) { - fStr=str; - fReconstucted=reconstructed; - fMCTracks=mctracks; + fStr = str; + fReconstucted = reconstructed; + fMCTracks = mctracks; - fEv=0; + fEv = 0; } diff --git a/ecal/ecalMatch.h b/ecal/ecalMatch.h index a94afc43f1..ced119fae7 100644 --- a/ecal/ecalMatch.h +++ b/ecal/ecalMatch.h @@ -10,43 +10,44 @@ class ecalStructure; class ecalMatch : public FairTask { -public: - /** Standard constructor **/ - ecalMatch(const char* name, const Int_t verbose); - /** Only to comply with frame work. **/ - ecalMatch(); - - /** Should we use 3x3 cluster instead of 5x5 **/ - Int_t GetUse3x3() const {return fUse3x3;} - void SetUse3x3(Int_t use3x3=0) {fUse3x3=use3x3;} - - /** Finish a task **/ - virtual void Finish(); - /** Exec a task **/ - virtual void Exec(Option_t* option, TClonesArray* reconstructed, TClonesArray* mctracks); - /** Initialization **/ - virtual InitStatus Init(); - void InitPython(ecalStructure* str, TClonesArray* reconstructed, TClonesArray* mctracks); - /** Destructor **/ - ~ecalMatch(); -private: - /** Current event **/ - Int_t fEv; - /** Current reconstructed particle **/ - Int_t fN; - /** Number of rejected clusters **/ - Int_t fRejected; - /** Use 3x3 cluster instead of 5x5 **/ - Int_t fUse3x3; - - /** Array of reconstructed objects **/ - TClonesArray* fReconstucted; //! - /** Array of MC tracks **/ - TClonesArray* fMCTracks; //! - /** A calorimeter structure **/ - ecalStructure* fStr; //! - - ClassDef(ecalMatch, 1) + public: + /** Standard constructor **/ + ecalMatch(const char* name, const Int_t verbose); + /** Only to comply with frame work. **/ + ecalMatch(); + + /** Should we use 3x3 cluster instead of 5x5 **/ + Int_t GetUse3x3() const { return fUse3x3; } + void SetUse3x3(Int_t use3x3 = 0) { fUse3x3 = use3x3; } + + /** Finish a task **/ + virtual void Finish(); + /** Exec a task **/ + virtual void Exec(Option_t* option, TClonesArray* reconstructed, TClonesArray* mctracks); + /** Initialization **/ + virtual InitStatus Init(); + void InitPython(ecalStructure* str, TClonesArray* reconstructed, TClonesArray* mctracks); + /** Destructor **/ + ~ecalMatch(); + + private: + /** Current event **/ + Int_t fEv; + /** Current reconstructed particle **/ + Int_t fN; + /** Number of rejected clusters **/ + Int_t fRejected; + /** Use 3x3 cluster instead of 5x5 **/ + Int_t fUse3x3; + + /** Array of reconstructed objects **/ + TClonesArray* fReconstucted; //! + /** Array of MC tracks **/ + TClonesArray* fMCTracks; //! + /** A calorimeter structure **/ + ecalStructure* fStr; //! + + ClassDef(ecalMatch, 1) }; #endif diff --git a/ecal/ecalMaximum.cxx b/ecal/ecalMaximum.cxx index 29033e3ca2..b232fcbb40 100644 --- a/ecal/ecalMaximum.cxx +++ b/ecal/ecalMaximum.cxx @@ -1,40 +1,38 @@ #include "ecalMaximum.h" -#include "ecalCell.h" - #include "TMath.h" +#include "ecalCell.h" #include using namespace std; ecalMaximum::ecalMaximum(ecalCell* cell, Double_t z) - : TObject(), - fCell(cell), - fCX(0.), - fCY(0.), - fX(0.), - fY(0.), - fMark(0), - fTheta(0) + : TObject() + , fCell(cell) + , fCX(0.) + , fCY(0.) + , fX(0.) + , fY(0.) + , fMark(0) + , fTheta(0) { - Double_t me=cell->GetEnergy(); - Double_t e; - Int_t i; - list cells; - list::const_iterator p; - - fCX=cell->GetCenterX(); - fCY=cell->GetCenterY(); - fX=cell->GetEnergy()*fCX; - fY=cell->GetEnergy()*fCY; - - - cell->GetNeighborsList(cells); - for(p=cells.begin();p!=cells.end();++p) - { - fX+=(*p)->GetEnergy()*(*p)->GetCenterX(); - fY+=(*p)->GetEnergy()*(*p)->GetCenterY(); - } - fX/=me; fY/=me; + Double_t me = cell->GetEnergy(); + Double_t e; + Int_t i; + list cells; + list::const_iterator p; + + fCX = cell->GetCenterX(); + fCY = cell->GetCenterY(); + fX = cell->GetEnergy() * fCX; + fY = cell->GetEnergy() * fCY; + + cell->GetNeighborsList(cells); + for (p = cells.begin(); p != cells.end(); ++p) { + fX += (*p)->GetEnergy() * (*p)->GetCenterX(); + fY += (*p)->GetEnergy() * (*p)->GetCenterY(); + } + fX /= me; + fY /= me; } diff --git a/ecal/ecalMaximum.h b/ecal/ecalMaximum.h index b8c67dfc1a..e0743e8e3e 100644 --- a/ecal/ecalMaximum.h +++ b/ecal/ecalMaximum.h @@ -8,49 +8,64 @@ class ecalCell; ** electron identification procedures **/ class ecalMaximum : public TObject { -public: - /** An emtry constructor **/ - ecalMaximum() : TObject(), fCell(NULL), fCX(0.), fCY(0.), fX(0.), fY(0.), fMark(0), fTheta(0) - {}; - /** Simplest constructor **/ - ecalMaximum(ecalCell* cell, Double_t z); - /** Standard constructor **/ - ecalMaximum(ecalCell* cell, Double_t cx, Double_t cy, Double_t x, Double_t y); - ~ecalMaximum() {}; - - ecalCell* Cell() const {return fCell;} - Double_t CX() const {return fCX;} - Double_t CY() const {return fCY;} - Double_t X() const {return fX;} - Double_t Y() const {return fY;} - Int_t Mark() const {return fMark;} - Double_t Theta() const {return fTheta;} - - void SetMark(Int_t mark) {fMark=mark;} - void SetTheta(Double_t theta) {fTheta=theta;} -private: - ecalCell* fCell; - /** Coordinates of cell **/ - Double_t fCX; - Double_t fCY; - /** Coobdinates of center of mass of maximum subcluster **/ - Double_t fX; - Double_t fY; - /** A mark. Used for maximum exclusion. **/ - Int_t fMark; - /** Theta angle. 0 by default. Should be set outside if information - * about photon origin are here. **/ - Double_t fTheta; - - ecalMaximum(const ecalMaximum&); - ecalMaximum& operator=(const ecalMaximum&); - - ClassDef(ecalMaximum, 1) + public: + /** An emtry constructor **/ + ecalMaximum() + : TObject() + , fCell(NULL) + , fCX(0.) + , fCY(0.) + , fX(0.) + , fY(0.) + , fMark(0) + , fTheta(0) {}; + /** Simplest constructor **/ + ecalMaximum(ecalCell* cell, Double_t z); + /** Standard constructor **/ + ecalMaximum(ecalCell* cell, Double_t cx, Double_t cy, Double_t x, Double_t y); + ~ecalMaximum() {}; + + ecalCell* Cell() const { return fCell; } + Double_t CX() const { return fCX; } + Double_t CY() const { return fCY; } + Double_t X() const { return fX; } + Double_t Y() const { return fY; } + Int_t Mark() const { return fMark; } + Double_t Theta() const { return fTheta; } + + void SetMark(Int_t mark) { fMark = mark; } + void SetTheta(Double_t theta) { fTheta = theta; } + + private: + ecalCell* fCell; + /** Coordinates of cell **/ + Double_t fCX; + Double_t fCY; + /** Coobdinates of center of mass of maximum subcluster **/ + Double_t fX; + Double_t fY; + /** A mark. Used for maximum exclusion. **/ + Int_t fMark; + /** Theta angle. 0 by default. Should be set outside if information + * about photon origin are here. **/ + Double_t fTheta; + + ecalMaximum(const ecalMaximum&); + ecalMaximum& operator=(const ecalMaximum&); + + ClassDef(ecalMaximum, 1) }; inline ecalMaximum::ecalMaximum(ecalCell* cell, Double_t cx, Double_t cy, Double_t x, Double_t y) - : TObject(), fCell(cell), fCX(cx), fCY(cy), fX(x), fY(y), fMark(0), fTheta(0) + : TObject() + , fCell(cell) + , fCX(cx) + , fCY(cy) + , fX(x) + , fY(y) + , fMark(0) + , fTheta(0) { - ; + ; } #endif diff --git a/ecal/ecalMaximumLocator.cxx b/ecal/ecalMaximumLocator.cxx index 98d7a17584..709aa7e769 100644 --- a/ecal/ecalMaximumLocator.cxx +++ b/ecal/ecalMaximumLocator.cxx @@ -1,117 +1,114 @@ #include "ecalMaximumLocator.h" -#include "ecalStructure.h" -#include "ecalInf.h" -#include "ecalMaximum.h" -#include "ecalCell.h" - #include "FairRootManager.h" - #include "TClonesArray.h" +#include "ecalCell.h" +#include "ecalInf.h" +#include "ecalMaximum.h" +#include "ecalStructure.h" -#include #include +#include using namespace std; ecalMaximumLocator::ecalMaximumLocator() - : FairTask(), - fMaximums(NULL), - fStr(NULL), - fECut(0.015), - fEvent(-1) -{ -} + : FairTask() + , fMaximums(NULL) + , fStr(NULL) + , fECut(0.015) + , fEvent(-1) +{} ecalMaximumLocator::ecalMaximumLocator(const char* name, Int_t verbose) - : FairTask(name, verbose), - fMaximums(NULL), - fStr(NULL), - fECut(0.015), - fEvent(-1) -{ -} + : FairTask(name, verbose) + , fMaximums(NULL) + , fStr(NULL) + , fECut(0.015) + , fEvent(-1) +{} ecalMaximumLocator::~ecalMaximumLocator() { - if (fMaximums) - delete fMaximums; + if (fMaximums) + delete fMaximums; } InitStatus ecalMaximumLocator::Init() { - FairRootManager* fManager=FairRootManager::Instance(); - if (!fManager) - { - Fatal("Init", "Can't find a Root Manager."); - return kFATAL; - } - fStr=(ecalStructure*)fManager->GetObject("EcalStructure"); - if (!fStr) - { - Fatal("Init()", "Can't find calorimeter structure in the system."); - return kFATAL; - } - fMaximums=new TClonesArray("ecalMaximum", 3000); - fManager->Register("EcalMaximums", "ECAL", fMaximums, kFALSE); - fEvent=0; - return kSUCCESS; + FairRootManager* fManager = FairRootManager::Instance(); + if (!fManager) { + Fatal("Init", "Can't find a Root Manager."); + return kFATAL; + } + fStr = (ecalStructure*)fManager->GetObject("EcalStructure"); + if (!fStr) { + Fatal("Init()", "Can't find calorimeter structure in the system."); + return kFATAL; + } + fMaximums = new TClonesArray("ecalMaximum", 3000); + fManager->Register("EcalMaximums", "ECAL", fMaximums, kFALSE); + fEvent = 0; + return kSUCCESS; } TClonesArray* ecalMaximumLocator::InitPython(ecalStructure* structure) { - fStr=structure; - fMaximums=new TClonesArray("ecalMaximum", 3000); - return fMaximums; + fStr = structure; + fMaximums = new TClonesArray("ecalMaximum", 3000); + return fMaximums; } void ecalMaximumLocator::Finish() { - fMaximums->Clear(); + fMaximums->Clear(); } void ecalMaximumLocator::Exec(const Option_t* opt) { - list all; - list cells; - list::const_iterator p; - list::const_iterator r; - Double_t e; - Double_t z=fStr->GetEcalInf()->GetZPos(); - Double_t r1; - Double_t r2; - Double_t t; - Int_t n=0; + list all; + list cells; + list::const_iterator p; + list::const_iterator r; + Double_t e; + Double_t z = fStr->GetEcalInf()->GetZPos(); + Double_t r1; + Double_t r2; + Double_t t; + Int_t n = 0; - fEvent++; - fMaximums->Clear(); - fStr->GetCells(all); - for(p=all.begin();p!=all.end();++p) - { - e=(*p)->GetEnergy(); - r1=(*p)->GetCenterX(); r1*=r1; - t=(*p)->GetCenterY(); t*=t; - r1=TMath::Sqrt(r1*r1+t*t); - if (eGetNeighborsList(cells); - for(r=cells.begin();r!=cells.end();++r) - { - if ((*r)->GetEnergy()GetEnergy()==e) - { - r2=(*r)->GetCenterX(); r2*=r2; - t=(*r)->GetCenterY(); t*=t; - r2=TMath::Sqrt(r2*r2+t*t); - if (r1>=r2) continue; - } - break; + fEvent++; + fMaximums->Clear(); + fStr->GetCells(all); + for (p = all.begin(); p != all.end(); ++p) { + e = (*p)->GetEnergy(); + r1 = (*p)->GetCenterX(); + r1 *= r1; + t = (*p)->GetCenterY(); + t *= t; + r1 = TMath::Sqrt(r1 * r1 + t * t); + if (e < fECut) + continue; + (*p)->GetNeighborsList(cells); + for (r = cells.begin(); r != cells.end(); ++r) { + if ((*r)->GetEnergy() < e) + continue; + if ((*r)->GetEnergy() == e) { + r2 = (*r)->GetCenterX(); + r2 *= r2; + t = (*r)->GetCenterY(); + t *= t; + r2 = TMath::Sqrt(r2 * r2 + t * t); + if (r1 >= r2) + continue; + } + break; + } + if (r != cells.end()) + continue; + // cout << e << " : " << (*p)->GetCenterX() << ", " << (*p)->GetCenterY() << endl; + new ((*fMaximums)[n++]) ecalMaximum(*p, z); } - if (r!=cells.end()) - continue; -// cout << e << " : " << (*p)->GetCenterX() << ", " << (*p)->GetCenterY() << endl; - new ((*fMaximums)[n++]) ecalMaximum(*p, z); - } - if (fVerbose>9) - Info("Exec", "%d maximums found", n); + if (fVerbose > 9) + Info("Exec", "%d maximums found", n); } diff --git a/ecal/ecalMaximumLocator.h b/ecal/ecalMaximumLocator.h index 51c49e0dc2..a0a0fa1f80 100644 --- a/ecal/ecalMaximumLocator.h +++ b/ecal/ecalMaximumLocator.h @@ -9,32 +9,33 @@ class TClonesArray; class ecalMaximumLocator : public FairTask { -public: - /** An empty constructor **/ - ecalMaximumLocator(); - ecalMaximumLocator(const char* name, Int_t verbose); - virtual void Exec(const Option_t* option); - virtual InitStatus Init(); - TClonesArray* InitPython(ecalStructure* structure); - virtual void Finish(); - ~ecalMaximumLocator(); - - Double_t ECut() const {return fECut;} - void SetECut(Double_t ecut=0.005) {fECut=ecut;} -private: - /** Array of found maximums **/ - TClonesArray* fMaximums; - /** A calorimeter structure **/ - ecalStructure* fStr; - /** energy cut on energy of maximum**/ - Double_t fECut; - /** Current event **/ - Int_t fEvent; - - ecalMaximumLocator(const ecalMaximumLocator&); - ecalMaximumLocator& operator=(const ecalMaximumLocator&); - - ClassDef(ecalMaximumLocator, 1); + public: + /** An empty constructor **/ + ecalMaximumLocator(); + ecalMaximumLocator(const char* name, Int_t verbose); + virtual void Exec(const Option_t* option); + virtual InitStatus Init(); + TClonesArray* InitPython(ecalStructure* structure); + virtual void Finish(); + ~ecalMaximumLocator(); + + Double_t ECut() const { return fECut; } + void SetECut(Double_t ecut = 0.005) { fECut = ecut; } + + private: + /** Array of found maximums **/ + TClonesArray* fMaximums; + /** A calorimeter structure **/ + ecalStructure* fStr; + /** energy cut on energy of maximum**/ + Double_t fECut; + /** Current event **/ + Int_t fEvent; + + ecalMaximumLocator(const ecalMaximumLocator&); + ecalMaximumLocator& operator=(const ecalMaximumLocator&); + + ClassDef(ecalMaximumLocator, 1); }; #endif diff --git a/ecal/ecalModule.cxx b/ecal/ecalModule.cxx index c6049890fb..3a5d4c98fd 100644 --- a/ecal/ecalModule.cxx +++ b/ecal/ecalModule.cxx @@ -7,86 +7,113 @@ #include "ecalModule.h" -#include "ecalCellMC.h" - #include "TMath.h" +#include "ecalCellMC.h" using std::list; using std::vector; //----------------------------------------------------------------------------- -ecalModule::ecalModule(char type, Int_t cellnumber, Float_t x1, Float_t y1, Float_t x2, Float_t y2, Int_t mc, Float_t energy) - : ecalCell(cellnumber, x1,y1,x2,y2, type, energy), - fDx(x2-x1), - fDy(y2-y1), - fCells() +ecalModule::ecalModule(char type, + Int_t cellnumber, + Float_t x1, + Float_t y1, + Float_t x2, + Float_t y2, + Int_t mc, + Float_t energy) + : ecalCell(cellnumber, x1, y1, x2, y2, type, energy) + , fDx(x2 - x1) + , fDy(y2 - y1) + , fCells() { - if (GetType()<1) return; - - Int_t i; - Int_t j; - Int_t mt; - Int_t num; - - mt=type; - fCells.resize(mt*mt,NULL); - - num=cellnumber/100; - - if (mc==0) - for(i=0;i=GetType()||y>=GetType()) return NULL; - return fCells[y*GetType()+x]; + if (x < 0 || y < 0 || x >= GetType() || y >= GetType()) + return NULL; + return fCells[y * GetType() + x]; } //----------------------------------------------------------------------------- ecalCell* ecalModule::FindCell(Float_t x, Float_t y) const { - Int_t ix=(Int_t)TMath::Floor( (x-GetX1())/GetDX()*GetType() ); - Int_t iy=(Int_t)TMath::Floor( (y-GetY1())/GetDY()*GetType() ); - if (ix<0) ix=0; if (ix>=GetType()) ix=GetType()-1; - if (iy<0) iy=0; if (iy>=GetType()) iy=GetType()-1; - return At(ix,iy); + Int_t ix = (Int_t)TMath::Floor((x - GetX1()) / GetDX() * GetType()); + Int_t iy = (Int_t)TMath::Floor((y - GetY1()) / GetDY() * GetType()); + if (ix < 0) + ix = 0; + if (ix >= GetType()) + ix = GetType() - 1; + if (iy < 0) + iy = 0; + if (iy >= GetType()) + iy = GetType() - 1; + return At(ix, iy); } //----------------------------------------------------------------------------- void ecalModule::AddEnergy(Float_t x, Float_t y, Float_t energy) { - ecalCell* tmp=FindCell(x,y); - if (!tmp) return; - tmp->AddEnergy(energy); - ecalCell::AddEnergy(energy); + ecalCell* tmp = FindCell(x, y); + if (!tmp) + return; + tmp->AddEnergy(energy); + ecalCell::AddEnergy(energy); } //----------------------------------------------------------------------------- list ecalModule::GetCellsX(Float_t x) const { - list tmp; - vector::const_iterator p; + list tmp; + vector::const_iterator p; - for(p=fCells.begin();p!=fCells.end();++p) - if (x>(*p)->GetX1()&&x<(*p)->GetX2()) tmp.push_back(*p); - return tmp; + for (p = fCells.begin(); p != fCells.end(); ++p) + if (x > (*p)->GetX1() && x < (*p)->GetX2()) + tmp.push_back(*p); + return tmp; } //----------------------------------------------------------------------------- list ecalModule::GetCellsY(Float_t y) const { - list tmp; - vector::const_iterator p; + list tmp; + vector::const_iterator p; - for(p=fCells.begin();p!=fCells.end();++p) - if (y>(*p)->GetY1()&&y<(*p)->GetY2()) tmp.push_back(*p); - return tmp; + for (p = fCells.begin(); p != fCells.end(); ++p) + if (y > (*p)->GetY1() && y < (*p)->GetY2()) + tmp.push_back(*p); + return tmp; } diff --git a/ecal/ecalModule.h b/ecal/ecalModule.h index f9ffc4ee78..f230b5c2ae 100644 --- a/ecal/ecalModule.h +++ b/ecal/ecalModule.h @@ -10,53 +10,62 @@ #include "ecalCell.h" -#include #include +#include class ecalModule : public ecalCell { -public: - // Set mc==1 to construct ecalCellMC, not ecalCell - ecalModule(char type=1, Int_t cellnumber=-1, Float_t x1=0, Float_t y1=0, Float_t x2=0, Float_t y2=0, Int_t mc=0,Float_t energy=0); - - ecalCell* Locate(Int_t x, Int_t y) const; - - //Faster than Locate, but doesn't check boundaries - inline ecalCell* At(Int_t x, Int_t y) const {return fCells[y*GetType()+x];} - ecalCell* FindCell(Float_t x, Float_t y) const; - void AddEnergy(Float_t x, Float_t y, Float_t energy); - inline Float_t GetEnergy(Float_t x, Float_t y) const - { - ecalCell* tmp=FindCell(x,y); - if (tmp) return tmp->GetEnergy(); - return -1; - } - void ResetModule(); - - inline Float_t GetDX() const {return fDx;} - inline Float_t GetDY() const {return fDy;} - std::vector GetCells() const {return fCells;} - - //returns cells for which X1 GetCellsX(Float_t x) const; - //returns cells for which Y1 GetCellsY(Float_t y) const; - -private: - /** module x-size **/ - Float_t fDx; - /** module y-size **/ - Float_t fDy; - /** list of cells contained in a module **/ - std::vector fCells; - - ClassDef(ecalModule,1); + public: + // Set mc==1 to construct ecalCellMC, not ecalCell + ecalModule(char type = 1, + Int_t cellnumber = -1, + Float_t x1 = 0, + Float_t y1 = 0, + Float_t x2 = 0, + Float_t y2 = 0, + Int_t mc = 0, + Float_t energy = 0); + + ecalCell* Locate(Int_t x, Int_t y) const; + + // Faster than Locate, but doesn't check boundaries + inline ecalCell* At(Int_t x, Int_t y) const { return fCells[y * GetType() + x]; } + ecalCell* FindCell(Float_t x, Float_t y) const; + void AddEnergy(Float_t x, Float_t y, Float_t energy); + inline Float_t GetEnergy(Float_t x, Float_t y) const + { + ecalCell* tmp = FindCell(x, y); + if (tmp) + return tmp->GetEnergy(); + return -1; + } + void ResetModule(); + + inline Float_t GetDX() const { return fDx; } + inline Float_t GetDY() const { return fDy; } + std::vector GetCells() const { return fCells; } + + // returns cells for which X1 GetCellsX(Float_t x) const; + // returns cells for which Y1 GetCellsY(Float_t y) const; + + private: + /** module x-size **/ + Float_t fDx; + /** module y-size **/ + Float_t fDy; + /** list of cells contained in a module **/ + std::vector fCells; + + ClassDef(ecalModule, 1); }; inline void ecalModule::ResetModule() { - ResetEnergyFast(); - for(UInt_t i=0;iResetEnergyFast(); + ResetEnergyFast(); + for (UInt_t i = 0; i < fCells.size(); i++) + fCells[i]->ResetEnergyFast(); } #endif diff --git a/ecal/ecalPoint.cxx b/ecal/ecalPoint.cxx index b0ee76d5db..c820992434 100644 --- a/ecal/ecalPoint.cxx +++ b/ecal/ecalPoint.cxx @@ -4,38 +4,38 @@ using std::cout; using std::endl; - // ----- Default constructor ------------------------------------------- ecalPoint::ecalPoint() - : FairMCPoint() -{ -} + : FairMCPoint() +{} // ------------------------------------------------------------------------- // ----- Standard constructor ------------------------------------------ -ecalPoint::ecalPoint(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t tof, Double_t length, - Double_t eLoss, Int_t pdgcode) - : FairMCPoint(trackID, detID, pos, mom, tof, length, eLoss), fPdgCode(pdgcode) -{ -} +ecalPoint::ecalPoint(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t tof, + Double_t length, + Double_t eLoss, + Int_t pdgcode) + : FairMCPoint(trackID, detID, pos, mom, tof, length, eLoss) + , fPdgCode(pdgcode) +{} // ------------------------------------------------------------------------- // ----- Destructor ---------------------------------------------------- -ecalPoint::~ecalPoint() { } +ecalPoint::~ecalPoint() {} // ------------------------------------------------------------------------- // ----- Public method Print ------------------------------------------- void ecalPoint::Print(const Option_t* opt) const { - cout << "-I- ecalPoint: ecal point for track " << fTrackID - << "(PDG=" << fPdgCode << ") in detector " << fDetectorID << endl; - cout << " Position (" << fX << ", " << fY << ", " << fZ - << ") cm" << endl; - cout << " Momentum (" << fPx << ", " << fPy << ", " << fPz - << ") GeV" << endl; - cout << " Time " << fTime << " ns, Length " << fLength - << " cm, Energy loss " << fELoss*1.0e06 << " keV" << endl; + cout << "-I- ecalPoint: ecal point for track " << fTrackID << "(PDG=" << fPdgCode << ") in detector " << fDetectorID + << endl; + cout << " Position (" << fX << ", " << fY << ", " << fZ << ") cm" << endl; + cout << " Momentum (" << fPx << ", " << fPy << ", " << fPz << ") GeV" << endl; + cout << " Time " << fTime << " ns, Length " << fLength << " cm, Energy loss " << fELoss * 1.0e06 << " keV" + << endl; } // ------------------------------------------------------------------------- diff --git a/ecal/ecalPoint.h b/ecal/ecalPoint.h index 41fc9900b5..b752505d2e 100644 --- a/ecal/ecalPoint.h +++ b/ecal/ecalPoint.h @@ -1,24 +1,19 @@ #ifndef ECALPOINT_H #define ECALPOINT_H 1 - #include "FairMCPoint.h" - +#include "TClonesArray.h" #include "TObject.h" #include "TVector3.h" -#include "TClonesArray.h" - class ecalPoint : public FairMCPoint { - friend class ecal; + friend class ecal; public: - /** Default constructor **/ ecalPoint(); - /** Constructor with arguments *@param trackID Index of MCTrack *@param detID Detector ID @@ -28,8 +23,14 @@ class ecalPoint : public FairMCPoint *@param length Track length since creation [cm] *@param eLoss Energy deposit [GeV] **/ - ecalPoint(Int_t trackID, Int_t detID, TVector3 pos, TVector3 mom, - Double_t tof, Double_t length, Double_t eLoss, Int_t pdgcode=0); + ecalPoint(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t tof, + Double_t length, + Double_t eLoss, + Int_t pdgcode = 0); /** Constructor with arguments for lite points *@param trackID Index of MCTrack @@ -37,12 +38,19 @@ class ecalPoint : public FairMCPoint *@param tof Time since event start [ns] *@param eLoss Energy deposit [GeV] **/ - ecalPoint(Int_t trackID, Int_t detID, Double32_t tof, Double32_t eloss, UInt_t EventId=0) - : FairMCPoint(trackID, detID, TVector3(-1111, -1111, -1111), TVector3(-1111, -1111, -1111), tof, -1111, eloss, EventId), fPdgCode(0) - {}; - - Int_t GetPdgCode() const {return fPdgCode;} - Int_t PdgCode() const {return fPdgCode;} + ecalPoint(Int_t trackID, Int_t detID, Double32_t tof, Double32_t eloss, UInt_t EventId = 0) + : FairMCPoint(trackID, + detID, + TVector3(-1111, -1111, -1111), + TVector3(-1111, -1111, -1111), + tof, + -1111, + eloss, + EventId) + , fPdgCode(0) {}; + + Int_t GetPdgCode() const { return fPdgCode; } + Int_t PdgCode() const { return fPdgCode; } /** Destructor **/ virtual ~ecalPoint(); @@ -57,8 +65,7 @@ class ecalPoint : public FairMCPoint Int_t fPdgCode; - ClassDef(ecalPoint,1) - + ClassDef(ecalPoint, 1) }; #endif diff --git a/ecal/ecalPreCluster.h b/ecal/ecalPreCluster.h index 90f8e899f4..2f1df4210d 100644 --- a/ecal/ecalPreCluster.h +++ b/ecal/ecalPreCluster.h @@ -7,47 +7,62 @@ #include "ecalMaximum.h" #include -//#include +// #include class ecalPreCluster { -public: - ecalPreCluster(const std::list cells, ecalCell* max, Double_t energy=-1111.0) - : fCells(cells), fMaximum(max), fEnergy(energy), fMax(NULL), fMark(0) - { - } - - ecalPreCluster(const std::list cells, ecalMaximum* max, Double_t energy=-1111.0) - : fCells(cells), fMaximum(max->Cell()), fEnergy(energy), fMax(max), fMark(0) - { -// std::cout << "list: " << fEnergy << std::endl; - } - - ecalPreCluster(ecalCell** cells, Int_t size, ecalCell* max, Double_t energy=-1111.0) - : fCells(), fMaximum(max), fEnergy(energy), fMax(NULL), fMark(0) - { - fCells.clear(); - for(Int_t i=0;iCell()), fEnergy(energy), fMax(max), fMark(0) - { - fCells.clear(); - for(Int_t i=0;i fCells; - ecalCell* fMaximum; - Double_t fEnergy; - ecalMaximum* fMax; //! - Int_t fMark; - - private: - ecalPreCluster(const ecalPreCluster&); - ecalPreCluster& operator=(const ecalPreCluster&); + public: + ecalPreCluster(const std::list cells, ecalCell* max, Double_t energy = -1111.0) + : fCells(cells) + , fMaximum(max) + , fEnergy(energy) + , fMax(NULL) + , fMark(0) + {} + + ecalPreCluster(const std::list cells, ecalMaximum* max, Double_t energy = -1111.0) + : fCells(cells) + , fMaximum(max->Cell()) + , fEnergy(energy) + , fMax(max) + , fMark(0) + { + // std::cout << "list: " << fEnergy << std::endl; + } + + ecalPreCluster(ecalCell** cells, Int_t size, ecalCell* max, Double_t energy = -1111.0) + : fCells() + , fMaximum(max) + , fEnergy(energy) + , fMax(NULL) + , fMark(0) + { + fCells.clear(); + for (Int_t i = 0; i < size; i++) + fCells.push_back(cells[i]); + } + + ecalPreCluster(ecalCell** cells, Int_t size, ecalMaximum* max, Double_t energy = -1111.0) + : fCells() + , fMaximum(max->Cell()) + , fEnergy(energy) + , fMax(max) + , fMark(0) + { + fCells.clear(); + for (Int_t i = 0; i < size; i++) + fCells.push_back(cells[i]); + } + + std::list fCells; + ecalCell* fMaximum; + Double_t fEnergy; + ecalMaximum* fMax; //! + Int_t fMark; + + private: + ecalPreCluster(const ecalPreCluster&); + ecalPreCluster& operator=(const ecalPreCluster&); }; #endif diff --git a/ecal/ecalPrepare.cxx b/ecal/ecalPrepare.cxx index b1d822244f..2b43091973 100644 --- a/ecal/ecalPrepare.cxx +++ b/ecal/ecalPrepare.cxx @@ -1,126 +1,123 @@ #include "ecalPrepare.h" -#include "ecalStructure.h" - #include "FairRootManager.h" - #include "TRandom.h" #include "TSystem.h" +#include "ecalStructure.h" -#include #include +#include #include using namespace std; /** --- Default constructor --------------------------------------------------- **/ ecalPrepare::ecalPrepare() - : FairTask(), - fPedestal(80), - fADCMax(16384), - fADCChannel(1.0e-3), - fStr(NULL), fChannelMap() + : FairTask() + , fPedestal(80) + , fADCMax(16384) + , fADCChannel(1.0e-3) + , fStr(NULL) + , fChannelMap() { - fChannelMap.clear(); + fChannelMap.clear(); } /** --- Standard constructor. Use this ---------------------------------------- **/ ecalPrepare::ecalPrepare(const char* name, Int_t iVerbose) - : FairTask(name, iVerbose), - fPedestal(80), - fADCMax(16384), - fADCChannel(1.0e-3), - fStr(NULL), fChannelMap() + : FairTask(name, iVerbose) + , fPedestal(80) + , fADCMax(16384) + , fADCChannel(1.0e-3) + , fStr(NULL) + , fChannelMap() { - fChannelMap.clear(); + fChannelMap.clear(); } /** --- Ugly load of map channel number -> ADC channel from the file ---------- **/ void ecalPrepare::LoadChannelMap(const char* filename) { - map tmp; - TString fname=filename; gSystem->ExpandPathName(fname); - ifstream f(filename); - Int_t ch; - Int_t i=0; - Float_t adc; - - tmp.clear(); - for(;;) - { - f >> ch; if (f.eof()) break; - f >> adc; if (f.eof()) break; - tmp[ch]=adc; - i++; - } - if (fVerbose>999) - Info("LoadChannelMap", "%d records read", i); - f.close(); - SetChannelMap(tmp); + map tmp; + TString fname = filename; + gSystem->ExpandPathName(fname); + ifstream f(filename); + Int_t ch; + Int_t i = 0; + Float_t adc; + + tmp.clear(); + for (;;) { + f >> ch; + if (f.eof()) + break; + f >> adc; + if (f.eof()) + break; + tmp[ch] = adc; + i++; + } + if (fVerbose > 999) + Info("LoadChannelMap", "%d records read", i); + f.close(); + SetChannelMap(tmp); } /** --- Initialization of the task -------------------------------------------- **/ InitStatus ecalPrepare::Init() { - FairRootManager* manager=FairRootManager::Instance(); - if (!manager) - { - Fatal("Init()", "Can't find IOManager."); - return kFATAL; - } + FairRootManager* manager = FairRootManager::Instance(); + if (!manager) { + Fatal("Init()", "Can't find IOManager."); + return kFATAL; + } - fStr=(ecalStructure*)manager->GetObject("EcalStructure"); - if (!fStr) - { - Fatal("Init()", "Can't find calorimeter structure in the system."); - return kFATAL; - } + fStr = (ecalStructure*)manager->GetObject("EcalStructure"); + if (!fStr) { + Fatal("Init()", "Can't find calorimeter structure in the system."); + return kFATAL; + } - return kSUCCESS; + return kSUCCESS; } void ecalPrepare::InitPython(ecalStructure* structure) { - fStr=structure; + fStr = structure; } /** --- Executed task --------------------------------------------------------- **/ void ecalPrepare::Exec(Option_t* option) { - ecalCell* cell; - list cells; - fStr->GetCells(cells); - list::const_iterator p=cells.begin(); - Short_t adc; - - for(;p!=cells.end();++p) - { - cell=(*p); - adc=cell->GetADC(); - adc-=fPedestal; //if (adc<0) adc=0; - if (fChannelMap.empty()) - cell->SetEnergy(adc*fADCChannel); - else - if (fChannelMap.find(cell->GetCellNumber())==fChannelMap.end()) - { - Error("Exec", "Channel %d not found in map. Using default value!", cell->GetCellNumber()); - //TODO: Should we insert Fatal here? - cell->SetEnergy(adc*fADCChannel); - } - else - { - cell->SetEnergy(adc*fChannelMap[cell->GetCellNumber()]); + ecalCell* cell; + list cells; + fStr->GetCells(cells); + list::const_iterator p = cells.begin(); + Short_t adc; + + for (; p != cells.end(); ++p) { + cell = (*p); + adc = cell->GetADC(); + adc -= fPedestal; // if (adc<0) adc=0; + if (fChannelMap.empty()) + cell->SetEnergy(adc * fADCChannel); + else if (fChannelMap.find(cell->GetCellNumber()) == fChannelMap.end()) { + Error("Exec", "Channel %d not found in map. Using default value!", cell->GetCellNumber()); + // TODO: Should we insert Fatal here? + cell->SetEnergy(adc * fADCChannel); + } else { + cell->SetEnergy(adc * fChannelMap[cell->GetCellNumber()]); + } } - } } /** --- Finish task ----------------------------------------------------------- **/ void ecalPrepare::Finish() { - ; + ; } /** --- Destructor ------------------------------------------------------------ **/ ecalPrepare::~ecalPrepare() { - ; + ; } diff --git a/ecal/ecalPrepare.h b/ecal/ecalPrepare.h index 274b5ae6fa..07977a54c2 100644 --- a/ecal/ecalPrepare.h +++ b/ecal/ecalPrepare.h @@ -12,50 +12,51 @@ class ecalStructure; class ecalPrepare : public FairTask { -public: - /** Default constructor **/ - ecalPrepare(); - /** Standard constructor. Use this **/ - ecalPrepare(const char* name, Int_t iVerbose); - /** Destructor **/ - virtual ~ecalPrepare(); - /** Initialization of the task **/ - virtual InitStatus Init(); - void InitPython(ecalStructure* structure); - /** Executed task **/ - virtual void Exec(Option_t* option); - /** Finish task **/ - virtual void Finish(); - - void SetPedestal(Short_t ped=80) {fPedestal=ped;} - void SetADCMax(Short_t adcmax=16384) {fADCMax=adcmax;} - void SetADCChannel(Float_t adcchannel=1.0e-3) {fADCChannel=adcchannel;} - - //Map: channel number -> ADC channel in GeV - void SetChannelMap(std::map map) {fChannelMap=map;} - //TODO: An ugly way, need database here - void LoadChannelMap(const char* filename); - - Short_t GetPedestal() const {return fPedestal;} - Short_t GetADCMax() const {return fADCMax;} - Float_t GetADCChannel() const {return fADCChannel;} -private: - // Pedestal - Short_t fPedestal; - // ADC maximum - Short_t fADCMax; - // ADC channel (in energy deposition in _SCINTILLATOR_) - Float_t fADCChannel; - // Calorimeter structure - ecalStructure* fStr; //! - - // May be better use Float_t*? - std::map fChannelMap; //! Map: channel number -> ADC channel in GeV - - ecalPrepare(const ecalPrepare&); - ecalPrepare& operator=(const ecalPrepare&); - - ClassDef(ecalPrepare, 1); + public: + /** Default constructor **/ + ecalPrepare(); + /** Standard constructor. Use this **/ + ecalPrepare(const char* name, Int_t iVerbose); + /** Destructor **/ + virtual ~ecalPrepare(); + /** Initialization of the task **/ + virtual InitStatus Init(); + void InitPython(ecalStructure* structure); + /** Executed task **/ + virtual void Exec(Option_t* option); + /** Finish task **/ + virtual void Finish(); + + void SetPedestal(Short_t ped = 80) { fPedestal = ped; } + void SetADCMax(Short_t adcmax = 16384) { fADCMax = adcmax; } + void SetADCChannel(Float_t adcchannel = 1.0e-3) { fADCChannel = adcchannel; } + + // Map: channel number -> ADC channel in GeV + void SetChannelMap(std::map map) { fChannelMap = map; } + // TODO: An ugly way, need database here + void LoadChannelMap(const char* filename); + + Short_t GetPedestal() const { return fPedestal; } + Short_t GetADCMax() const { return fADCMax; } + Float_t GetADCChannel() const { return fADCChannel; } + + private: + // Pedestal + Short_t fPedestal; + // ADC maximum + Short_t fADCMax; + // ADC channel (in energy deposition in _SCINTILLATOR_) + Float_t fADCChannel; + // Calorimeter structure + ecalStructure* fStr; //! + + // May be better use Float_t*? + std::map fChannelMap; //! Map: channel number -> ADC channel in GeV + + ecalPrepare(const ecalPrepare&); + ecalPrepare& operator=(const ecalPrepare&); + + ClassDef(ecalPrepare, 1); }; #endif diff --git a/ecal/ecalReco.cxx b/ecal/ecalReco.cxx index 3776ed4b93..2908b675c3 100644 --- a/ecal/ecalReco.cxx +++ b/ecal/ecalReco.cxx @@ -1,13 +1,12 @@ -#include "FairRootManager.h" #include "ecalReco.h" +#include "FairRootManager.h" +#include "TClonesArray.h" #include "ecalCell.h" #include "ecalCluster.h" -#include "ecalStructure.h" #include "ecalClusterCalibration.h" #include "ecalReconstructed.h" - -#include "TClonesArray.h" +#include "ecalStructure.h" #include #include @@ -16,289 +15,299 @@ using namespace std; void ecalReco::Exec(Option_t* option) { - fEv++; fN=0; fRejected=0; fRejectedP=0; -// if (fVerbose>0) Info("Exec", "Event %d.", fEv); + fEv++; + fN = 0; + fRejected = 0; + fRejectedP = 0; + // if (fVerbose>0) Info("Exec", "Event %d.", fEv); - fReconstucted->Delete(); + fReconstucted->Delete(); - Int_t i; - Int_t nc=fClusters->GetEntriesFast(); - ecalCluster* cls; - ecalReconstructed* reco; - Float_t x; - Float_t y; - ecalCell* maxs[40]; //maximums of the cluster - Float_t e3[40]; //energy in 3x3 area near the maximum - list lists[40]; //lists of 5x5-3x3 clusters near the maximum - Int_t n; - Int_t j; - Int_t k; - list cells; - list cells2; - list::const_iterator p; - list::const_iterator p2; - Float_t rawE; - Float_t ourE; - Float_t allE; - ecalCell* tcell; + Int_t i; + Int_t nc = fClusters->GetEntriesFast(); + ecalCluster* cls; + ecalReconstructed* reco; + Float_t x; + Float_t y; + ecalCell* maxs[40]; // maximums of the cluster + Float_t e3[40]; // energy in 3x3 area near the maximum + list lists[40]; // lists of 5x5-3x3 clusters near the maximum + Int_t n; + Int_t j; + Int_t k; + list cells; + list cells2; + list::const_iterator p; + list::const_iterator p2; + Float_t rawE; + Float_t ourE; + Float_t allE; + ecalCell* tcell; - for(i=0;iAt(i); - // Clusters with single maximum. Separate code for speedup - if (cls->Maxs()==1) - { - ReconstructXY(fStr->GetHitCell(cls->PeakNum(0)), x, y); - reco=new ((*fReconstucted)[fN++]) ecalReconstructed(cls->Energy(), cls->PreCalibrated(), x, y, cls->PeakNum(0), i); - cls->SetStatus(1); - continue; - } - TryReconstruct(cls, i); -/* - //Multimaximum case - n=cls->Maxs(); - for(j=0;jGetHitCell(cls->PeakNum(j)); - e3[j]=maxs[j]->GetEnergy(); - lists[j].clear(); - maxs[j]->GetNeighborsList(cells); - for(p=cells.begin();p!=cells.end();++p) - { - e3[j]+=(*p)->GetEnergy(); - for(k=0;kGetHitCell(cls->PeakNum(k)); - tcell->GetNeighborsList(cells2); - // Have an intersection between 3x3 areas near maximum - if (find(cells2.begin(), cells2.end(), *p)!=cells2.end()) break; - } - if (j!=0&&k!=j-1) break; + for (i = 0; i < nc; i++) { + cls = (ecalCluster*)fClusters->At(i); + // Clusters with single maximum. Separate code for speedup + if (cls->Maxs() == 1) { + ReconstructXY(fStr->GetHitCell(cls->PeakNum(0)), x, y); + reco = new ((*fReconstucted)[fN++]) + ecalReconstructed(cls->Energy(), cls->PreCalibrated(), x, y, cls->PeakNum(0), i); + cls->SetStatus(1); + continue; + } + TryReconstruct(cls, i); + /* + //Multimaximum case + n=cls->Maxs(); + for(j=0;jGetHitCell(cls->PeakNum(j)); + e3[j]=maxs[j]->GetEnergy(); + lists[j].clear(); + maxs[j]->GetNeighborsList(cells); + for(p=cells.begin();p!=cells.end();++p) + { + e3[j]+=(*p)->GetEnergy(); + for(k=0;kGetHitCell(cls->PeakNum(k)); + tcell->GetNeighborsList(cells2); + // Have an intersection between 3x3 areas near maximum + if (find(cells2.begin(), cells2.end(), *p)!=cells2.end()) break; + } + if (j!=0&&k!=j-1) break; - //form 5x5-3x3 - (*p)->GetNeighborsList(cells2); - for(p2=cells2.begin();p2!=cells2.end();++p2) - { - if (*p2==maxs[j]) - continue; //exclude maximum - if (find(cells.begin(), cells.end(), *p2)!=cells.end()) - continue; //exclude 3x3 area - if (find(lists[j].begin(), lists[j].end(), *p2)==lists[j].end()) - lists[j].push_back(*p2); - } - } - if (p!=cells.end()) break; - } - if (j!=n) - { - cls->SetStatus(-1); - fRejected++; fRejectedP+=cls->Maxs(); - if (fVerbose>9) - Info("Exec", "Cluster %d with %d maximums rejected", i, n); - continue; + //form 5x5-3x3 + (*p)->GetNeighborsList(cells2); + for(p2=cells2.begin();p2!=cells2.end();++p2) + { + if (*p2==maxs[j]) + continue; //exclude maximum + if (find(cells.begin(), cells.end(), *p2)!=cells.end()) + continue; //exclude 3x3 area + if (find(lists[j].begin(), lists[j].end(), *p2)==lists[j].end()) + lists[j].push_back(*p2); + } + } + if (p!=cells.end()) break; + } + if (j!=n) + { + cls->SetStatus(-1); + fRejected++; fRejectedP+=cls->Maxs(); + if (fVerbose>9) + Info("Exec", "Cluster %d with %d maximums rejected", i, n); + continue; + } + //Second pass. Reconstruction + for(j=0;jGet5x5Cluster(cells2); + if (find(cells2.begin(), cells2.end(), *p)!=cells2.end()) allE+=e3[k]; + } + rawE+=(*p)->GetEnergy()*ourE/allE; + } + reco=new ((*fReconstucted)[fN++]) ecalReconstructed(rawE, fCalib->Calibrate(maxs[j]->GetType(), rawE), x, + y, cls->PeakNum(j), i); + } + cls->SetStatus(1); + */ } - //Second pass. Reconstruction - for(j=0;jGet5x5Cluster(cells2); - if (find(cells2.begin(), cells2.end(), *p)!=cells2.end()) allE+=e3[k]; - } - rawE+=(*p)->GetEnergy()*ourE/allE; - } - reco=new ((*fReconstucted)[fN++]) ecalReconstructed(rawE, fCalib->Calibrate(maxs[j]->GetType(), rawE), x, y, cls->PeakNum(j), i); - } - cls->SetStatus(1); -*/ - } - if (fVerbose>0) Info("Exec", "Event %d. Good %d. Bad %d cls, %d maxs.", fEv, fN, fRejected, fRejectedP); + if (fVerbose > 0) + Info("Exec", "Event %d. Good %d. Bad %d cls, %d maxs.", fEv, fN, fRejected, fRejectedP); } void ecalReco::TryReconstruct(ecalCluster* cls, Int_t clsnum) { - Int_t n=cls->Maxs(); - Int_t i; - Int_t k; - ecalCell* maxs[40]; //maximums of the cluster - Float_t e3[40]; //energy in 3x3 area near the maximum - list lists[40]; //lists of 5x5-3x3 areas near maximum - Int_t isgood[40]; //good maximum (no intersection of 3x3 areas) - Int_t rejected=0; - list cells; - list cells2; - list::const_iterator p; - list::const_iterator p2; - ecalReconstructed* reco; - Float_t rawE; - Float_t ourE; - Float_t allE; - ecalCell* tcell; - Float_t x; - Float_t y; + Int_t n = cls->Maxs(); + Int_t i; + Int_t k; + ecalCell* maxs[40]; // maximums of the cluster + Float_t e3[40]; // energy in 3x3 area near the maximum + list lists[40]; // lists of 5x5-3x3 areas near maximum + Int_t isgood[40]; // good maximum (no intersection of 3x3 areas) + Int_t rejected = 0; + list cells; + list cells2; + list::const_iterator p; + list::const_iterator p2; + ecalReconstructed* reco; + Float_t rawE; + Float_t ourE; + Float_t allE; + ecalCell* tcell; + Float_t x; + Float_t y; - for(i=0;iGetHitCell(cls->PeakNum(i)); - e3[i]=maxs[i]->GetEnergy(); - lists[i].clear(); - isgood[i]=1; - maxs[i]->GetNeighborsList(cells); - for(p=cells.begin();p!=cells.end();++p) - { - e3[i]+=(*p)->GetEnergy(); - for(k=0;kGetHitCell(cls->PeakNum(k)); - tcell->GetNeighborsList(cells2); - // Have an intersection between 3x3 areas near maximum - if (find(cells2.begin(), cells2.end(), *p)!=cells2.end()) isgood[i]--; - } - //form 5x5-3x3 - (*p)->GetNeighborsList(cells2); - for(p2=cells2.begin();p2!=cells2.end();++p2) - { - if (*p2==maxs[i]) - continue; //exclude maximum - if (find(cells.begin(), cells.end(), *p2)!=cells.end()) - continue; //exclude 3x3 area - if (find(lists[i].begin(), lists[i].end(), *p2)==lists[i].end()) - lists[i].push_back(*p2); - } + for (i = 0; i < n; i++) { + maxs[i] = fStr->GetHitCell(cls->PeakNum(i)); + e3[i] = maxs[i]->GetEnergy(); + lists[i].clear(); + isgood[i] = 1; + maxs[i]->GetNeighborsList(cells); + for (p = cells.begin(); p != cells.end(); ++p) { + e3[i] += (*p)->GetEnergy(); + for (k = 0; k < i - 1; k++) { + tcell = fStr->GetHitCell(cls->PeakNum(k)); + tcell->GetNeighborsList(cells2); + // Have an intersection between 3x3 areas near maximum + if (find(cells2.begin(), cells2.end(), *p) != cells2.end()) + isgood[i]--; + } + // form 5x5-3x3 + (*p)->GetNeighborsList(cells2); + for (p2 = cells2.begin(); p2 != cells2.end(); ++p2) { + if (*p2 == maxs[i]) + continue; // exclude maximum + if (find(cells.begin(), cells.end(), *p2) != cells.end()) + continue; // exclude 3x3 area + if (find(lists[i].begin(), lists[i].end(), *p2) == lists[i].end()) + lists[i].push_back(*p2); + } + } + if (p != cells.end()) + break; } - if (p!=cells.end()) break; - } - //Second pass. Reconstruction - for(i=0;iGet5x5Cluster(cells2); + if (find(cells2.begin(), cells2.end(), *p) != cells2.end()) + allE += e3[k]; + } + rawE += (*p)->GetEnergy() * ourE / allE; + } + reco = new ((*fReconstucted)[fN++]) + ecalReconstructed(rawE, fCalib->Calibrate(maxs[i]->GetType(), rawE), x, y, cls->PeakNum(i), clsnum); } - ReconstructXY(maxs[i], x, y); - rawE=ourE=e3[i]; - for(p=lists[i].begin();p!=lists[i].end();++p) - { - allE=ourE; - for(k=0;kGet5x5Cluster(cells2); - if (find(cells2.begin(), cells2.end(), *p)!=cells2.end()) allE+=e3[k]; - } - rawE+=(*p)->GetEnergy()*ourE/allE; + cls->SetStatus(1); + if (rejected > 0) { + cls->SetStatus(-rejected); + fRejected++; } - reco=new ((*fReconstucted)[fN++]) ecalReconstructed(rawE, fCalib->Calibrate(maxs[i]->GetType(), rawE), x, y, cls->PeakNum(i), clsnum); - } - cls->SetStatus(1); - if (rejected>0) - { - cls->SetStatus(-rejected); - fRejected++; - } } void ecalReco::ReconstructXY(ecalCell* max, Float_t& x, Float_t& y) { - // Now use just center of gravity - Float_t e=max->GetEnergy(); - list cls; - list::const_iterator p; + // Now use just center of gravity + Float_t e = max->GetEnergy(); + list cls; + list::const_iterator p; - x=max->GetCenterX()*max->GetEnergy(); - y=max->GetCenterY()*max->GetEnergy(); - max->GetNeighborsList(cls); - for(p=cls.begin();p!=cls.end();++p) - { - x+=(*p)->GetCenterX()*(*p)->GetEnergy(); - y+=(*p)->GetCenterY()*(*p)->GetEnergy(); - e+=(*p)->GetEnergy(); - } - x/=e; y/=e; -// cout << x << ", " << y << " : " << max->GetCenterX() << ", " << max->GetCenterY() << endl; + x = max->GetCenterX() * max->GetEnergy(); + y = max->GetCenterY() * max->GetEnergy(); + max->GetNeighborsList(cls); + for (p = cls.begin(); p != cls.end(); ++p) { + x += (*p)->GetCenterX() * (*p)->GetEnergy(); + y += (*p)->GetCenterY() * (*p)->GetEnergy(); + e += (*p)->GetEnergy(); + } + x /= e; + y /= e; + // cout << x << ", " << y << " : " << max->GetCenterX() << ", " << max->GetCenterY() << endl; } /** Standard constructor **/ ecalReco::ecalReco(const char* name, const Int_t verbose) - : FairTask(name, verbose), fEv(0), fN(0), fRejected(0), fRejectedP(0), - fClusters(NULL), fReconstucted(NULL), fStr(NULL), fCalib(NULL) + : FairTask(name, verbose) + , fEv(0) + , fN(0) + , fRejected(0) + , fRejectedP(0) + , fClusters(NULL) + , fReconstucted(NULL) + , fStr(NULL) + , fCalib(NULL) { - ; + ; } /** Only to comply with frame work. **/ ecalReco::ecalReco() - : FairTask(), fEv(-1111), fN(0), fRejected(0), fRejectedP(0), - fClusters(NULL), fReconstucted(NULL), fStr(NULL), fCalib(NULL) + : FairTask() + , fEv(-1111) + , fN(0) + , fRejected(0) + , fRejectedP(0) + , fClusters(NULL) + , fReconstucted(NULL) + , fStr(NULL) + , fCalib(NULL) { - ; + ; } /** Finish a task **/ void ecalReco::Finish() { - ; + ; } /** Destructor **/ ecalReco::~ecalReco() { - if (fReconstucted) - { - fReconstucted->Delete(); - delete fReconstucted; - } + if (fReconstucted) { + fReconstucted->Delete(); + delete fReconstucted; + } } InitStatus ecalReco::Init() { - FairRootManager* io=FairRootManager::Instance(); - if (!io) - { - Fatal("Init", "Can't find IOManager."); - return kFATAL; - } - fStr=(ecalStructure*)io->GetObject("EcalStructure"); - if (!fStr) - { - Fatal("Init()", "Can't find calorimeter structure in the system."); - return kFATAL; - } - fCalib=(ecalClusterCalibration*)io->GetObject("ecalClusterCalibration"); - if (!fCalib) - { - Fatal("Init", "Can't find ecalClusterCalibration in the system."); - return kFATAL; - } - fClusters=(TClonesArray*)io->GetObject("EcalClusters"); - if (!fClusters) - { - Fatal("Init()", "Can't find calorimeter clusters in the system."); - return kFATAL; - } + FairRootManager* io = FairRootManager::Instance(); + if (!io) { + Fatal("Init", "Can't find IOManager."); + return kFATAL; + } + fStr = (ecalStructure*)io->GetObject("EcalStructure"); + if (!fStr) { + Fatal("Init()", "Can't find calorimeter structure in the system."); + return kFATAL; + } + fCalib = (ecalClusterCalibration*)io->GetObject("ecalClusterCalibration"); + if (!fCalib) { + Fatal("Init", "Can't find ecalClusterCalibration in the system."); + return kFATAL; + } + fClusters = (TClonesArray*)io->GetObject("EcalClusters"); + if (!fClusters) { + Fatal("Init()", "Can't find calorimeter clusters in the system."); + return kFATAL; + } - fReconstucted=new TClonesArray("ecalReconstructed", 2000); - io->Register("EcalReco", "ECAL", fReconstucted, kTRUE); + fReconstucted = new TClonesArray("ecalReconstructed", 2000); + io->Register("EcalReco", "ECAL", fReconstucted, kTRUE); - fEv=0; - return kSUCCESS; + fEv = 0; + return kSUCCESS; } TClonesArray* ecalReco::InitPython(TClonesArray* clusters, ecalStructure* str, ecalClusterCalibration* calib) { - fStr=str; - fCalib=calib; - fClusters=clusters; - fReconstucted=new TClonesArray("ecalReconstructed", 2000); + fStr = str; + fCalib = calib; + fClusters = clusters; + fReconstucted = new TClonesArray("ecalReconstructed", 2000); - fEv=0; - return fReconstucted; + fEv = 0; + return fReconstucted; } diff --git a/ecal/ecalReco.h b/ecal/ecalReco.h index 4b0d9d7f23..a04304f955 100644 --- a/ecal/ecalReco.h +++ b/ecal/ecalReco.h @@ -15,43 +15,44 @@ class ecalCluster; class ecalReco : public FairTask { -public: - /** Standard constructor **/ - ecalReco(const char* name, const Int_t verbose); - /** Only to comply with frame work. **/ - ecalReco(); - - /** Finish a task **/ - virtual void Finish(); - /** Exec a task **/ - virtual void Exec(Option_t* option); - /** Initialization **/ - virtual InitStatus Init(); - TClonesArray* InitPython(TClonesArray* clusters, ecalStructure* str, ecalClusterCalibration* calib); - /** Destructor **/ - ~ecalReco(); -private: - void ReconstructXY(ecalCell* max, Float_t& x, Float_t& y); - void TryReconstruct(ecalCluster* cls, Int_t clsnum); - /** Current event **/ - Int_t fEv; - /** Current reconstructed particle **/ - Int_t fN; - /** Number of rejected clusters **/ - Int_t fRejected; - /** Number of maximums in rejected clusters **/ - Int_t fRejectedP; - - /** An array of clusters **/ - TClonesArray* fClusters; //! - /** Array of reconstructed objects **/ - TClonesArray* fReconstucted; //! - /** A calorimeter structure **/ - ecalStructure* fStr; //! - /** Cluster calibration object for photons **/ - ecalClusterCalibration* fCalib; //! - - ClassDef(ecalReco, 1) + public: + /** Standard constructor **/ + ecalReco(const char* name, const Int_t verbose); + /** Only to comply with frame work. **/ + ecalReco(); + + /** Finish a task **/ + virtual void Finish(); + /** Exec a task **/ + virtual void Exec(Option_t* option); + /** Initialization **/ + virtual InitStatus Init(); + TClonesArray* InitPython(TClonesArray* clusters, ecalStructure* str, ecalClusterCalibration* calib); + /** Destructor **/ + ~ecalReco(); + + private: + void ReconstructXY(ecalCell* max, Float_t& x, Float_t& y); + void TryReconstruct(ecalCluster* cls, Int_t clsnum); + /** Current event **/ + Int_t fEv; + /** Current reconstructed particle **/ + Int_t fN; + /** Number of rejected clusters **/ + Int_t fRejected; + /** Number of maximums in rejected clusters **/ + Int_t fRejectedP; + + /** An array of clusters **/ + TClonesArray* fClusters; //! + /** Array of reconstructed objects **/ + TClonesArray* fReconstucted; //! + /** A calorimeter structure **/ + ecalStructure* fStr; //! + /** Cluster calibration object for photons **/ + ecalClusterCalibration* fCalib; //! + + ClassDef(ecalReco, 1) }; #endif diff --git a/ecal/ecalReconstructed.h b/ecal/ecalReconstructed.h index cd2f99c324..660679d29b 100644 --- a/ecal/ecalReconstructed.h +++ b/ecal/ecalReconstructed.h @@ -5,42 +5,56 @@ class ecalReconstructed : public TObject { -friend class ecalReco; -public: - /** For framework compatibility **/ - ecalReconstructed() : TObject() {}; - /** Standard constructor**/ - ecalReconstructed(Float_t rawE, Float_t recoE, Float_t x, Float_t y, Int_t cellnum, Int_t clusternum, Int_t mc=-1111) - : TObject(), fRawE(rawE), fRecoE(recoE), fX(x), fY(y), fCellNum(cellnum), fClusterNum(clusternum), fMCTrack(mc) - {}; - ~ecalReconstructed() {}; + friend class ecalReco; - /** Getters/setters **/ - inline Float_t RawE() const {return fRawE;} - inline Float_t RecoE() const {return fRecoE;} - inline Float_t X() const {return fX;} - inline Float_t Y() const {return fY;} - inline Int_t CellNum() const {return fCellNum;} - inline Int_t ClusterNum() const {return fClusterNum;} - inline Int_t MCTrack() const {return fMCTrack;} - inline void SetMCTrack(Int_t mctrack) {fMCTrack=mctrack;} + public: + /** For framework compatibility **/ + ecalReconstructed() + : TObject() {}; + /** Standard constructor**/ + ecalReconstructed(Float_t rawE, + Float_t recoE, + Float_t x, + Float_t y, + Int_t cellnum, + Int_t clusternum, + Int_t mc = -1111) + : TObject() + , fRawE(rawE) + , fRecoE(recoE) + , fX(x) + , fY(y) + , fCellNum(cellnum) + , fClusterNum(clusternum) + , fMCTrack(mc) {}; + ~ecalReconstructed() {}; -private: - /** Uncalibrated energy **/ - Float_t fRawE; - /** Reconstructed energy **/ - Float_t fRecoE; - /** Coordinates of impact point **/ - Float_t fX; - Float_t fY; - /** Serial number of maximum **/ - Int_t fCellNum; - /** Serial number of cluster **/ - Int_t fClusterNum; - /** Serial number of MC track (if any) **/ - Int_t fMCTrack; + /** Getters/setters **/ + inline Float_t RawE() const { return fRawE; } + inline Float_t RecoE() const { return fRecoE; } + inline Float_t X() const { return fX; } + inline Float_t Y() const { return fY; } + inline Int_t CellNum() const { return fCellNum; } + inline Int_t ClusterNum() const { return fClusterNum; } + inline Int_t MCTrack() const { return fMCTrack; } + inline void SetMCTrack(Int_t mctrack) { fMCTrack = mctrack; } - ClassDef(ecalReconstructed, 1) + private: + /** Uncalibrated energy **/ + Float_t fRawE; + /** Reconstructed energy **/ + Float_t fRecoE; + /** Coordinates of impact point **/ + Float_t fX; + Float_t fY; + /** Serial number of maximum **/ + Int_t fCellNum; + /** Serial number of cluster **/ + Int_t fClusterNum; + /** Serial number of MC track (if any) **/ + Int_t fMCTrack; + + ClassDef(ecalReconstructed, 1) }; #endif diff --git a/ecal/ecalStructure.cxx b/ecal/ecalStructure.cxx index 5dc2de3fee..a20c1a9336 100644 --- a/ecal/ecalStructure.cxx +++ b/ecal/ecalStructure.cxx @@ -7,373 +7,367 @@ #include "ecalStructure.h" #include "ecal.h" -#include "ecalCellMC.h" - #include "ecalCell.h" +#include "ecalCellMC.h" -#include #include #include +#include using namespace std; - ecalCell* ecalStructure::GetCell(Int_t volId, Int_t& ten) { - UInt_t i; - static Int_t volidmax = 0; - volidmax=10000000; - - if ((Int_t)fHash.size()volidmax) - return NULL; - if (fHash[volId]==NULL) - { - Bool_t lisPS; - Int_t iten; - Float_t x; - Float_t y; - fHash[volId]=new __ecalCellWrapper(); - lisPS=ecal::GetCellCoordInf(volId, x, y, iten); - fHash[volId]->cell=GetCell(x+0.025,y+0.025); - fHash[volId]->isPsTen=iten*2; - if (lisPS) fHash[volId]->isPsTen+=1; - } - ten=fHash[volId]->isPsTen/2; - return fHash[volId]->cell; + UInt_t i; + static Int_t volidmax = 0; + volidmax = 10000000; + + if ((Int_t)fHash.size() < volidmax) { + fHash.resize(volidmax); + for (i = 0; i < fHash.size(); i++) + fHash[i] = NULL; + } + if (volId > volidmax) + return NULL; + if (fHash[volId] == NULL) { + Bool_t lisPS; + Int_t iten; + Float_t x; + Float_t y; + fHash[volId] = new __ecalCellWrapper(); + lisPS = ecal::GetCellCoordInf(volId, x, y, iten); + fHash[volId]->cell = GetCell(x + 0.025, y + 0.025); + fHash[volId]->isPsTen = iten * 2; + if (lisPS) + fHash[volId]->isPsTen += 1; + } + ten = fHash[volId]->isPsTen / 2; + return fHash[volId]->cell; } //----------------------------------------------------------------------------- void ecalStructure::Serialize() { - fCells.clear(); - for(UInt_t i=0;i cells=fStructure[i]->GetCells(); - copy(cells.begin(),cells.end(), back_inserter(fCells)); - } + fCells.clear(); + for (UInt_t i = 0; i < fStructure.size(); i++) + if (fStructure[i]) { + vector cells = fStructure[i]->GetCells(); + copy(cells.begin(), cells.end(), back_inserter(fCells)); + } } //----------------------------------------------------------------------------- ecalModule* ecalStructure::CreateModule(char type, Int_t number, Float_t x1, Float_t y1, Float_t x2, Float_t y2) { - return new ecalModule(type, number, x1, y1, x2, y2, fUseMC); + return new ecalModule(type, number, x1, y1, x2, y2, fUseMC); } //----------------------------------------------------------------------------- ecalStructure::ecalStructure(ecalInf* ecalinf) - : TNamed("ecalStructure", "Calorimeter structure"), - fUseMC(0), - fX1(0.), - fY1(0.), - fEcalInf(ecalinf), - fStructure(), - fCells(), - fHash() + : TNamed("ecalStructure", "Calorimeter structure") + , fUseMC(0) + , fX1(0.) + , fY1(0.) + , fEcalInf(ecalinf) + , fStructure() + , fCells() + , fHash() { - fX1=fEcalInf->GetXPos()-\ - fEcalInf->GetModuleSize()*fEcalInf->GetXSize()/2.0; - fY1=fEcalInf->GetYPos()-\ - fEcalInf->GetModuleSize()*fEcalInf->GetYSize()/2.0; + fX1 = fEcalInf->GetXPos() - fEcalInf->GetModuleSize() * fEcalInf->GetXSize() / 2.0; + fY1 = fEcalInf->GetYPos() - fEcalInf->GetModuleSize() * fEcalInf->GetYSize() / 2.0; } //----------------------------------------------------------------------------- void ecalStructure::Construct() { - if (!fEcalInf) return; - - Float_t x1=GetX1(); - Float_t y1=GetY1(); - Float_t x; - Float_t y; - Float_t dx; - Float_t dy; - Int_t i; - Int_t j; - Int_t k; - Int_t number; - char type; - - fStructure.resize(fEcalInf->GetXSize()*fEcalInf->GetYSize(), NULL); - - dx=fEcalInf->GetModuleSize(); - dy=fEcalInf->GetModuleSize(); - //Creating ECAL Matrix - for(i=0;iGetXSize();i++) - for(j=0;jGetYSize();j++) { - type=fEcalInf->GetType(i,j); - if (type) { - x=x1+i*dx; - y=y1+j*dy; - number=(i*100+j)*100; - fStructure[GetNum(i,j)]=CreateModule(type,number,x,y,x+dx,y+dy); - } - else - fStructure[GetNum(i,j)]=NULL; - } + if (!fEcalInf) + return; + + Float_t x1 = GetX1(); + Float_t y1 = GetY1(); + Float_t x; + Float_t y; + Float_t dx; + Float_t dy; + Int_t i; + Int_t j; + Int_t k; + Int_t number; + char type; + + fStructure.resize(fEcalInf->GetXSize() * fEcalInf->GetYSize(), NULL); + + dx = fEcalInf->GetModuleSize(); + dy = fEcalInf->GetModuleSize(); + // Creating ECAL Matrix + for (i = 0; i < fEcalInf->GetXSize(); i++) + for (j = 0; j < fEcalInf->GetYSize(); j++) { + type = fEcalInf->GetType(i, j); + if (type) { + x = x1 + i * dx; + y = y1 + j * dy; + number = (i * 100 + j) * 100; + fStructure[GetNum(i, j)] = CreateModule(type, number, x, y, x + dx, y + dy); + } else + fStructure[GetNum(i, j)] = NULL; + } #ifdef _DECALSTRUCT - cerr << "-I- ecalStructure::Construct(): calorimeter matrix created." << endl; + cerr << "-I- ecalStructure::Construct(): calorimeter matrix created." << endl; #endif - //Now ECAL matrix created - list neib; - vector cl; - vector::const_iterator pcl; - - Int_t num; - //We want neighbors for ecalModules be ecalModules - for(i=0;iGetXSize();i++) - for(j=0;jGetYSize();j++) - if (fStructure[GetNum(i,j)]) { - neib.clear(); - - num=GetNumber(i-1,j); - if (-1!=num) { - neib.push_back(fStructure[num]); - } - - num=GetNumber(i-1,j+1); - if (-1!=num) { - neib.push_back(fStructure[num]); - } - - num=GetNumber(i,j+1); - if (-1!=num) { - neib.push_back(fStructure[num]); - } - - num=GetNumber(i+1,j+1); - if (-1!=num) { - neib.push_back(fStructure[num]); - } - - num=GetNumber(i+1,j); - if (-1!=num) { - neib.push_back(fStructure[num]); - } - - num=GetNumber(i+1,j-1); - if (-1!=num) { - neib.push_back(fStructure[num]); - } - - num=GetNumber(i,j-1); - if (-1!=num) { - neib.push_back(fStructure[num]); - } - - num=GetNumber(i-1,j-1); - if (-1!=num) { - neib.push_back(fStructure[num]); - } - - num=GetNumber(i,j); - fStructure[num]->SetNeighborsList(neib); - cl=fStructure[num]->GetCells(); - for(pcl=cl.begin();pcl!=cl.end();++pcl) - CreateNLists(*pcl); - } - Serialize(); + // Now ECAL matrix created + list neib; + vector cl; + vector::const_iterator pcl; + + Int_t num; + // We want neighbors for ecalModules be ecalModules + for (i = 0; i < fEcalInf->GetXSize(); i++) + for (j = 0; j < fEcalInf->GetYSize(); j++) + if (fStructure[GetNum(i, j)]) { + neib.clear(); + + num = GetNumber(i - 1, j); + if (-1 != num) { + neib.push_back(fStructure[num]); + } + + num = GetNumber(i - 1, j + 1); + if (-1 != num) { + neib.push_back(fStructure[num]); + } + + num = GetNumber(i, j + 1); + if (-1 != num) { + neib.push_back(fStructure[num]); + } + + num = GetNumber(i + 1, j + 1); + if (-1 != num) { + neib.push_back(fStructure[num]); + } + + num = GetNumber(i + 1, j); + if (-1 != num) { + neib.push_back(fStructure[num]); + } + + num = GetNumber(i + 1, j - 1); + if (-1 != num) { + neib.push_back(fStructure[num]); + } + + num = GetNumber(i, j - 1); + if (-1 != num) { + neib.push_back(fStructure[num]); + } + + num = GetNumber(i - 1, j - 1); + if (-1 != num) { + neib.push_back(fStructure[num]); + } + + num = GetNumber(i, j); + fStructure[num]->SetNeighborsList(neib); + cl = fStructure[num]->GetCells(); + for (pcl = cl.begin(); pcl != cl.end(); ++pcl) + CreateNLists(*pcl); + } + Serialize(); } //----------------------------------------------------------------------------- void _add_not_null(ecalModule* mod, list& lst) { - if (mod) - if (find(lst.begin(),lst.end(),mod)==lst.end()) - lst.push_back(mod); + if (mod) + if (find(lst.begin(), lst.end(), mod) == lst.end()) + lst.push_back(mod); } //----------------------------------------------------------------------------- void _add_not_null(list from, list& where) { - list::const_iterator p; - for(p=from.begin();p!=from.end();++p) - if (find(where.begin(),where.end(),(*p))==where.end()) - //this p uniq! - where.push_back(*p); + list::const_iterator p; + for (p = from.begin(); p != from.end(); ++p) + if (find(where.begin(), where.end(), (*p)) == where.end()) + // this p uniq! + where.push_back(*p); } //----------------------------------------------------------------------------- void _add_not_null(ecalCell* cell, list& lst) { - if (find(lst.begin(),lst.end(),cell)==lst.end()) - lst.push_back(cell); + if (find(lst.begin(), lst.end(), cell) == lst.end()) + lst.push_back(cell); } //----------------------------------------------------------------------------- void ecalStructure::CreateNLists(ecalCell* cell) { - Float_t x=cell->GetCenterX(); - Float_t y=cell->GetCenterY(); - Float_t dx=(cell->GetX2()-cell->GetX1())/2.0; - Float_t dy=(cell->GetX2()-cell->GetX1())/2.0; - Float_t x1; - Float_t x2; - Float_t y1; - Float_t y2; - Float_t mx1=cell->GetX1(); - Float_t mx2=cell->GetX2(); - Float_t my1=cell->GetY1(); - Float_t my2=cell->GetY2(); - Float_t cx; - Float_t cy; - Float_t d=0.1; - Float_t dd=1e-6; - list neib; - list tl; - list tml; - list::const_iterator ptml; - list::const_iterator ptl; - Int_t i; - - neib.clear(); - - tml.clear(); - _add_not_null(GetModule(x-2*dx,y-2*dy),tml); - _add_not_null(GetModule(x-2*dx,y ),tml); - _add_not_null(GetModule(x-2*dx,y+2*dy),tml); - _add_not_null(GetModule(x ,y-2*dy),tml); - _add_not_null(GetModule(x ,y ),tml); - _add_not_null(GetModule(x ,y+2*dy),tml); - _add_not_null(GetModule(x+2*dx,y-2*dy),tml); - _add_not_null(GetModule(x+2*dx,y ),tml); - _add_not_null(GetModule(x+2*dx,y+2*dy),tml); - if (tml.empty()) { - cerr << "Error during creating neighbors lists." << endl; - cerr << "Can't' find any modules neighbors to cell." << endl; - cerr << "Cell: CenterX=" << x << ", CenterY=" << y << "." << endl; - return; - } - for(ptml=tml.begin();ptml!=tml.end();++ptml) { - _add_not_null((*ptml)->GetCellsY(y-dy-d),tl); - _add_not_null((*ptml)->GetCellsY(y+dy+d),tl); - _add_not_null((*ptml)->GetCellsX(x-dx-d),tl); - _add_not_null((*ptml)->GetCellsX(x+dx+d),tl); - } - if (tl.empty()) { - cerr << "Error during creating neighbors lists." << endl; - cerr << "Can't' find any cells neighbors to cell." << endl; - cerr << "Cell: CenterX=" << x << ", CenterY=" << y << "." << endl; - return; - } - for(ptl=tl.begin();ptl!=tl.end();++ptl) { - x1=(*ptl)->GetX1(); - x2=(*ptl)->GetX2(); - y1=(*ptl)->GetY1(); - y2=(*ptl)->GetY2(); - cx=(*ptl)->GetCenterX(); - cy=(*ptl)->GetCenterY(); - if (fabs(mx1-x2)-dd&&cy-y-dy/2-dd)||fabs(y+dy-y1)GetCenterX(); + Float_t y = cell->GetCenterY(); + Float_t dx = (cell->GetX2() - cell->GetX1()) / 2.0; + Float_t dy = (cell->GetX2() - cell->GetX1()) / 2.0; + Float_t x1; + Float_t x2; + Float_t y1; + Float_t y2; + Float_t mx1 = cell->GetX1(); + Float_t mx2 = cell->GetX2(); + Float_t my1 = cell->GetY1(); + Float_t my2 = cell->GetY2(); + Float_t cx; + Float_t cy; + Float_t d = 0.1; + Float_t dd = 1e-6; + list neib; + list tl; + list tml; + list::const_iterator ptml; + list::const_iterator ptl; + Int_t i; + + neib.clear(); + + tml.clear(); + _add_not_null(GetModule(x - 2 * dx, y - 2 * dy), tml); + _add_not_null(GetModule(x - 2 * dx, y), tml); + _add_not_null(GetModule(x - 2 * dx, y + 2 * dy), tml); + _add_not_null(GetModule(x, y - 2 * dy), tml); + _add_not_null(GetModule(x, y), tml); + _add_not_null(GetModule(x, y + 2 * dy), tml); + _add_not_null(GetModule(x + 2 * dx, y - 2 * dy), tml); + _add_not_null(GetModule(x + 2 * dx, y), tml); + _add_not_null(GetModule(x + 2 * dx, y + 2 * dy), tml); + if (tml.empty()) { + cerr << "Error during creating neighbors lists." << endl; + cerr << "Can't' find any modules neighbors to cell." << endl; + cerr << "Cell: CenterX=" << x << ", CenterY=" << y << "." << endl; + return; } - if (fabs(my1-y2)-dd&&cx-x-dx/2-dd)||fabs(x+dx-x1)GetCellsY(y - dy - d), tl); + _add_not_null((*ptml)->GetCellsY(y + dy + d), tl); + _add_not_null((*ptml)->GetCellsX(x - dx - d), tl); + _add_not_null((*ptml)->GetCellsX(x + dx + d), tl); } - if (fabs(mx2-x1)-dd&&cy-y-dy/2-dd)||fabs(y+dy-y1)-dd&&cx-x-dx/2-dd)||fabs(x+dx-x1)GetX1(); + x2 = (*ptl)->GetX2(); + y1 = (*ptl)->GetY1(); + y2 = (*ptl)->GetY2(); + cx = (*ptl)->GetCenterX(); + cy = (*ptl)->GetCenterY(); + if (fabs(mx1 - x2) < dd) { + if ((cy - y + 2 * dy > -dd && cy - y - dy / 2 < dd) || fabs(y - dy - y1) < dd || fabs(y - dy - y2) < dd) { + _add_not_null((*ptl), neib); + } + if ((cy - y - 2 * dy < dd && cy - y + dy / 2 > -dd) || fabs(y + dy - y1) < dd || fabs(y + dy - y2) < dd) { + _add_not_null((*ptl), neib); + } + } + if (fabs(my1 - y2) < dd) { + if ((cx - x + 2 * dx > -dd && cx - x - dx / 2 < dd) || fabs(x - dx - x1) < dd || fabs(x - dx - x2) < dd) { + _add_not_null((*ptl), neib); + } + if ((cx - x - 2 * dx < dd && cx - x + dx / 2 > -dd) || fabs(x + dx - x1) < dd || fabs(x + dx - x2) < dd) { + _add_not_null((*ptl), neib); + } + } + if (fabs(mx2 - x1) < dd) { + if ((cy - y + 2 * dy > -dd && cy - y - dy / 2 < dd) || fabs(y - dy - y1) < dd || fabs(y - dy - y2) < dd) { + _add_not_null((*ptl), neib); + } + if ((cy - y - 2 * dy < dd && cy - y + dy / 2 > -dd) || fabs(y + dy - y1) < dd || fabs(y + dy - y2) < dd) { + _add_not_null((*ptl), neib); + } + } + if (fabs(my2 - y1) < dd) { + if ((cx - x + 2 * dx > -dd && cx - x - dx / 2 < dd) || fabs(x - dx - x1) < dd || fabs(x - dx - x2) < dd) { + _add_not_null((*ptl), neib); + } + if ((cx - x - 2 * dx < dd && cx - x + dx / 2 > -dd) || fabs(x + dx - x1) < dd || fabs(x + dx - x2) < dd) { + _add_not_null((*ptl), neib); + } + } } - - } - cell->SetNeighborsList(neib); + cell->SetNeighborsList(neib); } //----------------------------------------------------------------------------- void ecalStructure::ResetModules() { - list::const_iterator p=fCells.begin(); - if (fUseMC==0) - { - for(;p!=fCells.end();++p) - (*p)->ResetEnergyFast(); - } - else - { - for(;p!=fCells.end();++p) - ((ecalCellMC*)(*p))->ResetEnergy(); - } + list::const_iterator p = fCells.begin(); + if (fUseMC == 0) { + for (; p != fCells.end(); ++p) + (*p)->ResetEnergyFast(); + } else { + for (; p != fCells.end(); ++p) + ((ecalCellMC*)(*p))->ResetEnergy(); + } } //----------------------------------------------------------------------------- void ecalStructure::GetHitXY(const Int_t hitId, Float_t& x, Float_t& y) const { - /** Hit Id -> (x,y) **/ + /** Hit Id -> (x,y) **/ - // Some translation from x*100+y to y*sizex+x coding... + // Some translation from x*100+y to y*sizex+x coding... - Int_t mnum=hitId/100; - Int_t cellx = mnum/100; - Int_t celly = mnum%100; - mnum = GetNum(cellx, celly); + Int_t mnum = hitId / 100; + Int_t cellx = mnum / 100; + Int_t celly = mnum % 100; + mnum = GetNum(cellx, celly); - // end translation + // end translation - ecalModule* module=fStructure[mnum]; - ecalCell* cell; + ecalModule* module = fStructure[mnum]; + ecalCell* cell; - Int_t cellnum=hitId%100; - // change place - Int_t cx=cellnum%10-1; - Int_t cy=cellnum/10-1; + Int_t cellnum = hitId % 100; + // change place + Int_t cx = cellnum % 10 - 1; + Int_t cy = cellnum / 10 - 1; - if (module==NULL||cx<0||cy<0||cx>=module->GetType()||cy>=module->GetType()) {x=0; y=0; return;} - cell=module->At(cx,cy); - x=cell->GetCenterX(); - y=cell->GetCenterY(); + if (module == NULL || cx < 0 || cy < 0 || cx >= module->GetType() || cy >= module->GetType()) { + x = 0; + y = 0; + return; + } + cell = module->At(cx, cy); + x = cell->GetCenterX(); + y = cell->GetCenterY(); } //----------------------------------------------------------------------------- ecalCell* ecalStructure::GetHitCell(const Int_t hitId) const { - /** Hit Id -> Cell **/ + /** Hit Id -> Cell **/ - // Some translation from x*100+y to y*sizex+x coding... + // Some translation from x*100+y to y*sizex+x coding... - Int_t mnum=hitId/100; - Int_t cellx = mnum/100; - Int_t celly = mnum%100; - mnum = GetNum(cellx, celly); + Int_t mnum = hitId / 100; + Int_t cellx = mnum / 100; + Int_t celly = mnum % 100; + mnum = GetNum(cellx, celly); - // end translation + // end translation - ecalModule* module=fStructure[mnum]; + ecalModule* module = fStructure[mnum]; - Int_t cellnum=hitId%100; - Int_t cx=cellnum%10-1; - Int_t cy=cellnum/10-1; + Int_t cellnum = hitId % 100; + Int_t cx = cellnum % 10 - 1; + Int_t cy = cellnum / 10 - 1; - if (module==NULL||cx<0||cy<0||cx>=module->GetType()||cy>=module->GetType()) - return NULL; -// cout << hitId << " --- " << module->At(cx,cy)->GetCellNumber() << endl; - return module->At(cx,cy); + if (module == NULL || cx < 0 || cy < 0 || cx >= module->GetType() || cy >= module->GetType()) + return NULL; + // cout << hitId << " --- " << module->At(cx,cy)->GetCellNumber() << endl; + return module->At(cx, cy); } //----------------------------------------------------------------------------- @@ -381,28 +375,25 @@ ecalCell* ecalStructure::GetHitCell(const Int_t hitId) const void ecalStructure::GetGlobalCellXY(const Int_t hitId, Int_t& x, Int_t& y) const { + Int_t modulenum = hitId / 100; + Int_t cellx = modulenum / 100; + Int_t celly = modulenum % 100; - Int_t modulenum = hitId/100; - Int_t cellx = modulenum/100; - Int_t celly = modulenum%100; - - Int_t innernum = hitId%100; - Int_t iny = innernum/10; - Int_t inx = innernum%10; - Int_t msize = fEcalInf->GetType(cellx,celly); - - - x = (cellx-1)* msize + inx; - y = (celly-1)* msize + iny; + Int_t innernum = hitId % 100; + Int_t iny = innernum / 10; + Int_t inx = innernum % 10; + Int_t msize = fEcalInf->GetType(cellx, celly); + x = (cellx - 1) * msize + inx; + y = (celly - 1) * msize + iny; } // Int_t ecalStructure::GetType(const Int_t hitId) const { - Int_t modulenum = hitId/100; - Int_t cellx = modulenum/100; - Int_t celly = modulenum%100; + Int_t modulenum = hitId / 100; + Int_t cellx = modulenum / 100; + Int_t celly = modulenum % 100; - Int_t msize = fEcalInf->GetType(cellx,celly); - return msize; + Int_t msize = fEcalInf->GetType(cellx, celly); + return msize; } diff --git a/ecal/ecalStructure.h b/ecal/ecalStructure.h index 31d54e542b..31bb1b46cc 100644 --- a/ecal/ecalStructure.h +++ b/ecal/ecalStructure.h @@ -7,13 +7,11 @@ #ifndef ECALSTRUCTURE_H #define ECALSTRUCTURE_H - -#include "ecalInf.h" -#include "ecalModule.h" -#include "ecalCell.h" - #include "TMath.h" #include "TNamed.h" +#include "ecalCell.h" +#include "ecalInf.h" +#include "ecalModule.h" #include @@ -23,166 +21,165 @@ struct __ecalCellWrapper; class ecalStructure : public TNamed { -public: - ecalStructure(ecalInf* ecalinf); - void SetUseMC(Int_t mc=0) {fUseMC=mc;} - Int_t GetUseMC() const {return fUseMC;} - void Construct(); - Int_t GetNumber(Int_t x, Int_t y) const; - - Bool_t AddEnergy(Float_t x, Float_t y, Float_t energy); - Float_t GetEnergy(Float_t x, Float_t y) const; - ecalCell* GetCell(Float_t x, Float_t y) const; - ecalModule* GetModule(Float_t x, Float_t y) const; - Int_t GetModuleNumber(Float_t x, Float_t y) const; - - Float_t GetX1() const {return fX1;}; - Float_t GetY1() const {return fY1;}; - Float_t GetX2() const; - Float_t GetY2() const; - inline ecalInf* GetEcalInf() const {return fEcalInf;} - inline void GetStructure(std::vector& stru) const {stru=fStructure;} - inline void GetCells(std::list& cells) const {cells=fCells;} - //Create neighbors lists - void CreateNLists(ecalCell* cell); - void ResetModules(); - - ecalModule* CreateModule(char type, Int_t number, Float_t x1, Float_t y1, Float_t x2, Float_t y2); - //Some usefull procedures for hit processing - - //Converts (x,y) to hit Id - Int_t GetHitId(Float_t x, Float_t y) const; - //Hit Id -> (x,y) - void GetHitXY(const Int_t hitId, Float_t& x, Float_t& y) const; - - // HitId -> in global cell coordinate - void GetGlobalCellXY(const Int_t hitId, Int_t& x, Int_t& y) const; - - // HitId -> cell type - Int_t GetType(const Int_t hitId) const; - - ecalCell* GetCell(Int_t fVolId, Int_t& ten); - //Hit It -> Cell - ecalCell* GetHitCell(const Int_t hitId) const; - -private: - Int_t GetNum(Int_t x, Int_t y) const; - -private: - /** Creates fCells lists **/ - void Serialize(); - /** Use store MC information in cells **/ - Int_t fUseMC; - /** X coordibate of left bottom angle of ECAL **/ - Float_t fX1; - /** Y coordibate of left bottom angle of ECAL **/ - Float_t fY1; - /** ECAL geometry container **/ - ecalInf* fEcalInf; - /** total list of ECAL modules **/ - std::vector fStructure; - /** All ECAL cells **/ - std::list fCells; - /** MCPoint id -> ECAL cell**/ - std::vector<__ecalCellWrapper*> fHash; - - ecalStructure(const ecalStructure&); - ecalStructure& operator=(const ecalStructure&); - - ClassDef(ecalStructure,1); + public: + ecalStructure(ecalInf* ecalinf); + void SetUseMC(Int_t mc = 0) { fUseMC = mc; } + Int_t GetUseMC() const { return fUseMC; } + void Construct(); + Int_t GetNumber(Int_t x, Int_t y) const; + + Bool_t AddEnergy(Float_t x, Float_t y, Float_t energy); + Float_t GetEnergy(Float_t x, Float_t y) const; + ecalCell* GetCell(Float_t x, Float_t y) const; + ecalModule* GetModule(Float_t x, Float_t y) const; + Int_t GetModuleNumber(Float_t x, Float_t y) const; + + Float_t GetX1() const { return fX1; }; + Float_t GetY1() const { return fY1; }; + Float_t GetX2() const; + Float_t GetY2() const; + inline ecalInf* GetEcalInf() const { return fEcalInf; } + inline void GetStructure(std::vector& stru) const { stru = fStructure; } + inline void GetCells(std::list& cells) const { cells = fCells; } + // Create neighbors lists + void CreateNLists(ecalCell* cell); + void ResetModules(); + + ecalModule* CreateModule(char type, Int_t number, Float_t x1, Float_t y1, Float_t x2, Float_t y2); + // Some usefull procedures for hit processing + + // Converts (x,y) to hit Id + Int_t GetHitId(Float_t x, Float_t y) const; + // Hit Id -> (x,y) + void GetHitXY(const Int_t hitId, Float_t& x, Float_t& y) const; + + // HitId -> in global cell coordinate + void GetGlobalCellXY(const Int_t hitId, Int_t& x, Int_t& y) const; + + // HitId -> cell type + Int_t GetType(const Int_t hitId) const; + + ecalCell* GetCell(Int_t fVolId, Int_t& ten); + // Hit It -> Cell + ecalCell* GetHitCell(const Int_t hitId) const; + + private: + Int_t GetNum(Int_t x, Int_t y) const; + + private: + /** Creates fCells lists **/ + void Serialize(); + /** Use store MC information in cells **/ + Int_t fUseMC; + /** X coordibate of left bottom angle of ECAL **/ + Float_t fX1; + /** Y coordibate of left bottom angle of ECAL **/ + Float_t fY1; + /** ECAL geometry container **/ + ecalInf* fEcalInf; + /** total list of ECAL modules **/ + std::vector fStructure; + /** All ECAL cells **/ + std::list fCells; + /** MCPoint id -> ECAL cell**/ + std::vector<__ecalCellWrapper*> fHash; + + ecalStructure(const ecalStructure&); + ecalStructure& operator=(const ecalStructure&); + + ClassDef(ecalStructure, 1); }; inline ecalCell* ecalStructure::GetCell(Float_t x, Float_t y) const { - /** get ECAL cell by known cell center coordinate (x,y) **/ - ecalModule* module=GetModule(x,y); - if (module) return module->FindCell(x,y); - return NULL; + /** get ECAL cell by known cell center coordinate (x,y) **/ + ecalModule* module = GetModule(x, y); + if (module) + return module->FindCell(x, y); + return NULL; } inline ecalModule* ecalStructure::GetModule(Float_t x, Float_t y) const { - /** get ECAL module by known module center coordinate (x,y) **/ - Int_t num=GetModuleNumber(x,y); - if (-1==num) return NULL; else return fStructure[num]; + /** get ECAL module by known module center coordinate (x,y) **/ + Int_t num = GetModuleNumber(x, y); + if (-1 == num) + return NULL; + else + return fStructure[num]; } -inline Int_t ecalStructure::GetModuleNumber(Float_t x, Float_t y) const +inline Int_t ecalStructure::GetModuleNumber(Float_t x, Float_t y) const { - /** get ECAL module by known module center coordinate (x,y) **/ - Int_t ix=(Int_t)TMath::Floor((x-GetX1())/fEcalInf->GetModuleSize()); - Int_t iy=(Int_t)TMath::Floor((y-GetY1())/fEcalInf->GetModuleSize()); - return GetNumber(ix,iy); + /** get ECAL module by known module center coordinate (x,y) **/ + Int_t ix = (Int_t)TMath::Floor((x - GetX1()) / fEcalInf->GetModuleSize()); + Int_t iy = (Int_t)TMath::Floor((y - GetY1()) / fEcalInf->GetModuleSize()); + return GetNumber(ix, iy); } inline Int_t ecalStructure::GetNumber(Int_t x, Int_t y) const { - /** get ECAL absolute module number by known module relative number (x,y) - ** with check for the ECAL boundaries **/ - if (x>-1&&y>-1) - if (xGetXSize()&&yGetYSize()) - return GetNum(x,y); - return -1; + /** get ECAL absolute module number by known module relative number (x,y) + ** with check for the ECAL boundaries **/ + if (x > -1 && y > -1) + if (x < fEcalInf->GetXSize() && y < fEcalInf->GetYSize()) + return GetNum(x, y); + return -1; } inline Int_t ecalStructure::GetNum(Int_t x, Int_t y) const { - /** get ECAL absolute module number by known module relative number (x,y) **/ - return y*fEcalInf->GetXSize()+x; + /** get ECAL absolute module number by known module relative number (x,y) **/ + return y * fEcalInf->GetXSize() + x; } inline Float_t ecalStructure::GetX2() const { - /** get ECAL right edge coordinate in cm **/ - return fEcalInf->GetXPos()+ - fEcalInf->GetModuleSize()*fEcalInf->GetXSize()/2.0; + /** get ECAL right edge coordinate in cm **/ + return fEcalInf->GetXPos() + fEcalInf->GetModuleSize() * fEcalInf->GetXSize() / 2.0; } inline Float_t ecalStructure::GetY2() const { - /** get ECAL upper edge coordinate in cm **/ - return fEcalInf->GetYPos()+ - fEcalInf->GetModuleSize()*fEcalInf->GetYSize()/2.0; + /** get ECAL upper edge coordinate in cm **/ + return fEcalInf->GetYPos() + fEcalInf->GetModuleSize() * fEcalInf->GetYSize() / 2.0; } inline Bool_t ecalStructure::AddEnergy(Float_t x, Float_t y, Float_t energy) { - /** Add calorimeter energy to a cell with coordinate (x,y) **/ - ecalCell* cell=GetCell(x,y); - if (cell) - { - cell->AddEnergy(energy); - } - else - return kFALSE; - return kTRUE; + /** Add calorimeter energy to a cell with coordinate (x,y) **/ + ecalCell* cell = GetCell(x, y); + if (cell) { + cell->AddEnergy(energy); + } else + return kFALSE; + return kTRUE; } inline Float_t ecalStructure::GetEnergy(Float_t x, Float_t y) const { - ecalCell* cell=GetCell(x,y); - if (cell) - { - return cell->GetEnergy(); - } - return -1111; + ecalCell* cell = GetCell(x, y); + if (cell) { + return cell->GetEnergy(); + } + return -1111; } -//Converts (x,y) to hit Id +// Converts (x,y) to hit Id inline Int_t ecalStructure::GetHitId(Float_t x, Float_t y) const { - ecalCell* cell=GetCell(x,y); - if (cell) - return cell->GetCellNumber(); - else - return -1111; + ecalCell* cell = GetCell(x, y); + if (cell) + return cell->GetCellNumber(); + else + return -1111; } struct __ecalCellWrapper { -public: - ecalCell* cell; - Char_t isPsTen; + public: + ecalCell* cell; + Char_t isPsTen; }; #endif diff --git a/ecal/ecalStructureFiller.cxx b/ecal/ecalStructureFiller.cxx index 1ee06ef346..4b6d2a5cca 100644 --- a/ecal/ecalStructureFiller.cxx +++ b/ecal/ecalStructureFiller.cxx @@ -1,156 +1,148 @@ #include "ecalStructureFiller.h" -#include "ecalPoint.h" -#include "ecalCellMC.h" -#include "ecalInf.h" -#include "ecalStructure.h" #include "FairRootManager.h" - +#include "TClonesArray.h" #include "TRandom.h" #include "TVector3.h" -#include "TClonesArray.h" +#include "ecalCellMC.h" +#include "ecalInf.h" +#include "ecalPoint.h" +#include "ecalStructure.h" -#include #include +#include using namespace std; // ----- Default constructor ------------------------------------------- ecalStructureFiller::ecalStructureFiller() - : FairTask(), - fStr(NULL), - fInf(NULL), - fListECALpts(NULL), - fEvent(0), - fInited(kFALSE), - fUseMCPoints(kFALSE), - fStoreTrackInfo(kTRUE), - fFileGeo("") -{ -} + : FairTask() + , fStr(NULL) + , fInf(NULL) + , fListECALpts(NULL) + , fEvent(0) + , fInited(kFALSE) + , fUseMCPoints(kFALSE) + , fStoreTrackInfo(kTRUE) + , fFileGeo("") +{} // ------------------------------------------------------------------------- // ----- Standard constructor ------------------------------------------- -ecalStructureFiller::ecalStructureFiller(const char *name, const Int_t iVerbose, const char* fileGeo) - : FairTask(name,iVerbose), - fStr(NULL), - fInf(ecalInf::GetInstance(fileGeo)), - fListECALpts(NULL), - fEvent(0), - fInited(kFALSE), - fUseMCPoints(kFALSE), - fStoreTrackInfo(kTRUE), - fFileGeo(fileGeo) -{ -} +ecalStructureFiller::ecalStructureFiller(const char* name, const Int_t iVerbose, const char* fileGeo) + : FairTask(name, iVerbose) + , fStr(NULL) + , fInf(ecalInf::GetInstance(fileGeo)) + , fListECALpts(NULL) + , fEvent(0) + , fInited(kFALSE) + , fUseMCPoints(kFALSE) + , fStoreTrackInfo(kTRUE) + , fFileGeo(fileGeo) +{} // ------------------------------------------------------------------------- - // ----- Destructor ---------------------------------------------------- ecalStructureFiller::~ecalStructureFiller() { - ; + ; } // ------------------------------------------------------------------------- void ecalStructureFiller::SetParContainers() { - ; + ; } // ----- Initialization ------------------------------------------------ InitStatus ecalStructureFiller::Init() { - fInited=kTRUE; - FairRootManager* fManager = FairRootManager::Instance(); - - if (fUseMCPoints==kFALSE) - { - Warning("Init()", "No data source for structure filler! Calorimeter structure will be empty."); -// return kFATAL; - } - //ECAL MC points - if (fUseMCPoints) - fListECALpts = (TClonesArray*)fManager->GetObject("EcalPointLite"); - - //fInf->CheckVariables(); - fStr=new ecalStructure(fInf); - if (fStoreTrackInfo) fStr->SetUseMC(1); - fStr->Construct(); - - fManager->Register("EcalStructure", "ECAL", fStr, kFALSE); - return kSUCCESS; + fInited = kTRUE; + FairRootManager* fManager = FairRootManager::Instance(); + + if (fUseMCPoints == kFALSE) { + Warning("Init()", "No data source for structure filler! Calorimeter structure will be empty."); + // return kFATAL; + } + // ECAL MC points + if (fUseMCPoints) + fListECALpts = (TClonesArray*)fManager->GetObject("EcalPointLite"); + + // fInf->CheckVariables(); + fStr = new ecalStructure(fInf); + if (fStoreTrackInfo) + fStr->SetUseMC(1); + fStr->Construct(); + + fManager->Register("EcalStructure", "ECAL", fStr, kFALSE); + return kSUCCESS; } // ------------------------------------------------------------------------- - ecalStructure* ecalStructureFiller::InitPython(TClonesArray* litePoints) { - fListECALpts=litePoints; + fListECALpts = litePoints; - //fInf->CheckVariables(); - fStr=new ecalStructure(fInf); - if (fStoreTrackInfo) fStr->SetUseMC(1); - fStr->Construct(); + // fInf->CheckVariables(); + fStr = new ecalStructure(fInf); + if (fStoreTrackInfo) + fStr->SetUseMC(1); + fStr->Construct(); - return fStr; + return fStr; } - /** Loop over MCPoints hits and add them to cells **/ void ecalStructureFiller::LoopForMCPoints() { - ecalPoint* pt; - ecalCell* cell; - Int_t ten; - UInt_t n; - - n=fListECALpts->GetEntriesFast(); - if (fVerbose>0) - { - cout << ". Number of input MC points: "; - cout << n << flush; - } - - for(UInt_t j=0; jAt(j); - cell=fStr->GetCell(pt->GetDetectorID(), ten); - if (ten==0) { - cell->AddEnergy(pt->GetEnergyLoss()); + ecalPoint* pt; + ecalCell* cell; + Int_t ten; + UInt_t n; + + n = fListECALpts->GetEntriesFast(); + if (fVerbose > 0) { + cout << ". Number of input MC points: "; + cout << n << flush; } - } - if (fStoreTrackInfo) - for(UInt_t j=0; jAt(j); - ecalCellMC* cellmc=(ecalCellMC*)fStr->GetCell(pt->GetDetectorID(), ten); - if (ten==0) { - cellmc->AddTrackEnergy(pt->GetTrackID(),pt->GetEnergyLoss(), pt->GetTime()); + + for (UInt_t j = 0; j < n; j++) { + pt = (ecalPoint*)fListECALpts->At(j); + cell = fStr->GetCell(pt->GetDetectorID(), ten); + if (ten == 0) { + cell->AddEnergy(pt->GetEnergyLoss()); + } } - } + if (fStoreTrackInfo) + for (UInt_t j = 0; j < n; j++) { + pt = (ecalPoint*)fListECALpts->At(j); + ecalCellMC* cellmc = (ecalCellMC*)fStr->GetCell(pt->GetDetectorID(), ten); + if (ten == 0) { + cellmc->AddTrackEnergy(pt->GetTrackID(), pt->GetEnergyLoss(), pt->GetTime()); + } + } } // ----- Execution of Task --------------------------------------------- -void ecalStructureFiller::Exec(Option_t* option,TClonesArray* litePoints) +void ecalStructureFiller::Exec(Option_t* option, TClonesArray* litePoints) { - fEvent++; - fListECALpts=litePoints; - if (fVerbose>0) - cout << "--> Event no. " << fEvent; + fEvent++; + fListECALpts = litePoints; + if (fVerbose > 0) + cout << "--> Event no. " << fEvent; - fStr->ResetModules(); - if (fUseMCPoints) LoopForMCPoints(); + fStr->ResetModules(); + if (fUseMCPoints) + LoopForMCPoints(); - if (fVerbose>0) - cout << endl << flush; + if (fVerbose > 0) + cout << endl << flush; } // ------------------------------------------------------------------------- - // ----- Finish Task --------------------------------------------------- void ecalStructureFiller::Finish() { - ; + ; } // ------------------------------------------------------------------------- diff --git a/ecal/ecalStructureFiller.h b/ecal/ecalStructureFiller.h index 1124bb8a11..ebdb01748b 100644 --- a/ecal/ecalStructureFiller.h +++ b/ecal/ecalStructureFiller.h @@ -21,96 +21,98 @@ class ecalInf; class ecalStructure; class TClonesArray; -class ecalStructureFiller : public FairTask { - -public: - /** Default constructor **/ - ecalStructureFiller(); +class ecalStructureFiller : public FairTask +{ - /** Standard constructor **/ - ecalStructureFiller(const char *name, const Int_t iVerbose=1, const char* fileGeo="ecal_FullMC.geo"); + public: + /** Default constructor **/ + ecalStructureFiller(); - /** Destructor **/ - virtual ~ecalStructureFiller(); + /** Standard constructor **/ + ecalStructureFiller(const char* name, const Int_t iVerbose = 1, const char* fileGeo = "ecal_FullMC.geo"); - /** Initialization of the task **/ - virtual InitStatus Init(); + /** Destructor **/ + virtual ~ecalStructureFiller(); - ecalStructure* InitPython(TClonesArray* litePoints); + /** Initialization of the task **/ + virtual InitStatus Init(); - /** Executed task **/ - virtual void Exec(Option_t* option,TClonesArray* litePoints); + ecalStructure* InitPython(TClonesArray* litePoints); - /** Finish task **/ - virtual void Finish(); + /** Executed task **/ + virtual void Exec(Option_t* option, TClonesArray* litePoints); - /** Set data source for hit producer. - ** This must be called before Init() - ** (No effect other case)! **/ - void SetUseMCPoints(Bool_t UseMCPoints); + /** Finish task **/ + virtual void Finish(); - ecalStructure* GetStructure() const; - void StoreTrackInformation(Bool_t storetrackinfo=kTRUE); - Bool_t GetStoreTrackInformation() const; + /** Set data source for hit producer. + ** This must be called before Init() + ** (No effect other case)! **/ + void SetUseMCPoints(Bool_t UseMCPoints); - Bool_t GetUseMCPoints() const; - Bool_t GetUseSummableHits() const; - Bool_t GetUseHits() const; -protected: + ecalStructure* GetStructure() const; + void StoreTrackInformation(Bool_t storetrackinfo = kTRUE); + Bool_t GetStoreTrackInformation() const; -private: - /** Init parameter containers **/ - void SetParContainers(); - /** Loop over MCPoints **/ - void LoopForMCPoints(); - ecalStructure* fStr; - ecalInf* fInf; //ECAL geometry container + Bool_t GetUseMCPoints() const; + Bool_t GetUseSummableHits() const; + Bool_t GetUseHits() const; - TClonesArray* fListECALpts; // ECAL MC points - Int_t fEvent; //! Internal event counter + protected: + private: + /** Init parameter containers **/ + void SetParContainers(); + /** Loop over MCPoints **/ + void LoopForMCPoints(); + ecalStructure* fStr; + ecalInf* fInf; // ECAL geometry container - /** Is Init() already done? **/ - Bool_t fInited; - /** Should we take data from MCPoints? **/ - Bool_t fUseMCPoints; + TClonesArray* fListECALpts; // ECAL MC points + Int_t fEvent; //! Internal event counter - /** Should we store information about tracks/energy depostion **/ - Bool_t fStoreTrackInfo; - /** Geo file to use **/ - TString fFileGeo; + /** Is Init() already done? **/ + Bool_t fInited; + /** Should we take data from MCPoints? **/ + Bool_t fUseMCPoints; - ecalStructureFiller(const ecalStructureFiller&); - ecalStructureFiller& operator=(const ecalStructureFiller&); + /** Should we store information about tracks/energy depostion **/ + Bool_t fStoreTrackInfo; + /** Geo file to use **/ + TString fFileGeo; - ClassDef(ecalStructureFiller,1) + ecalStructureFiller(const ecalStructureFiller&); + ecalStructureFiller& operator=(const ecalStructureFiller&); + ClassDef(ecalStructureFiller, 1) }; inline void ecalStructureFiller::SetUseMCPoints(Bool_t UseMCPoints) { - if (fInited) return; - fUseMCPoints=UseMCPoints; + if (fInited) + return; + fUseMCPoints = UseMCPoints; } inline Bool_t ecalStructureFiller::GetUseMCPoints() const { - return fUseMCPoints; + return fUseMCPoints; } inline void ecalStructureFiller::StoreTrackInformation(Bool_t storetrackinfo) { - if (fInited) return; - fStoreTrackInfo=storetrackinfo; + if (fInited) + return; + fStoreTrackInfo = storetrackinfo; } inline Bool_t ecalStructureFiller::GetStoreTrackInformation() const { - return fStoreTrackInfo; + return fStoreTrackInfo; } inline ecalStructure* ecalStructureFiller::GetStructure() const { - return fStr; + return fStr; } #endif diff --git a/field/CMakeLists.txt b/field/CMakeLists.txt index f65668742e..2aafd2d62f 100644 --- a/field/CMakeLists.txt +++ b/field/CMakeLists.txt @@ -1,49 +1,38 @@ # Create a library called "libField” which includes the source files given in -# the array . -# The extension is already found. Any number of sources could be listed here. +# the array . The extension is already found. Any number of sources could be +# listed here. set(INCLUDE_DIRECTORIES -${CMAKE_SOURCE_DIR}/field -${ROOT_INCLUDE_DIR} -${GEANT4_VMC_INCLUDE_DIR} -${GEANT4_INCLUDE_DIR} -${FAIRROOT_INCLUDE_DIR} -${VMC_INCLUDE_DIRS} -${genfit2_INCDIR} -) + ${CMAKE_SOURCE_DIR}/field + ${ROOT_INCLUDE_DIR} + ${GEANT4_VMC_INCLUDE_DIR} + ${GEANT4_INCLUDE_DIR} + ${FAIRROOT_INCLUDE_DIR} + ${VMC_INCLUDE_DIRS} + ${genfit2_INCDIR}) -include_directories( ${INCLUDE_DIRECTORIES} -) +include_directories(${INCLUDE_DIRECTORIES}) include_directories(SYSTEM ${SYSTEM_INCLUDE_DIRECTORIES}) set(LINK_DIRECTORIES -${ROOT_LIBRARY_DIR} -${FAIRROOT_LIBRARY_DIR} -${GEANT4VMC_LIBRARY_DIR} -${GEANT4_LIBRARY_DIR} -${genfit2_LIBDIR} -) + ${ROOT_LIBRARY_DIR} ${FAIRROOT_LIBRARY_DIR} ${GEANT4VMC_LIBRARY_DIR} + ${GEANT4_LIBRARY_DIR} ${genfit2_LIBDIR}) -link_directories( ${LINK_DIRECTORIES}) +link_directories(${LINK_DIRECTORIES}) set(SRCS -ShipConstField.cxx -ShipFieldCreator.cxx -ShipFieldPar.cxx -ShipBellField.cxx -ShipBFieldMap.cxx -ShipCompField.cxx -ShipFieldMaker.cxx -ShipGoliathField.cxx -FairShipFields.cxx -) + ShipConstField.cxx + ShipFieldCreator.cxx + ShipFieldPar.cxx + ShipBellField.cxx + ShipBFieldMap.cxx + ShipCompField.cxx + ShipFieldMaker.cxx + ShipGoliathField.cxx + FairShipFields.cxx) set(LINKDEF FieldLinkDef.h) -Set(LIBRARY_NAME ShipField) -Set(DEPENDENCIES - Base - FairLogger::FairLogger - genfit2 -) +set(LIBRARY_NAME ShipField) +set(DEPENDENCIES Base FairLogger::FairLogger genfit2) -GENERATE_LIBRARY() +generate_library() diff --git a/field/FairShipFields.cxx b/field/FairShipFields.cxx index 107f155320..05eb4faedd 100644 --- a/field/FairShipFields.cxx +++ b/field/FairShipFields.cxx @@ -1,42 +1,48 @@ -/* +/* generic interface to B fields of FairShip assumes that magnetic fields for tracking are global fields, not matched to a volume. */ #include "FairShipFields.h" + #include "TVirtualMC.h" + #include using std::cout; using std::endl; -namespace genfit { +namespace genfit +{ - FairShipFields::FairShipFields() +FairShipFields::FairShipFields() : AbsBField() - { ; } - +{ + ; +} -TVector3 FairShipFields::get(const TVector3& pos) const { - Double_t bx,by,bz; - get(pos.X(),pos.Y(),pos.Z(),bx,by,bz); - TVector3 field_(bx,by,bz); - return field_; +TVector3 FairShipFields::get(const TVector3& pos) const +{ + Double_t bx, by, bz; + get(pos.X(), pos.Y(), pos.Z(), bx, by, bz); + TVector3 field_(bx, by, bz); + return field_; } -void FairShipFields::get(const double& x, const double& y, const double& z, double& Bx, double& By, double& Bz) const { - Double_t X[3] = {x,y,z}; - Double_t B[3] = {Bx,By,Bz}; - if (!gMC && !gField_){ - cout<<"no Field Manager instantiated"<GetMagField()->Field(X,B); - } else { - gField_->Field(X,B); - } - Bx = B[0]; - By = B[1]; - Bz = B[2]; +void FairShipFields::get(const double& x, const double& y, const double& z, double& Bx, double& By, double& Bz) const +{ + Double_t X[3] = {x, y, z}; + Double_t B[3] = {Bx, By, Bz}; + if (!gMC && !gField_) { + cout << "no Field Manager instantiated" << endl; + return; + } + if (gMC) { + gMC->GetMagField()->Field(X, B); + } else { + gField_->Field(X, B); + } + Bx = B[0]; + By = B[1]; + Bz = B[2]; } } /* End of namespace genfit */ diff --git a/field/FairShipFields.h b/field/FairShipFields.h index 14a22f4708..a85d291137 100644 --- a/field/FairShipFields.h +++ b/field/FairShipFields.h @@ -1,4 +1,4 @@ -/* +/* generic interface to B fields of FairShip */ @@ -8,31 +8,31 @@ generic interface to B fields of FairShip #include "AbsBField.h" #include "ShipCompField.h" - -namespace genfit { +namespace genfit +{ /** @brief Field for SHiP * * @author Thomas Ruf CERN */ -class FairShipFields : public AbsBField { - public: - - /** Default constructor **/ - FairShipFields(); +class FairShipFields : public AbsBField +{ + public: + /** Default constructor **/ + FairShipFields(); - //! set field if not gMC present - inline void setField(ShipCompField* gField) { gField_ = gField; } + //! set field if not gMC present + inline void setField(ShipCompField* gField) { gField_ = gField; } - //! return value at position - TVector3 get(const TVector3& pos) const; - void get(const double& posX, const double& posY, const double& posZ, double& Bx, double& By, double& Bz) const; + //! return value at position + TVector3 get(const TVector3& pos) const; + void get(const double& posX, const double& posY, const double& posZ, double& Bx, double& By, double& Bz) const; - private: - ShipCompField* gField_; + private: + ShipCompField* gField_; }; } /* End of namespace genfit */ /** @} */ -#endif // genfit_FairShipFields_h +#endif // genfit_FairShipFields_h diff --git a/field/ShipBFieldMap.cxx b/field/ShipBFieldMap.cxx index f756dcc699..966ccce04a 100644 --- a/field/ShipBFieldMap.cxx +++ b/field/ShipBFieldMap.cxx @@ -13,37 +13,46 @@ #include ShipBFieldMap::ShipBFieldMap(const std::string& label, - const std::string& mapFileName, - Float_t xOffset, - Float_t yOffset, - Float_t zOffset, - Float_t phi, - Float_t theta, - Float_t psi, - Float_t scale, - Bool_t isSymmetric) : - TVirtualMagField(label.c_str()), - fieldMap_(new floatArray()), - mapFileName_(mapFileName), - initialised_(kFALSE), - isCopy_(kFALSE), - Nx_(0), Ny_(0), Nz_(0), N_(0), - xMin_(0.0), xMax_(0.0), - dx_(0.0), xRange_(0.0), - yMin_(0.0), yMax_(0.0), - dy_(0.0), yRange_(0.0), - zMin_(0.0), zMax_(0.0), - dz_(0.0), zRange_(0.0), - xOffset_(xOffset), - yOffset_(yOffset), - zOffset_(zOffset), - phi_(phi), - theta_(theta), - psi_(psi), - scale_(scale), - isSymmetric_(isSymmetric), - theTrans_(0), - Tesla_(10.0) + const std::string& mapFileName, + Float_t xOffset, + Float_t yOffset, + Float_t zOffset, + Float_t phi, + Float_t theta, + Float_t psi, + Float_t scale, + Bool_t isSymmetric) + : TVirtualMagField(label.c_str()) + , fieldMap_(new floatArray()) + , mapFileName_(mapFileName) + , initialised_(kFALSE) + , isCopy_(kFALSE) + , Nx_(0) + , Ny_(0) + , Nz_(0) + , N_(0) + , xMin_(0.0) + , xMax_(0.0) + , dx_(0.0) + , xRange_(0.0) + , yMin_(0.0) + , yMax_(0.0) + , dy_(0.0) + , yRange_(0.0) + , zMin_(0.0) + , zMax_(0.0) + , dz_(0.0) + , zRange_(0.0) + , xOffset_(xOffset) + , yOffset_(yOffset) + , zOffset_(zOffset) + , phi_(phi) + , theta_(theta) + , psi_(psi) + , scale_(scale) + , isSymmetric_(isSymmetric) + , theTrans_(0) + , Tesla_(10.0) { this->initialise(); } @@ -52,48 +61,56 @@ ShipBFieldMap::~ShipBFieldMap() { // Delete the internal vector storing the field map values if (fieldMap_ && isCopy_ == kFALSE) { - delete fieldMap_; fieldMap_ = 0; + delete fieldMap_; + fieldMap_ = 0; } - if (theTrans_) {delete theTrans_; theTrans_ = 0;} - + if (theTrans_) { + delete theTrans_; + theTrans_ = 0; + } } - -ShipBFieldMap::ShipBFieldMap(const std::string& newName, const ShipBFieldMap& rhs, - Float_t newXOffset, Float_t newYOffset, Float_t newZOffset, - Float_t newPhi, Float_t newTheta, Float_t newPsi, Float_t newScale) : - TVirtualMagField(newName.c_str()), - fieldMap_(rhs.fieldMap_), - mapFileName_(rhs.GetMapFileName()), - initialised_(kFALSE), - isCopy_(kTRUE), - Nx_(rhs.Nx_), - Ny_(rhs.Ny_), - Nz_(rhs.Nz_), - N_(rhs.N_), - xMin_(rhs.xMin_), - xMax_(rhs.xMax_), - dx_(rhs.dx_), - xRange_(rhs.xRange_), - yMin_(rhs.yMin_), - yMax_(rhs.yMax_), - dy_(rhs.dy_), - yRange_(rhs.yRange_), - zMin_(rhs.zMin_), - zMax_(rhs.zMax_), - dz_(rhs.dz_), - zRange_(rhs.zRange_), - xOffset_(newXOffset), - yOffset_(newYOffset), - zOffset_(newZOffset), - phi_(newPhi), - theta_(newTheta), - psi_(newPsi), - scale_(newScale), - isSymmetric_(rhs.isSymmetric_), - theTrans_(0), - Tesla_(10.0) +ShipBFieldMap::ShipBFieldMap(const std::string& newName, + const ShipBFieldMap& rhs, + Float_t newXOffset, + Float_t newYOffset, + Float_t newZOffset, + Float_t newPhi, + Float_t newTheta, + Float_t newPsi, + Float_t newScale) + : TVirtualMagField(newName.c_str()) + , fieldMap_(rhs.fieldMap_) + , mapFileName_(rhs.GetMapFileName()) + , initialised_(kFALSE) + , isCopy_(kTRUE) + , Nx_(rhs.Nx_) + , Ny_(rhs.Ny_) + , Nz_(rhs.Nz_) + , N_(rhs.N_) + , xMin_(rhs.xMin_) + , xMax_(rhs.xMax_) + , dx_(rhs.dx_) + , xRange_(rhs.xRange_) + , yMin_(rhs.yMin_) + , yMax_(rhs.yMax_) + , dy_(rhs.dy_) + , yRange_(rhs.yRange_) + , zMin_(rhs.zMin_) + , zMax_(rhs.zMax_) + , dz_(rhs.dz_) + , zRange_(rhs.zRange_) + , xOffset_(newXOffset) + , yOffset_(newYOffset) + , zOffset_(newZOffset) + , phi_(newPhi) + , theta_(newTheta) + , psi_(newPsi) + , scale_(newScale) + , isSymmetric_(rhs.isSymmetric_) + , theTrans_(0) + , Tesla_(10.0) { // Copy constructor with new label and different global offset, which uses // the same field map data (pointer) and distance units as the rhs object @@ -111,7 +128,9 @@ void ShipBFieldMap::Field(const Double_t* position, Double_t* B) // volume transformation is ignored Double_t localCoords[3] = {position[0], position[1], position[2]}; - if (theTrans_) {theTrans_->MasterToLocal(position, localCoords);} + if (theTrans_) { + theTrans_->MasterToLocal(position, localCoords); + } // The local position co-ordinates Float_t x = localCoords[0]; @@ -131,20 +150,20 @@ void ShipBFieldMap::Field(const Double_t* position, Double_t* B) if (isSymmetric_) { - // The field map co-ordinates only contain x > 0 and y > 0, i.e. we - // are using x-y quadrant symmetry. If the local x or y coordinates - // are negative we need to change their sign and keep track of the - // adjusted sign of Bx which we use as a multiplication factor at the end - if (x < 0.0) { - x = -x; BxSign *= -1.0; - } - - if (y < 0.0) { - y = -y; - BxSign *= -1.0; - BzSign = -1.0; - } - + // The field map co-ordinates only contain x > 0 and y > 0, i.e. we + // are using x-y quadrant symmetry. If the local x or y coordinates + // are negative we need to change their sign and keep track of the + // adjusted sign of Bx which we use as a multiplication factor at the end + if (x < 0.0) { + x = -x; + BxSign *= -1.0; + } + + if (y < 0.0) { + y = -y; + BxSign *= -1.0; + BzSign = -1.0; + } } // Initialise the B field components to zero @@ -154,7 +173,9 @@ void ShipBFieldMap::Field(const Double_t* position, Double_t* B) // First check to see if we are inside the field map range Bool_t inside = this->insideRange(x, y, z); - if (inside == kFALSE) {return;} + if (inside == kFALSE) { + return; + } // Find the neighbouring bins for the given point binPair xBinInfo = this->getBinInfo(x, ShipBFieldMap::xAxis); @@ -166,7 +187,9 @@ void ShipBFieldMap::Field(const Double_t* position, Double_t* B) Int_t iZ = zBinInfo.first; // Check that the bins are valid - if (iX == -1 || iY == -1 || iZ == -1) {return;} + if (iX == -1 || iY == -1 || iZ == -1) { + return; + } // Get the various neighbouring bin entries Int_t iX1(iX + 1); @@ -194,10 +217,9 @@ void ShipBFieldMap::Field(const Double_t* position, Double_t* B) // Finally get the magnetic field components using trilinear interpolation // and scale with the appropriate multiplication factor (default = 1.0) - B[0] = this->BInterCalc(ShipBFieldMap::xAxis)*scale_*BxSign; - B[1] = this->BInterCalc(ShipBFieldMap::yAxis)*scale_; + B[0] = this->BInterCalc(ShipBFieldMap::xAxis) * scale_ * BxSign; + B[1] = this->BInterCalc(ShipBFieldMap::yAxis) * scale_; B[2] = this->BInterCalc(ShipBFieldMap::zAxis) * scale_ * BzSign; - } void ShipBFieldMap::initialise() @@ -205,62 +227,60 @@ void ShipBFieldMap::initialise() if (initialised_ == kFALSE) { - if (isCopy_ == kFALSE) {this->readMapFile();} - - // Set the global co-ordinate translation and rotation info - if (fabs(phi_) > 1e-6 || fabs(theta_) > 1e-6 || fabs(psi_) > 1e-6) { - - // We have non-zero rotation angles. Create a combined translation and rotation - TGeoTranslation tr("offsets", xOffset_, yOffset_, zOffset_); - TGeoRotation rot("angles", phi_, theta_, psi_); - theTrans_ = new TGeoCombiTrans(tr, rot); + if (isCopy_ == kFALSE) { + this->readMapFile(); + } - } else { + // Set the global co-ordinate translation and rotation info + if (fabs(phi_) > 1e-6 || fabs(theta_) > 1e-6 || fabs(psi_) > 1e-6) { - // We only need a translation - theTrans_ = new TGeoTranslation("offsets", xOffset_, yOffset_, zOffset_); + // We have non-zero rotation angles. Create a combined translation and rotation + TGeoTranslation tr("offsets", xOffset_, yOffset_, zOffset_); + TGeoRotation rot("angles", phi_, theta_, psi_); + theTrans_ = new TGeoCombiTrans(tr, rot); - } + } else { - initialised_ = kTRUE; + // We only need a translation + theTrans_ = new TGeoTranslation("offsets", xOffset_, yOffset_, zOffset_); + } + initialised_ = kTRUE; } - } void ShipBFieldMap::readMapFile() { - std::cout<<"ShipBFieldMap::readMapFile() creating field "<GetName() - <<" using file "<GetName() << " using file " << mapFileName_ + << std::endl; // Check to see if we have a ROOT file if (mapFileName_.find(".root") != std::string::npos) { - this->readRootFile(); + this->readRootFile(); } else { - this->readTextFile(); - + this->readTextFile(); } - } -void ShipBFieldMap::readRootFile() { +void ShipBFieldMap::readRootFile() +{ TFile* theFile = TFile::Open(mapFileName_.c_str()); if (!theFile) { - std::cout<<"ShipBFieldMap: could not find the file "<(theFile->Get("Range")); if (!rTree) { - std::cout<<"ShipBFieldMap: could not find Range tree in "<SetBranchAddress("xMin", &xMin_); @@ -281,104 +301,102 @@ void ShipBFieldMap::readRootFile() { // Make sure we don't have a copy if (isCopy_ == kFALSE) { - // The data is expected to contain Bx,By,Bz data values - // in ascending z,y,x co-ordinate order - - TTree* dTree = dynamic_cast(theFile->Get("Data")); - if (!dTree) { - std::cout<<"ShipBFieldMap: could not find Data tree in "<SetBranchStatus("*", 0); - dTree->SetBranchStatus("Bx", 1); - dTree->SetBranchStatus("By", 1); - dTree->SetBranchStatus("Bz", 1); - - dTree->SetBranchAddress("Bx", &Bx); - dTree->SetBranchAddress("By", &By); - dTree->SetBranchAddress("Bz", &Bz); - - Int_t nEntries = dTree->GetEntries(); - if (nEntries != N_) { - std::cout<<"Expected "<reserve(nEntries); - - for (Int_t i = 0; i < nEntries; i++) { - - dTree->GetEntry(i); - - // B field values are in Tesla. This means these values are multiplied - // by a factor of ten since both FairRoot and the VMC interface use kGauss - Bx *= Tesla_; - By *= Tesla_; - Bz *= Tesla_; - - // Store the B field 3-vector - std::vector BVector(3); - BVector[0] = Bx; BVector[1] = By; BVector[2] = Bz; - fieldMap_->push_back(BVector); - - } - + // The data is expected to contain Bx,By,Bz data values + // in ascending z,y,x co-ordinate order + + TTree* dTree = dynamic_cast(theFile->Get("Data")); + if (!dTree) { + std::cout << "ShipBFieldMap: could not find Data tree in " << mapFileName_ << std::endl; + return; + } + + Float_t Bx, By, Bz; + // Only enable the field components + dTree->SetBranchStatus("*", 0); + dTree->SetBranchStatus("Bx", 1); + dTree->SetBranchStatus("By", 1); + dTree->SetBranchStatus("Bz", 1); + + dTree->SetBranchAddress("Bx", &Bx); + dTree->SetBranchAddress("By", &By); + dTree->SetBranchAddress("Bz", &Bz); + + Int_t nEntries = dTree->GetEntries(); + if (nEntries != N_) { + std::cout << "Expected " << N_ << " field map entries but found " << nEntries << std::endl; + nEntries = 0; + } + + fieldMap_->reserve(nEntries); + + for (Int_t i = 0; i < nEntries; i++) { + + dTree->GetEntry(i); + + // B field values are in Tesla. This means these values are multiplied + // by a factor of ten since both FairRoot and the VMC interface use kGauss + Bx *= Tesla_; + By *= Tesla_; + Bz *= Tesla_; + + // Store the B field 3-vector + std::vector BVector(3); + BVector[0] = Bx; + BVector[1] = By; + BVector[2] = Bz; + fieldMap_->push_back(BVector); + } } theFile->Close(); - } -void ShipBFieldMap::readTextFile() { +void ShipBFieldMap::readTextFile() +{ std::ifstream getData(mapFileName_.c_str()); std::string tmpString(""); - getData >> tmpString >> xMin_ >> xMax_ >> dx_ - >> yMin_ >> yMax_ >> dy_ >> zMin_ >> zMax_ >> dz_; + getData >> tmpString >> xMin_ >> xMax_ >> dx_ >> yMin_ >> yMax_ >> dy_ >> zMin_ >> zMax_ >> dz_; this->setLimits(); // Check to see if this object is a "copy" if (isCopy_ == kFALSE) { - // Read the field map and store the magnetic field components - - // Second line can be ignored since they are - // just labels for the data columns for readability - getData >> tmpString >> tmpString >> tmpString; + // Read the field map and store the magnetic field components - // The remaining lines contain Bx,By,Bz data values - // in ascending z,y,x co-ord order - fieldMap_->reserve(N_); + // Second line can be ignored since they are + // just labels for the data columns for readability + getData >> tmpString >> tmpString >> tmpString; - Float_t Bx(0.0), By(0.0), Bz(0.0); + // The remaining lines contain Bx,By,Bz data values + // in ascending z,y,x co-ord order + fieldMap_->reserve(N_); - for (Int_t i = 0; i < N_; i++) { + Float_t Bx(0.0), By(0.0), Bz(0.0); - getData >> Bx >> By >> Bz; + for (Int_t i = 0; i < N_; i++) { - // B field values are in Tesla. This means these values are multiplied - // by a factor of ten since both FairRoot and the VMC interface use kGauss - Bx *= Tesla_; - By *= Tesla_; - Bz *= Tesla_; + getData >> Bx >> By >> Bz; - // Store the B field 3-vector - std::vector BVector(3); - BVector[0] = Bx; BVector[1] = By; BVector[2] = Bz; - fieldMap_->push_back(BVector); - - } + // B field values are in Tesla. This means these values are multiplied + // by a factor of ten since both FairRoot and the VMC interface use kGauss + Bx *= Tesla_; + By *= Tesla_; + Bz *= Tesla_; + // Store the B field 3-vector + std::vector BVector(3); + BVector[0] = Bx; + BVector[1] = By; + BVector[2] = Bz; + fieldMap_->push_back(BVector); + } } getData.close(); - } Bool_t ShipBFieldMap::insideRange(Float_t x, Float_t y, Float_t z) @@ -386,14 +404,15 @@ Bool_t ShipBFieldMap::insideRange(Float_t x, Float_t y, Float_t z) Bool_t inside(kFALSE); - if (x >= xMin_ && x <= xMax_ && y >= yMin_ && - y <= yMax_ && z >= zMin_ && z <= zMax_) {inside = kTRUE;} + if (x >= xMin_ && x <= xMax_ && y >= yMin_ && y <= yMax_ && z >= zMin_ && z <= zMax_) { + inside = kTRUE; + } return inside; - } -void ShipBFieldMap::setLimits() { +void ShipBFieldMap::setLimits() +{ // Since the default SHIP distance unit is cm, we do not need to convert // these map limits, i.e. cm = 1 already @@ -406,41 +425,45 @@ void ShipBFieldMap::setLimits() { // includes both the minimum and maximum values. To ensure correct rounding // up to the nearest integer we need to add 1.5 not 1.0. if (dx_ > 0.0) { - Nx_ = static_cast(((xMax_ - xMin_)/dx_) + 1.5); + Nx_ = static_cast(((xMax_ - xMin_) / dx_) + 1.5); } if (dy_ > 0.0) { - Ny_ = static_cast(((yMax_ - yMin_)/dy_) + 1.5); + Ny_ = static_cast(((yMax_ - yMin_) / dy_) + 1.5); } if (dz_ > 0.0) { - Nz_ = static_cast(((zMax_ - zMin_)/dz_) + 1.5); + Nz_ = static_cast(((zMax_ - zMin_) / dz_) + 1.5); } - N_ = Nx_*Ny_*Nz_; + N_ = Nx_ * Ny_ * Nz_; - std::cout<<"x limits: "< > floatArray; + typedef std::vector> floatArray; //! Retrieve the field map /*! \returns the field map */ - floatArray* getFieldMap() const {return fieldMap_;} + floatArray* getFieldMap() const { return fieldMap_; } //! Set the x global co-ordinate shift /*! \param [in] xValue The value of the x global co-ordinate shift (cm) */ - void SetXOffset(Float_t xValue) {xOffset_ = xValue;} + void SetXOffset(Float_t xValue) { xOffset_ = xValue; } //! Set the y global co-ordinate shift /*! \param [in] yValue The value of the y global co-ordinate shift (cm) */ - void SetYOffset(Float_t yValue) {yOffset_ = yValue;} + void SetYOffset(Float_t yValue) { yOffset_ = yValue; } //! Set the z global co-ordinate shift /*! \param [in] zValue The value of the z global co-ordinate shift (cm) */ - void SetZOffset(Float_t zValue) {zOffset_ = zValue;} + void SetZOffset(Float_t zValue) { zOffset_ = zValue; } //! Set the first Euler rotation angle phi about the z axis /*! \param [in] phi The first Euler rotation angle about the z axis (degrees) */ - void SetPhi(Float_t phi) {phi_ = phi;} + void SetPhi(Float_t phi) { phi_ = phi; } //! Set the second Euler rotation angle theta about the new x axis /*! \param [in] theta The second Euler rotation angle about the new x axis (degrees) */ - void SetTheta(Float_t theta) {theta_ = theta;} + void SetTheta(Float_t theta) { theta_ = theta; } //! Set the third Euler rotation angle psi about the new z axis /*! \param [in] psi The third Euler rotation angle about the new z axis (degrees) */ - void SetPsi(Float_t psi) {psi_ = psi;} + void SetPsi(Float_t psi) { psi_ = psi; } //! Set the field magnitude scaling factor /*! \param [in] scale The scaling factor for the field magnitude */ - void SetScale(Float_t scale) {scale_ = scale;} + void SetScale(Float_t scale) { scale_ = scale; } //! Set the boolean to specify if we have quadrant symmetry /*! \param [in] isSymmetric Boolean to specify if we have quadrant symmetry */ - void UseSymmetry(Bool_t flag) {isSymmetric_ = flag;} - + void UseSymmetry(Bool_t flag) { isSymmetric_ = flag; } //! Get the name of the map file /*! \returns the name of the map file as an STL string */ - std::string GetMapFileName() const {return mapFileName_;} + std::string GetMapFileName() const { return mapFileName_; } //! Get the number of bins along x /*! \returns the number of bins along x */ - Int_t GetNx() const {return Nx_;} + Int_t GetNx() const { return Nx_; } //! Get the number of bins along y /*! \returns the number of bins along y */ - Int_t GetNy() const {return Ny_;} + Int_t GetNy() const { return Ny_; } //! Get the number of bins along z /*! \returns the number of bins along z */ - Int_t GetNz() const {return Nz_;} + Int_t GetNz() const { return Nz_; } //! Get the total numer of bins /*! \returns the total number of bins */ - Int_t GetNBins() const {return N_;} + Int_t GetNBins() const { return N_; } //! Get the minimum value of x for the map /*! \returns the minimum x co-ordinate (cm) */ - Float_t GetXMin() const {return xMin_;} + Float_t GetXMin() const { return xMin_; } //! Get the maximum value of x for the map /*! \returns the maximum x co-ordinate (cm) */ - Float_t GetXMax() const {return xMax_;} + Float_t GetXMax() const { return xMax_; } //! Get the bin width along x for the map /*! \returns the bin width along x (cm) */ - Float_t GetdX() const {return dx_;} + Float_t GetdX() const { return dx_; } - //! Get the x co-ordinate range for the map + //! Get the x co-ordinate range for the map /*! \returns the x co-ordinate range (cm) */ - Float_t GetXRange() const {return xRange_;} + Float_t GetXRange() const { return xRange_; } - //! Get the minimum value of y for the map + //! Get the minimum value of y for the map /*! \returns the minimum y co-ordinate (cm) */ - Float_t GetYMin() const {return yMin_;} + Float_t GetYMin() const { return yMin_; } //! Get the maximum value of y for the map /*! \returns the maximum y co-ordinate (cm) */ - Float_t GetYMax() const {return yMax_;} + Float_t GetYMax() const { return yMax_; } //! Get the bin width along y for the map /*! \returns the bin width along y (cm) */ - Float_t GetdY() const {return dy_;} + Float_t GetdY() const { return dy_; } - //! Get the y co-ordinate range for the map + //! Get the y co-ordinate range for the map /*! \returns the y co-ordinate range (cm) */ - Float_t GetYRange() const {return yRange_;} + Float_t GetYRange() const { return yRange_; } //! Get the minimum value of z for the map /*! \returns the minimum z co-ordinate (cm) */ - Float_t GetZMin() const {return zMin_;} + Float_t GetZMin() const { return zMin_; } //! Get the maximum value of z for the map /*! \returns the maximum z co-ordinate (cm) */ - Float_t GetZMax() const {return zMax_;} + Float_t GetZMax() const { return zMax_; } //! Get the bin width along z for the map /*! \returns the bin width along z (cm) */ - Float_t GetdZ() const {return dz_;} + Float_t GetdZ() const { return dz_; } - //! Get the z co-ordinate range for the map + //! Get the z co-ordinate range for the map /*! \returns the z co-ordinate range (cm) */ - Float_t GetZRange() const {return zRange_;} + Float_t GetZRange() const { return zRange_; } //! Get the x offset co-ordinate of the map for global positioning /*! \returns the map's x offset co-ordinate for global positioning (cm) */ - Float_t GetXOffset() const {return xOffset_;} + Float_t GetXOffset() const { return xOffset_; } //! Get the y offset co-ordinate of the map for global positioning /*! \returns the map's y offset co-ordinate for global positioning (cm) */ - Float_t GetYOffset() const {return yOffset_;} + Float_t GetYOffset() const { return yOffset_; } //! Get the z offset co-ordinate of the map for global positioning /*! \returns the map's z offset co-ordinate for global positioning (cm) */ - Float_t GetZOffset() const {return zOffset_;} + Float_t GetZOffset() const { return zOffset_; } //! Get the first Euler rotation angle about the z axis for global positioning /*! \returns the map's first Euler rotation angle about the z axis (degrees) */ - Float_t GetPhi() const {return phi_;} + Float_t GetPhi() const { return phi_; } //! Get the second Euler rotation angle about the new x axis for global positioning /*! \returns the map's second Euler rotation angle about the new x axis (degrees) */ - Float_t GetTheta() const {return theta_;} + Float_t GetTheta() const { return theta_; } //! Get the third Euler rotation angle about the new z axis for global positioning /*! \returns the map's third Euler rotation angle about the new z axis (degrees) */ - Float_t GetPsi() const {return psi_;} + Float_t GetPsi() const { return psi_; } //! Get the field magnitude scaling factor /*! \returns the scaling factor for the field magnitude */ - Float_t GetScale() const {return scale_;} + Float_t GetScale() const { return scale_; } //! Get the boolean flag to specify if we have quadrant symmetry /*! \returns the boolean specifying if we have quadrant symmetry */ - Bool_t HasSymmetry() const {return isSymmetric_;} + Bool_t HasSymmetry() const { return isSymmetric_; } //! Get the boolean flag to specify if we are a "copy" /*! \returns the boolean copy flag status */ - Bool_t IsACopy() const {return isCopy_;} + Bool_t IsACopy() const { return isCopy_; } //! ClassDef for ROOT - ClassDef(ShipBFieldMap,1); - - - protected: - - private: + ClassDef(ShipBFieldMap, 1); + protected: + private: //! Copy constructor not implemented ShipBFieldMap(const ShipBFieldMap& rhs); @@ -294,7 +300,12 @@ class ShipBFieldMap : public TVirtualMagField ShipBFieldMap& operator=(const ShipBFieldMap& rhs); //! Enumeration to specify the co-ordinate type - enum CoordAxis {xAxis = 0, yAxis, zAxis}; + enum CoordAxis + { + xAxis = 0, + yAxis, + zAxis + }; //! Initialisation void initialise(); @@ -480,7 +491,6 @@ class ShipBFieldMap : public TVirtualMagField //! Complimentary fractional bin distance along z Float_t zFrac1_; - }; #endif diff --git a/field/ShipBellField.cxx b/field/ShipBellField.cxx index c7e5f115fc..5da2e4529d 100644 --- a/field/ShipBellField.cxx +++ b/field/ShipBellField.cxx @@ -2,154 +2,149 @@ // ----- ShipBellField source file ----- // ------------------------------------------------------------------------- #include "ShipBellField.h" -#include "math.h" + #include "ShipFieldPar.h" +#include "math.h" #include #include -using std::cout; using std::cerr; +using std::cout; using std::endl; using std::setw; Double_t kilogauss = 1.; -Double_t tesla = 10*kilogauss; - -Double_t cm = 1; // cm -Double_t m = 100*cm; // m -Double_t mm = 0.1*cm; // mm +Double_t tesla = 10 * kilogauss; +Double_t cm = 1; // cm +Double_t m = 100 * cm; // m +Double_t mm = 0.1 * cm; // mm // ----- Default constructor ------------------------------------------- ShipBellField::ShipBellField() - : FairField(), - fPeak(0.), - fMiddle(0.), - fBtube(0.) + : FairField() + , fPeak(0.) + , fMiddle(0.) + , fBtube(0.) { - fType = 1; - fInclTarget=kFALSE; + fType = 1; + fInclTarget = kFALSE; } // ------------------------------------------------------------------------- - - // ----- Standard constructor ------------------------------------------ -ShipBellField::ShipBellField(const char* name, Double_t Peak,Double_t Middle,Int_t orientation, Double_t Btube ) - : FairField(name), - fPeak(Peak), - fMiddle(Middle), - fBtube(Btube) +ShipBellField::ShipBellField(const char* name, Double_t Peak, Double_t Middle, Int_t orientation, Double_t Btube) + : FairField(name) + , fPeak(Peak) + , fMiddle(Middle) + , fBtube(Btube) { - fType=1; - fInclTarget=kFALSE; - fOrient = orientation; - fBtube = Btube; + fType = 1; + fInclTarget = kFALSE; + fOrient = orientation; + fBtube = Btube; } // ------------------------------------------------------------------------- - - // -------- Bell constructor from FieldPar ------------------------------- ShipBellField::ShipBellField(ShipFieldPar* fieldPar) - : FairField(), - fPeak(0.), - fMiddle(0.), - fBtube(0.), - fInclTarget(kFALSE) + : FairField() + , fPeak(0.) + , fMiddle(0.) + , fBtube(0.) + , fInclTarget(kFALSE) { - if ( ! fieldPar ) { - cerr << "-W- ShipBellField::ShipBellField: empty parameter container!" - << endl; - fType=0; - } - else { - fPeak = fieldPar->GetPeak(); - fMiddle = fieldPar->GetMiddle(); - fBtube = fieldPar->GetBtube(); - fType = fieldPar->GetType(); - } + if (!fieldPar) { + cerr << "-W- ShipBellField::ShipBellField: empty parameter container!" << endl; + fType = 0; + } else { + fPeak = fieldPar->GetPeak(); + fMiddle = fieldPar->GetMiddle(); + fBtube = fieldPar->GetBtube(); + fType = fieldPar->GetType(); + } } // ------------------------------------------------------------------------- - - // ----- Destructor ---------------------------------------------------- -ShipBellField::~ShipBellField() { } +ShipBellField::~ShipBellField() {} // ------------------------------------------------------------------------- // ----- Get x component of field -------------------------------------- -void ShipBellField::IncludeTarget(Double_t xy, Double_t z, Double_t l) { - fInclTarget = kTRUE; - targetXY = xy; - targetZ0 = z; - targetL = l; +void ShipBellField::IncludeTarget(Double_t xy, Double_t z, Double_t l) +{ + fInclTarget = kTRUE; + targetXY = xy; + targetZ0 = z; + targetL = l; } // ----- Get x component of field -------------------------------------- -Double_t ShipBellField::GetBx(Double_t x, Double_t y, Double_t z) { - if (fOrient==1){ return 0.;} - else { - Double_t zlocal=fabs(z-fMiddle)/100.; //zlocal: convert cm->m - //old Bell field from Wilfried Flegel - //Double_t bx= fPeak/(1.+pow(fabs(zlocal)/2.1,6.)); - //new field based on simulation of Davide Tommasini (22/1/2015) - - Double_t bx=0.; - //field in box 20 cm larger than inner tube. - if ( (fabs(x)<2.7*m) && (fabs(y)m + // old Bell field from Wilfried Flegel + // Double_t bx= fPeak/(1.+pow(fabs(zlocal)/2.1,6.)); + // new field based on simulation of Davide Tommasini (22/1/2015) + + Double_t bx = 0.; + // field in box 20 cm larger than inner tube. + if ((fabs(x) < 2.7 * m) && (fabs(y) < fBtube + 0.2 * m)) { + if (zlocal < 3.8) { + bx = 0.14361 * exp(-0.5 * pow((zlocal - 0.45479E-01) / 2.5046, 2.)); + } else if (zlocal < 11.9) { + bx = 0.19532 - 0.61512E-01 * zlocal + 0.68447E-02 * pow(zlocal, 2.) - 0.25672E-03 * pow(zlocal, 3.); + } + bx = ((fPeak / tesla) / 0.14361) * bx * tesla; + } + // cout << "Bell GetBX " << x << ", " << y << ", " << z << ", Bx= " << bx << endl; + return bx; } - // cout << "Bell GetBX " << x << ", " << y << ", " << z << ", Bx= " << bx << endl; - return bx; - } } // ------------------------------------------------------------------------- - // ----- Get y component of field -------------------------------------- -Double_t ShipBellField::GetBy(Double_t x, Double_t y, Double_t z) { - Double_t by = 0.; - if (fInclTarget && z < targetZ0+targetL && z > targetZ0){ - // check if in target area - if (fabs(x)2*targetXY && fabs(x)<3*targetXY && fabs(y) ** @since 25.03.2014 @@ -13,71 +12,58 @@ ** Bpeak/(1+abs((z-zmiddle)/2.1)**6) **/ - #ifndef ShipBellField_H #define ShipBellField_H 1 - #include "FairField.h" - class ShipFieldPar; - class ShipBellField : public FairField { - public: - - /** Default constructor **/ - ShipBellField(); - - - /** Standard constructor - ** @param name Object name - ** @param Bpeak peak field.. - ** @param Zmiddle middle of the magnet (global coordinates) - ** @param Btube largest radius of the tube ellips (inside) - **/ - ShipBellField(const char* name, Double_t Bpeak, Double_t Zmiddle,Int_t fOrient=1, Double_t Btube=500. ); - - - /** Constructor from ShipFieldPar **/ - ShipBellField(ShipFieldPar* fieldPar); - - - /** Destructor **/ - virtual ~ShipBellField(); - - - /** Get components of field at a given point - ** @param x,y,z Point coordinates [cm] - **/ - virtual Double_t GetBx(Double_t x, Double_t y, Double_t z); - virtual Double_t GetBy(Double_t x, Double_t y, Double_t z); - virtual Double_t GetBz(Double_t x, Double_t y, Double_t z); - - void IncludeTarget(Double_t xy, Double_t z, Double_t l); - - /** Screen output **/ - virtual void Print(); - - - private: - - /** Field parameters **/ - Double_t fPeak; - Double_t fMiddle; - Double_t fBtube; - Int_t fOrient; - Bool_t fInclTarget; - Double_t targetXY; - Double_t targetZ0; - Double_t targetL; - - ClassDef(ShipBellField, 2); - + public: + /** Default constructor **/ + ShipBellField(); + + /** Standard constructor + ** @param name Object name + ** @param Bpeak peak field.. + ** @param Zmiddle middle of the magnet (global coordinates) + ** @param Btube largest radius of the tube ellips (inside) + **/ + ShipBellField(const char* name, Double_t Bpeak, Double_t Zmiddle, Int_t fOrient = 1, Double_t Btube = 500.); + + /** Constructor from ShipFieldPar **/ + ShipBellField(ShipFieldPar* fieldPar); + + /** Destructor **/ + virtual ~ShipBellField(); + + /** Get components of field at a given point + ** @param x,y,z Point coordinates [cm] + **/ + virtual Double_t GetBx(Double_t x, Double_t y, Double_t z); + virtual Double_t GetBy(Double_t x, Double_t y, Double_t z); + virtual Double_t GetBz(Double_t x, Double_t y, Double_t z); + + void IncludeTarget(Double_t xy, Double_t z, Double_t l); + + /** Screen output **/ + virtual void Print(); + + private: + /** Field parameters **/ + Double_t fPeak; + Double_t fMiddle; + Double_t fBtube; + Int_t fOrient; + Bool_t fInclTarget; + Double_t targetXY; + Double_t targetZ0; + Double_t targetL; + + ClassDef(ShipBellField, 2); }; - #endif diff --git a/field/ShipCompField.cxx b/field/ShipCompField.cxx index 5461cb8d36..dce184686d 100644 --- a/field/ShipCompField.cxx +++ b/field/ShipCompField.cxx @@ -7,30 +7,25 @@ #include -ShipCompField::ShipCompField(const std::string& label, - TVirtualMagField* firstField) : - TVirtualMagField(label.c_str()), - theFields_() +ShipCompField::ShipCompField(const std::string& label, TVirtualMagField* firstField) + : TVirtualMagField(label.c_str()) + , theFields_() { theFields_.push_back(firstField); } -ShipCompField::ShipCompField(const std::string& label, - TVirtualMagField* firstField, - TVirtualMagField* secondField) : - TVirtualMagField(label.c_str()), - theFields_() +ShipCompField::ShipCompField(const std::string& label, TVirtualMagField* firstField, TVirtualMagField* secondField) + : TVirtualMagField(label.c_str()) + , theFields_() { theFields_.push_back(firstField); theFields_.push_back(secondField); } -ShipCompField::ShipCompField(const std::string& label, - const std::vector& theFields) : - TVirtualMagField(label.c_str()), - theFields_(theFields) -{ -} +ShipCompField::ShipCompField(const std::string& label, const std::vector& theFields) + : TVirtualMagField(label.c_str()) + , theFields_(theFields) +{} ShipCompField::~ShipCompField() { @@ -49,25 +44,22 @@ void ShipCompField::Field(const Double_t* position, Double_t* B) std::vector::const_iterator iter; for (iter = theFields_.begin(); iter != theFields_.end(); ++iter) { - TVirtualMagField* theField = *iter; - if (theField) { - - //std::cout<<"Finding field for "<GetName()<Field(position, BVect); + // std::cout<<"Finding field for "<GetName()<Field(position, BVect); - //std::cout<<"B = "< #include -class ShipCompField: public TVirtualMagField +class ShipCompField : public TVirtualMagField { - public: - + public: //! Main constructor /*! \param [in] label A descriptive name/title/lable for the composite field @@ -29,8 +28,7 @@ class ShipCompField: public TVirtualMagField \param [in] firstField The first magnetic field pointer for the composite \param [in] secondField The second magnetic field pointer for the composite */ - ShipCompField(const std::string& label, TVirtualMagField* firstField, - TVirtualMagField* secondField); + ShipCompField(const std::string& label, TVirtualMagField* firstField, TVirtualMagField* secondField); //! More general constructor /*! @@ -53,28 +51,25 @@ class ShipCompField: public TVirtualMagField /*! \returns the number of fields used in the composite */ - size_t nComposite() const {return theFields_.size();} + size_t nComposite() const { return theFields_.size(); } //! Get the vector of fields /*! \returns the vector of fields */ - std::vector getCompFields() const {return theFields_;} + std::vector getCompFields() const { return theFields_; } //! ClassDef for ROOT - ClassDef(ShipCompField,1); - - protected: - - private: + ClassDef(ShipCompField, 1); + protected: + private: //! Private copy and assignment operators. ShipCompField(const ShipCompField&); ShipCompField& operator=(const ShipCompField&); //! The vector of the various magnetic field pointers comprising the composite std::vector theFields_; - }; #endif diff --git a/field/ShipConstField.cxx b/field/ShipConstField.cxx index 64d295d983..e9dc479f7c 100644 --- a/field/ShipConstField.cxx +++ b/field/ShipConstField.cxx @@ -10,170 +10,156 @@ #include #include -using std::cout; using std::cerr; +using std::cout; using std::endl; using std::setw; - // ----- Default constructor ------------------------------------------- ShipConstField::ShipConstField() - : FairField(), - fXmin(0.), - fXmax(0.), - fYmin(0.), - fYmax(0.), - fZmin(0.), - fZmax(0.), - fBx(0.), - fBy(0.), - fBz(0.) + : FairField() + , fXmin(0.) + , fXmax(0.) + , fYmin(0.) + , fYmax(0.) + , fZmin(0.) + , fZmax(0.) + , fBx(0.) + , fBy(0.) + , fBz(0.) { - fType = 0; + fType = 0; } // ------------------------------------------------------------------------- - - // ----- Standard constructor ------------------------------------------ -ShipConstField::ShipConstField(const char* name, Double_t xMin, - Double_t xMax, Double_t yMin, - Double_t yMax, Double_t zMin, - Double_t zMax, Double_t bX, - Double_t bY, Double_t bZ) - : FairField(name), - fXmin(xMin), - fXmax(xMax), - fYmin(yMin), - fYmax(yMax), - fZmin(zMin), - fZmax(zMax), - fBx(bX), - fBy(bY), - fBz(bZ) +ShipConstField::ShipConstField(const char* name, + Double_t xMin, + Double_t xMax, + Double_t yMin, + Double_t yMax, + Double_t zMin, + Double_t zMax, + Double_t bX, + Double_t bY, + Double_t bZ) + : FairField(name) + , fXmin(xMin) + , fXmax(xMax) + , fYmin(yMin) + , fYmax(yMax) + , fZmin(zMin) + , fZmax(zMax) + , fBx(bX) + , fBy(bY) + , fBz(bZ) { - fType=0; + fType = 0; } // ------------------------------------------------------------------------- - - // -------- Constructor from CbmFieldPar ------------------------------- ShipConstField::ShipConstField(ShipFieldPar* fieldPar) - : FairField(), - fXmin(0.), - fXmax(0.), - fYmin(0.), - fYmax(0.), - fZmin(0.), - fZmax(0.), - fBx(0.), - fBy(0.), - fBz(0.) + : FairField() + , fXmin(0.) + , fXmax(0.) + , fYmin(0.) + , fYmax(0.) + , fZmin(0.) + , fZmax(0.) + , fBx(0.) + , fBy(0.) + , fBz(0.) { - if ( ! fieldPar ) { - cerr << "-W- ShipConstField::ShipConstField: empty parameter container!" - << endl; - fType=0; - } - else { - fXmin = fieldPar->GetXmin(); - fXmax = fieldPar->GetXmax(); - fYmin = fieldPar->GetYmin(); - fYmax = fieldPar->GetYmax(); - fZmin = fieldPar->GetZmin(); - fZmax = fieldPar->GetZmax(); - fBx = fieldPar->GetBx(); - fBy = fieldPar->GetBy(); - fBz = fieldPar->GetBz(); - fType = fieldPar->GetType(); - } + if (!fieldPar) { + cerr << "-W- ShipConstField::ShipConstField: empty parameter container!" << endl; + fType = 0; + } else { + fXmin = fieldPar->GetXmin(); + fXmax = fieldPar->GetXmax(); + fYmin = fieldPar->GetYmin(); + fYmax = fieldPar->GetYmax(); + fZmin = fieldPar->GetZmin(); + fZmax = fieldPar->GetZmax(); + fBx = fieldPar->GetBx(); + fBy = fieldPar->GetBy(); + fBz = fieldPar->GetBz(); + fType = fieldPar->GetType(); + } } // ------------------------------------------------------------------------- - - // ----- Destructor ---------------------------------------------------- -ShipConstField::~ShipConstField() { } +ShipConstField::~ShipConstField() {} // ------------------------------------------------------------------------- - - // ----- Set field region ---------------------------------------------- -void ShipConstField::SetFieldRegion(Double_t xMin, Double_t xMax, - Double_t yMin, Double_t yMax, - Double_t zMin, Double_t zMax) { - fXmin = xMin; - fXmax = xMax; - fYmin = yMin; - fYmax = yMax; - fZmin = zMin; - fZmax = zMax; +void ShipConstField::SetFieldRegion(Double_t xMin, + Double_t xMax, + Double_t yMin, + Double_t yMax, + Double_t zMin, + Double_t zMax) +{ + fXmin = xMin; + fXmax = xMax; + fYmin = yMin; + fYmax = yMax; + fZmin = zMin; + fZmax = zMax; } // ------------------------------------------------------------------------- - - // ----- Set field values ---------------------------------------------- -void ShipConstField::SetField(Double_t bX, Double_t bY, Double_t bZ) { - fBx = bX; - fBy = bY; - fBz = bZ; +void ShipConstField::SetField(Double_t bX, Double_t bY, Double_t bZ) +{ + fBx = bX; + fBy = bY; + fBz = bZ; } // ------------------------------------------------------------------------- - - // ----- Get x component of field -------------------------------------- -Double_t ShipConstField::GetBx(Double_t x, Double_t y, Double_t z) { - if ( x < fXmin || x > fXmax || - y < fYmin || y > fYmax || - z < fZmin || z > fZmax ) return 0.; - return fBx; +Double_t ShipConstField::GetBx(Double_t x, Double_t y, Double_t z) +{ + if (x < fXmin || x > fXmax || y < fYmin || y > fYmax || z < fZmin || z > fZmax) + return 0.; + return fBx; } // ------------------------------------------------------------------------- - - // ----- Get y component of field -------------------------------------- -Double_t ShipConstField::GetBy(Double_t x, Double_t y, Double_t z) { - if ( x < fXmin || x > fXmax || - y < fYmin || y > fYmax || - z < fZmin || z > fZmax ) return 0.; - return fBy; +Double_t ShipConstField::GetBy(Double_t x, Double_t y, Double_t z) +{ + if (x < fXmin || x > fXmax || y < fYmin || y > fYmax || z < fZmin || z > fZmax) + return 0.; + return fBy; } // ------------------------------------------------------------------------- - - // ----- Get z component of field -------------------------------------- -Double_t ShipConstField::GetBz(Double_t x, Double_t y, Double_t z) { - if ( x < fXmin || x > fXmax || - y < fYmin || y > fYmax || - z < fZmin || z > fZmax ) return 0.; - return fBz; +Double_t ShipConstField::GetBz(Double_t x, Double_t y, Double_t z) +{ + if (x < fXmin || x > fXmax || y < fYmin || y > fYmax || z < fZmin || z > fZmax) + return 0.; + return fBz; } // ------------------------------------------------------------------------- - - // ----- Screen output ------------------------------------------------- -void ShipConstField::Print() { - cout << "======================================================" << endl; - cout << "---- " << fTitle << " : " << fName << endl; - cout << "----" << endl; - cout << "---- Field type : constant" << endl; - cout << "----" << endl; - cout << "---- Field regions : " << endl; - cout << "---- x = " << setw(4) << fXmin << " to " << setw(4) - << fXmax << " cm" << endl; - cout << "---- y = " << setw(4) << fYmin << " to " << setw(4) - << fYmax << " cm" << endl; - cout << "---- z = " << setw(4) << fZmin << " to " << setw(4) - << fZmax << " cm" << endl; - cout.precision(4); - cout << "---- B = ( " << fBx << ", " << fBy << ", " << fBz << " ) kG" - << endl; - cout << "======================================================" << endl; +void ShipConstField::Print() +{ + cout << "======================================================" << endl; + cout << "---- " << fTitle << " : " << fName << endl; + cout << "----" << endl; + cout << "---- Field type : constant" << endl; + cout << "----" << endl; + cout << "---- Field regions : " << endl; + cout << "---- x = " << setw(4) << fXmin << " to " << setw(4) << fXmax << " cm" << endl; + cout << "---- y = " << setw(4) << fYmin << " to " << setw(4) << fYmax << " cm" << endl; + cout << "---- z = " << setw(4) << fZmin << " to " << setw(4) << fZmax << " cm" << endl; + cout.precision(4); + cout << "---- B = ( " << fBx << ", " << fBy << ", " << fBz << " ) kG" << endl; + cout << "======================================================" << endl; } // ------------------------------------------------------------------------- diff --git a/field/ShipConstField.h b/field/ShipConstField.h index 5358591028..88dc6e7d62 100644 --- a/field/ShipConstField.h +++ b/field/ShipConstField.h @@ -3,7 +3,6 @@ // ----- Created 25/03/14 by M. Al-Turany ----- // ------------------------------------------------------------------------- - /** ShipConstField.h ** @author M.Al-Turany ** @since 25.03.2014 @@ -12,106 +11,94 @@ ** A constant (homogeneous) magnetic field **/ - #ifndef ShipConstField_H #define ShipConstField_H 1 - #include "FairField.h" - class ShipFieldPar; - class ShipConstField : public FairField { - public: - - /** Default constructor **/ - ShipConstField(); - - - /** Standard constructor - ** @param name Object name - ** @param xMin,xMax x region of field (global coordinates) - ** @param yMin,yMax y region of field (global coordinates) - ** @param zMin,zMax z region of field (global coordinates) - ** @param bX,bY,bZ Field values [kG] - **/ - ShipConstField(const char* name, Double_t xMin, Double_t xMax, - Double_t yMin, Double_t yMax, Double_t zMin, - Double_t zMax, Double_t bX, Double_t bY, Double_t bZ); - - - /** Constructor from ShipFieldPar **/ - ShipConstField(ShipFieldPar* fieldPar); - - - /** Destructor **/ - virtual ~ShipConstField(); - - - /** Set the field region - ** @param xMin,xMax x region of field (global coordinates) - ** @param yMin,yMax y region of field (global coordinates) - ** @param zMin,zMax z region of field (global coordinates) - **/ - void SetFieldRegion(Double_t xMin, Double_t xMax, Double_t yMin, - Double_t yMax, Double_t zMin, Double_t zMax); - - - /** Set the field values - ** @param bX,bY,bZ Field values [kG] - **/ - void SetField(Double_t bX, Double_t bY, Double_t bZ); - - - /** Get components of field at a given point - ** @param x,y,z Point coordinates [cm] - **/ - virtual Double_t GetBx(Double_t x, Double_t y, Double_t z); - virtual Double_t GetBy(Double_t x, Double_t y, Double_t z); - virtual Double_t GetBz(Double_t x, Double_t y, Double_t z); - - - /** Accessors to field region **/ - Double_t GetXmin() const { return fXmin; } - Double_t GetXmax() const { return fXmax; } - Double_t GetYmin() const { return fYmin; } - Double_t GetYmax() const { return fYmax; } - Double_t GetZmin() const { return fZmin; } - Double_t GetZmax() const { return fZmax; } - - - /** Accessors to field values **/ - Double_t GetBx() const { return fBx; } - Double_t GetBy() const { return fBy; } - Double_t GetBz() const { return fBz; } - - - /** Screen output **/ - virtual void Print(); - - - private: - - /** Limits of the field region **/ - Double_t fXmin; - Double_t fXmax; - Double_t fYmin; - Double_t fYmax; - Double_t fZmin; - Double_t fZmax; - - /** Field components inside the field region **/ - Double_t fBx; - Double_t fBy; - Double_t fBz; - - ClassDef(ShipConstField, 1); - + public: + /** Default constructor **/ + ShipConstField(); + + /** Standard constructor + ** @param name Object name + ** @param xMin,xMax x region of field (global coordinates) + ** @param yMin,yMax y region of field (global coordinates) + ** @param zMin,zMax z region of field (global coordinates) + ** @param bX,bY,bZ Field values [kG] + **/ + ShipConstField(const char* name, + Double_t xMin, + Double_t xMax, + Double_t yMin, + Double_t yMax, + Double_t zMin, + Double_t zMax, + Double_t bX, + Double_t bY, + Double_t bZ); + + /** Constructor from ShipFieldPar **/ + ShipConstField(ShipFieldPar* fieldPar); + + /** Destructor **/ + virtual ~ShipConstField(); + + /** Set the field region + ** @param xMin,xMax x region of field (global coordinates) + ** @param yMin,yMax y region of field (global coordinates) + ** @param zMin,zMax z region of field (global coordinates) + **/ + void SetFieldRegion(Double_t xMin, Double_t xMax, Double_t yMin, Double_t yMax, Double_t zMin, Double_t zMax); + + /** Set the field values + ** @param bX,bY,bZ Field values [kG] + **/ + void SetField(Double_t bX, Double_t bY, Double_t bZ); + + /** Get components of field at a given point + ** @param x,y,z Point coordinates [cm] + **/ + virtual Double_t GetBx(Double_t x, Double_t y, Double_t z); + virtual Double_t GetBy(Double_t x, Double_t y, Double_t z); + virtual Double_t GetBz(Double_t x, Double_t y, Double_t z); + + /** Accessors to field region **/ + Double_t GetXmin() const { return fXmin; } + Double_t GetXmax() const { return fXmax; } + Double_t GetYmin() const { return fYmin; } + Double_t GetYmax() const { return fYmax; } + Double_t GetZmin() const { return fZmin; } + Double_t GetZmax() const { return fZmax; } + + /** Accessors to field values **/ + Double_t GetBx() const { return fBx; } + Double_t GetBy() const { return fBy; } + Double_t GetBz() const { return fBz; } + + /** Screen output **/ + virtual void Print(); + + private: + /** Limits of the field region **/ + Double_t fXmin; + Double_t fXmax; + Double_t fYmin; + Double_t fYmax; + Double_t fZmin; + Double_t fZmax; + + /** Field components inside the field region **/ + Double_t fBx; + Double_t fBy; + Double_t fBz; + + ClassDef(ShipConstField, 1); }; - #endif diff --git a/field/ShipFieldCreator.cxx b/field/ShipFieldCreator.cxx index 8828c8cf8f..771f9c4197 100644 --- a/field/ShipFieldCreator.cxx +++ b/field/ShipFieldCreator.cxx @@ -1,57 +1,53 @@ #include "ShipFieldCreator.h" -#include "ShipFieldPar.h" -#include "ShipConstField.h" - +#include "FairField.h" #include "FairRunAna.h" #include "FairRuntimeDb.h" -#include "FairField.h" +#include "ShipConstField.h" +#include "ShipFieldPar.h" #include -using std::cout; using std::cerr; +using std::cout; using std::endl; static ShipFieldCreator gShipFieldCreator; ShipFieldCreator::ShipFieldCreator() - :FairFieldFactory(), - fFieldPar(NULL) + : FairFieldFactory() + , fFieldPar(NULL) { - fCreator=this; + fCreator = this; } -ShipFieldCreator::~ShipFieldCreator() -{ -} +ShipFieldCreator::~ShipFieldCreator() {} void ShipFieldCreator::SetParm() { - FairRunAna *Run = FairRunAna::Instance(); - FairRuntimeDb *RunDB = Run->GetRuntimeDb(); - fFieldPar = (ShipFieldPar*) RunDB->getContainer("ShipFieldPar"); - + FairRunAna* Run = FairRunAna::Instance(); + FairRuntimeDb* RunDB = Run->GetRuntimeDb(); + fFieldPar = (ShipFieldPar*)RunDB->getContainer("ShipFieldPar"); } FairField* ShipFieldCreator::createFairField() { - FairField *fMagneticField=0; - - if ( ! fFieldPar ) { - cerr << "-E- No field parameters available!" - << endl; - }else{ - // Instantiate correct field type - Int_t fType = fFieldPar->GetType(); - if ( fType == 0 ) fMagneticField = new ShipConstField(fFieldPar); - else cerr << "-W- FairRunAna::GetField: Unknown field type " << fType - << endl; - cout << "New field at " << fMagneticField << ", type " << fType << endl; - // Initialise field - if ( fMagneticField ) { - fMagneticField->Init(); - fMagneticField->Print(""); - } - } - return fMagneticField; + FairField* fMagneticField = 0; + + if (!fFieldPar) { + cerr << "-E- No field parameters available!" << endl; + } else { + // Instantiate correct field type + Int_t fType = fFieldPar->GetType(); + if (fType == 0) + fMagneticField = new ShipConstField(fFieldPar); + else + cerr << "-W- FairRunAna::GetField: Unknown field type " << fType << endl; + cout << "New field at " << fMagneticField << ", type " << fType << endl; + // Initialise field + if (fMagneticField) { + fMagneticField->Init(); + fMagneticField->Print(""); + } + } + return fMagneticField; } diff --git a/field/ShipFieldCreator.h b/field/ShipFieldCreator.h index 13b2ba8ae0..448e67dd64 100644 --- a/field/ShipFieldCreator.h +++ b/field/ShipFieldCreator.h @@ -3,7 +3,6 @@ // ----- Created 26/03/14 by M. Al-Turany ----- // ------------------------------------------------------------------------- - #ifndef ShipFieldCreator_H #define ShipFieldCreator_H @@ -16,19 +15,18 @@ class FairField; class ShipFieldCreator : public FairFieldFactory { - public: - ShipFieldCreator(); - virtual ~ShipFieldCreator(); - virtual FairField* createFairField(); - virtual void SetParm(); - ClassDef(ShipFieldCreator,1); - - protected: - ShipFieldPar* fFieldPar; + public: + ShipFieldCreator(); + virtual ~ShipFieldCreator(); + virtual FairField* createFairField(); + virtual void SetParm(); + ClassDef(ShipFieldCreator, 1); - private: - ShipFieldCreator(const ShipFieldCreator&); - ShipFieldCreator& operator=(const ShipFieldCreator&); + protected: + ShipFieldPar* fFieldPar; + private: + ShipFieldCreator(const ShipFieldCreator&); + ShipFieldCreator& operator=(const ShipFieldCreator&); }; -#endif //ShipFieldCreator_H +#endif // ShipFieldCreator_H diff --git a/field/ShipFieldMaker.cxx b/field/ShipFieldMaker.cxx index 2e0e5da8cd..33c530badd 100644 --- a/field/ShipFieldMaker.cxx +++ b/field/ShipFieldMaker.cxx @@ -11,41 +11,41 @@ */ #include "ShipFieldMaker.h" + #include "ShipBFieldMap.h" -#include "ShipConstField.h" #include "ShipBellField.h" - -#include "TGeoManager.h" +#include "ShipConstField.h" +#include "TCanvas.h" #include "TGeoChecker.h" -#include "TGeoPhysicalNode.h" -#include "TGeoUniformMagField.h" +#include "TGeoManager.h" #include "TGeoMatrix.h" #include "TGeoNode.h" +#include "TGeoPhysicalNode.h" +#include "TGeoUniformMagField.h" #include "TGeoVolume.h" -#include "TVirtualMC.h" -#include "TObjArray.h" #include "TH2.h" -#include "TCanvas.h" -#include "TStyle.h" +#include "TObjArray.h" #include "TROOT.h" +#include "TStyle.h" +#include "TVirtualMC.h" +#include #include #include #include -#include -ShipFieldMaker::ShipFieldMaker(Bool_t verbose) : - TG4VUserPostDetConstruction(), - globalField_(0), - theFields_(), - regionInfo_(), - localInfo_(), - verbose_(verbose), - Tesla_(10.0), // To convert T to kGauss for VMC/FairRoot - theNode_(0), - gotNode_(kFALSE) -{ -} +ShipFieldMaker::ShipFieldMaker(Bool_t verbose) + : TG4VUserPostDetConstruction() + , globalField_(0) + , theFields_() + , regionInfo_() + , localInfo_() + , verbose_(verbose) + , Tesla_(10.0) + , // To convert T to kGauss for VMC/FairRoot + theNode_(0) + , gotNode_(kFALSE) +{} ShipFieldMaker::~ShipFieldMaker() { @@ -54,12 +54,10 @@ ShipFieldMaker::~ShipFieldMaker() SFMap::iterator iter; for (iter = theFields_.begin(); iter != theFields_.end(); ++iter) { - delete iter->second; - + delete iter->second; } theFields_.clear(); - } void ShipFieldMaker::Construct() @@ -68,7 +66,6 @@ void ShipFieldMaker::Construct() // Assign volumes with their regional (local + global) or local B fields this->setAllRegionFields(); this->setAllLocalFields(); - } void ShipFieldMaker::readInputFile(const std::string& inputFile) @@ -76,14 +73,15 @@ void ShipFieldMaker::readInputFile(const std::string& inputFile) // Check that we have a non-empty string if (inputFile.size() < 1) { - std::cerr<<"Skipping ShipFieldMaker::readInputFile(): file name is empty"< lineVect = this->splitString(line, whiteSpace); + // Split up the line according to white spaces + std::vector lineVect = this->splitString(line, whiteSpace); - size_t nWords = lineVect.size(); + size_t nWords = lineVect.size(); - // Check to see if we have at least one keyword at the start of the line - if (nWords > 1) { + // Check to see if we have at least one keyword at the start of the line + if (nWords > 1) { - TString keyWord(lineVect[0].c_str()); - keyWord.ToLower(); + TString keyWord(lineVect[0].c_str()); + keyWord.ToLower(); - if (!keyWord.CompareTo("uniform")) { + if (!keyWord.CompareTo("uniform")) { - // Define the uniform magnetic field - this->defineUniform(lineVect); + // Define the uniform magnetic field + this->defineUniform(lineVect); - } else if (!keyWord.CompareTo("constant")) { + } else if (!keyWord.CompareTo("constant")) { - // Define a uniform field with an x,y,z boundary - this->defineConstant(lineVect); + // Define a uniform field with an x,y,z boundary + this->defineConstant(lineVect); - } else if (!keyWord.CompareTo("bell")) { + } else if (!keyWord.CompareTo("bell")) { - // Define the Bell-shaped field - this->defineBell(lineVect); + // Define the Bell-shaped field + this->defineBell(lineVect); - } else if (!keyWord.CompareTo("fieldmap")) { + } else if (!keyWord.CompareTo("fieldmap")) { - // Define the field map - this->defineFieldMap(lineVect); + // Define the field map + this->defineFieldMap(lineVect); - } else if (!keyWord.CompareTo("symfieldmap")) { + } else if (!keyWord.CompareTo("symfieldmap")) { - // Define the symmetric field map - this->defineFieldMap(lineVect, kTRUE); + // Define the symmetric field map + this->defineFieldMap(lineVect, kTRUE); - } else if (!keyWord.CompareTo("copymap")) { + } else if (!keyWord.CompareTo("copymap")) { - // Copy (& translate) the field map - this->defineFieldMapCopy(lineVect); + // Copy (& translate) the field map + this->defineFieldMapCopy(lineVect); - } else if (!keyWord.CompareTo("composite")) { + } else if (!keyWord.CompareTo("composite")) { - // Define the composite field - this->defineComposite(lineVect); + // Define the composite field + this->defineComposite(lineVect); - } else if (!keyWord.CompareTo("global")) { + } else if (!keyWord.CompareTo("global")) { - // Define which fields are global - this->defineGlobalField(lineVect); + // Define which fields are global + this->defineGlobalField(lineVect); - } else if (!keyWord.CompareTo("region")) { + } else if (!keyWord.CompareTo("region")) { - // Define the local and global fields for the given volume - this->defineRegionField(lineVect); + // Define the local and global fields for the given volume + this->defineRegionField(lineVect); - } else if (!keyWord.CompareTo("local")) { - - // Define the field for the given volume as the local one only - this->defineLocalField(lineVect); - - } - - } - - } + } else if (!keyWord.CompareTo("local")) { + // Define the field for the given volume as the local one only + this->defineLocalField(lineVect); + } + } + } } getData.close(); - } void ShipFieldMaker::defineUniform(const stringVect& inputLine) @@ -201,22 +200,20 @@ void ShipFieldMaker::defineUniform(const stringVect& inputLine) if (nWords == 5) { - const TString name(inputLine[1].c_str()); + const TString name(inputLine[1].c_str()); - Double_t Bx = std::atof(inputLine[2].c_str()); - Double_t By = std::atof(inputLine[3].c_str()); - Double_t Bz = std::atof(inputLine[4].c_str()); - const TVector3 BVector(Bx, By, Bz); + Double_t Bx = std::atof(inputLine[2].c_str()); + Double_t By = std::atof(inputLine[3].c_str()); + Double_t Bz = std::atof(inputLine[4].c_str()); + const TVector3 BVector(Bx, By, Bz); - this->defineUniform(name, BVector); + this->defineUniform(name, BVector); } else { - std::cout<<"Expecting 5 words for the definition of the uniform field: " - <<"Uniform Name Bx By Bz"<gotField(name)) { - if (verbose_) {std::cout<<"Creating uniform field for "<defineConstant(name, xRange, yRange, zRange, BVector); + this->defineConstant(name, xRange, yRange, zRange, BVector); } else { - std::cout<<"Expecting 11 words for the definition of the constant field: " - <<"Constant Name xMin xMax yMin yMax zMin zMax Bx By Bz"<gotField(name)) { - Double_t xMin = xRange.X(); - Double_t xMax = xRange.Y(); - Double_t yMin = yRange.X(); - Double_t yMax = yRange.Y(); - Double_t zMin = zRange.X(); - Double_t zMax = zRange.Y(); + Double_t xMin = xRange.X(); + Double_t xMax = xRange.Y(); + Double_t yMin = yRange.X(); + Double_t yMax = yRange.Y(); + Double_t zMin = zRange.X(); + Double_t zMax = zRange.Y(); - Double_t Bx = BVector.X()*Tesla_; - Double_t By = BVector.Y()*Tesla_; - Double_t Bz = BVector.Z()*Tesla_; + Double_t Bx = BVector.X() * Tesla_; + Double_t By = BVector.Y() * Tesla_; + Double_t Bz = BVector.Z() * Tesla_; - ShipConstField* theField = new ShipConstField(name.Data(), xMin, xMax, yMin, yMax, - zMin, zMax, Bx, By, Bz); - theFields_[name] = theField; + ShipConstField* theField = new ShipConstField(name.Data(), xMin, xMax, yMin, yMax, zMin, zMax, Bx, By, Bz); + theFields_[name] = theField; - } else { + } else { - if (verbose_) { - std::cout<<"We already have a constant field with the name " - <defineBell(name, BPeak, zMiddle, orient, tubeR, xy, z, L); + this->defineBell(name, BPeak, zMiddle, orient, tubeR, xy, z, L); } else { - std::cout<<"Expecting 6 or 9 words for the definition of the Bell field: " - <<"Bell Name BPeak zMiddle orientationInt tubeRadius [targetXY targetZ0 targetL]"<gotField(name)) { - ShipBellField* theField = new ShipBellField(name.Data(), BPeak*Tesla_, zMiddle, orient, tubeR); + ShipBellField* theField = new ShipBellField(name.Data(), BPeak * Tesla_, zMiddle, orient, tubeR); - // Set additional parameters if we have a non-zero target length - if (fabs(L) > 0.0) { - theField->IncludeTarget(xy, z, L); - } + // Set additional parameters if we have a non-zero target length + if (fabs(L) > 0.0) { + theField->IncludeTarget(xy, z, L); + } - theFields_[name] = theField; + theFields_[name] = theField; } else { - if (verbose_) { - std::cout<<"We already have a Bell field with the name " - < 5) { - x0 = std::atof(inputLine[3].c_str()); - y0 = std::atof(inputLine[4].c_str()); - z0 = std::atof(inputLine[5].c_str()); - } + if (nWords > 5) { + x0 = std::atof(inputLine[3].c_str()); + y0 = std::atof(inputLine[4].c_str()); + z0 = std::atof(inputLine[5].c_str()); + } - if (nWords == 9) { - phi = std::atof(inputLine[6].c_str()); - theta = std::atof(inputLine[7].c_str()); - psi = std::atof(inputLine[8].c_str()); - } + if (nWords == 9) { + phi = std::atof(inputLine[6].c_str()); + theta = std::atof(inputLine[7].c_str()); + psi = std::atof(inputLine[8].c_str()); + } - const TVector3 localCentre(x0, y0, z0); - const TVector3 localAngles(phi, theta, psi); + const TVector3 localCentre(x0, y0, z0); + const TVector3 localAngles(phi, theta, psi); - this->defineFieldMap(name, mapFileName, localCentre, localAngles, useSymmetry); + this->defineFieldMap(name, mapFileName, localCentre, localAngles, useSymmetry); } else { - std::cout<<"Expecting 3, 6 or 9 words for the definition of the field map: " - <<"(Sym)FieldMap Name mapFileName [x0 y0 z0] [[phi theta psi]]"<gotField(name)) { - // Add the VMCWORKDIR prefix to this map file location - std::string fullFileName = getenv("VMCWORKDIR"); - fullFileName += "/"; fullFileName += mapFileName.Data(); - - if (verbose_) { - if (useSymmetry) { - std::cout<<"Creating symmetric field map called "<defineFieldMapCopy(name, mapNameToCopy, translation, eulerAngles); + this->defineFieldMapCopy(name, mapNameToCopy, translation, eulerAngles); } else { - std::cout<<"Expecting 6 or 9 words for the copy of a field map: " - <<"CopyMap Name MapNameToCopy x0 y0 z0 [phi theta psi]"<gotField(name)) { - ShipBFieldMap* fieldToCopy = - dynamic_cast(this->getField(mapNameToCopy)); + ShipBFieldMap* fieldToCopy = dynamic_cast(this->getField(mapNameToCopy)); - if (fieldToCopy) { + if (fieldToCopy) { - if (verbose_) { - std::cout<<"Creating map field copy "< 2) { - TString name(inputLine[1].c_str()); - - std::vector fieldNames; - for (size_t i = 2; i < nWords; i++) { + TString name(inputLine[1].c_str()); - TString aName(inputLine[i].c_str()); - fieldNames.push_back(aName); + std::vector fieldNames; + for (size_t i = 2; i < nWords; i++) { - } + TString aName(inputLine[i].c_str()); + fieldNames.push_back(aName); + } - this->defineComposite(name, fieldNames); + this->defineComposite(name, fieldNames); } else { - std::cout<<"Expecting at least 3 words for the composite definition: " - <<"Composite Name Field1 Field2 ... FieldN"< fieldNames; @@ -595,14 +586,13 @@ void ShipFieldMaker::defineComposite(const TString& name, const TString& field1N fieldNames.push_back(field2Name); if (field3Name.Length() > 0) { - fieldNames.push_back(field3Name); + fieldNames.push_back(field3Name); } if (field4Name.Length() > 0) { - fieldNames.push_back(field4Name); + fieldNames.push_back(field4Name); } this->defineComposite(name, fieldNames); - } void ShipFieldMaker::defineComposite(const TString& name, std::vector fieldNames) @@ -611,30 +601,29 @@ void ShipFieldMaker::defineComposite(const TString& name, std::vector f // Check if the field is already in the map if (!this->gotField(name)) { - // Loop over the list of fields and add them to the composite - std::vector vectFields; - - std::vector::iterator iter; - for (iter = fieldNames.begin(); iter != fieldNames.end(); ++iter) { + // Loop over the list of fields and add them to the composite + std::vector vectFields; - TString aName = *iter; - TVirtualMagField* aField = this->getField(aName); - if (aField) { - if (verbose_) {std::cout<<"Adding field "<::iterator iter; + for (iter = fieldNames.begin(); iter != fieldNames.end(); ++iter) { - ShipCompField* composite = new ShipCompField(name.Data(), vectFields); - theFields_[name] = composite; + TString aName = *iter; + TVirtualMagField* aField = this->getField(aName); + if (aField) { + if (verbose_) { + std::cout << "Adding field " << aName << std::endl; + } + vectFields.push_back(aField); + } - } + ShipCompField* composite = new ShipCompField(name.Data(), vectFields); + theFields_[name] = composite; + } } else { - std::cout<<"We already have a composite field with the name " - < 1) { - TString name("Global"); + TString name("Global"); - std::vector fieldNames; - for (size_t i = 1; i < nWords; i++) { + std::vector fieldNames; + for (size_t i = 1; i < nWords; i++) { - TString aName(inputLine[i].c_str()); - fieldNames.push_back(aName); - - } + TString aName(inputLine[i].c_str()); + fieldNames.push_back(aName); + } - this->defineGlobalField(fieldNames); + this->defineGlobalField(fieldNames); } else { - std::cout<<"Expecting at least two words for the global field definition: " - <<"Global Field1 ... FieldN"< fieldNames; fieldNames.push_back(field1Name); if (field2Name.Length() > 0) { - fieldNames.push_back(field2Name); + fieldNames.push_back(field2Name); } if (field3Name.Length() > 0) { - fieldNames.push_back(field3Name); + fieldNames.push_back(field3Name); } if (field4Name.Length() > 0) { - fieldNames.push_back(field4Name); + fieldNames.push_back(field4Name); } this->defineGlobalField(fieldNames); - } void ShipFieldMaker::defineGlobalField(std::vector fieldNames) { if (globalField_) { - if (verbose_) { - std::cout<<"Deleting already existing Global field"< vectFields; std::vector::iterator iter; for (iter = fieldNames.begin(); iter != fieldNames.end(); ++iter) { - TString aName = *iter; - TVirtualMagField* aField = this->getField(aName); - - if (aField) { - if (verbose_) {std::cout<<"Adding field "<getField(aName); + if (aField) { + if (verbose_) { + std::cout << "Adding field " << aName << " to Global" << std::endl; + } + vectFields.push_back(aField); + } else { + std::cout << "Could not find the field " << aName << std::endl; + } } TString name("Global"); @@ -725,11 +715,12 @@ void ShipFieldMaker::defineGlobalField(std::vector fieldNames) // Set this as the global field in the virtual MC if (gMC) { - gMC->SetMagField(globalField_); + gMC->SetMagField(globalField_); } else { - std::cout<<"The virtual MC pointer gMC is null! The global field can't be used by Geant4 but will work for track fitting and track extrapolation"<defineRegionField(volName, fieldName, scale); + this->defineRegionField(volName, fieldName, scale); } else { - std::cout<<"Expecting 3 or 4 words for the region (local + global) field definition: " - <<"Region VolName LocalFieldName [LocalFieldMapScale]"<getField(lgName); + if (theVol) { - if (!lgField) { + // Find the local field + TVirtualMagField* localField = this->getField(fieldName); - // Create the combined local + global field and store in the internal map. - // Other volumes that use the same combined field will use the stored pointer - if (verbose_) { - std::cout<<"Creating the combined field "<SetField(combField); + // Check local field maps know about their associated volume position and orientation. + // This will update the localField pointer if required + this->checkLocalFieldMap(localField, volName, scale); - } else { + // Reset the fieldName to use the name from the localField pointer, since this + // could have changed for a local field map, for example + fieldName = localField->GetName(); - if (verbose_) { - std::cout<<"Setting the field "<SetField(lgField); + // See if we have already combined this local field with the global field + if (globalField_ && fieldName.Length() > 0) { - } + TString lgName(fieldName); + lgName += "Global"; + TVirtualMagField* lgField = this->getField(lgName); - } else { + if (!lgField) { - if (verbose_) { - std::cout<<"There is no global field defined. Just setting the local field"<SetField(localField); + // Create the combined local + global field and store in the internal map. + // Other volumes that use the same combined field will use the stored pointer + if (verbose_) { + std::cout << "Creating the combined field " << lgName.Data() << ", with local field " + << fieldName.Data() << " with the global field for volume " << volName.Data() + << std::endl; + } - } + ShipCompField* combField = new ShipCompField(lgName.Data(), localField, globalField_); + theFields_[lgName] = combField; + theVol->SetField(combField); - } else { + } else { - std::cout<<"Could not find the local field "<SetField(lgField); + } - } + } else { + if (verbose_) { + std::cout << "There is no global field defined. Just setting the local field" << std::endl; + } + theVol->SetField(localField); + } - } else { + } else { - std::cout<<"Could not find the volume "<defineLocalField(volName, fieldName, scale); + this->defineLocalField(volName, fieldName, scale); } else { - std::cout<<"Expecting 3 or 4 words for the local field definition: " - <<"Local VolName LocalFieldName [FieldMapScale]"<GetName() - <<" for volume "<checkLocalFieldMap(localField, volName, scale); + theVol->SetField(localField); - } else { + if (verbose_) { + std::cout << "Setting local field " << localField->GetName() << " for volume " << volName + << std::endl; + } - std::cout<<"Could not find the field "<(localField); if (mapField) { - TString fieldName(mapField->GetName()); - TString localName(fieldName); localName += volName; - - if (verbose_) { - std::cout<<"Checking local field map "<(this->getField(localName)); - - if (!localMap && volName.Length() > 0) { - - // Get the volume and its associate global transformation - TString volName1(volName); volName1 += "_1"; - - transformInfo theInfo; - this->getTransformation(volName1, theInfo); - - // The original field map may have defined its own translation and rotation. - // Apply this before the volume global transformation - Double_t origX0 = mapField->GetXOffset(); - Double_t origY0 = mapField->GetYOffset(); - Double_t origZ0 = mapField->GetZOffset(); - TGeoTranslation origTrans("origTrans", origX0, origY0, origZ0); - - Double_t origPhi = mapField->GetPhi(); - Double_t origTheta = mapField->GetTheta(); - Double_t origPsi = mapField->GetPsi(); - TGeoRotation origRot("origRot", origPhi, origTheta, origPsi); - - TGeoCombiTrans origComb(origTrans, origRot); - if (verbose_) { - std::cout<<"The original field map transformation:"<GetAngles(theInfo.phi_, theInfo.theta_, theInfo.psi_); - } - - // Create a lightweight copy, reusing the map data but just updating - // the global transformation - if (verbose_) { - std::cout<<"Creating field map copy for "<GetName() - <<": x0 = "<(this->getField(localName)); + + if (!localMap && volName.Length() > 0) { + + // Get the volume and its associate global transformation + TString volName1(volName); + volName1 += "_1"; + + transformInfo theInfo; + this->getTransformation(volName1, theInfo); + + // The original field map may have defined its own translation and rotation. + // Apply this before the volume global transformation + Double_t origX0 = mapField->GetXOffset(); + Double_t origY0 = mapField->GetYOffset(); + Double_t origZ0 = mapField->GetZOffset(); + TGeoTranslation origTrans("origTrans", origX0, origY0, origZ0); + + Double_t origPhi = mapField->GetPhi(); + Double_t origTheta = mapField->GetTheta(); + Double_t origPsi = mapField->GetPsi(); + TGeoRotation origRot("origRot", origPhi, origTheta, origPsi); + + TGeoCombiTrans origComb(origTrans, origRot); + if (verbose_) { + std::cout << "The original field map transformation:" << std::endl; + origComb.Print(); + } + + TGeoTranslation newTrans("newTrans", theInfo.x0_, theInfo.y0_, theInfo.z0_); + TGeoRotation newRot("newRot", theInfo.phi_, theInfo.theta_, theInfo.psi_); + + TGeoCombiTrans newComb(newTrans, newRot); + + if (verbose_) { + std::cout << "The volume transformation:" << std::endl; + newComb.Print(); + } + + // The full transformation + newComb = newComb * origComb; + + if (verbose_) { + std::cout << "The combined transformation:" << std::endl; + newComb.Print(); + } + + // Update transformation info + const Double_t* newTransArray = newComb.GetTranslation(); + theInfo.x0_ = newTransArray[0]; + theInfo.y0_ = newTransArray[1]; + theInfo.z0_ = newTransArray[2]; + + const TGeoRotation* fullRot = newComb.GetRotation(); + if (fullRot) { + fullRot->GetAngles(theInfo.phi_, theInfo.theta_, theInfo.psi_); + } + + // Create a lightweight copy, reusing the map data but just updating + // the global transformation + if (verbose_) { + std::cout << "Creating field map copy for " << localName << " based on " << mapField->GetName() + << ": x0 = " << theInfo.x0_ << ", y0 = " << theInfo.y0_ << ", z0 = " << theInfo.z0_ + << ", phi = " << theInfo.phi_ << ", theta = " << theInfo.theta_ << ", psi = " << theInfo.psi_ + << ", scale = " << scale << " and symmetry = " << mapField->HasSymmetry() << std::endl; + } + + localMap = new ShipBFieldMap(localName.Data(), + *mapField, + theInfo.x0_, + theInfo.y0_, + theInfo.z0_, + theInfo.phi_, + theInfo.theta_, + theInfo.psi_, + scale); + // Keep track that we have created this field pointer + theFields_[localName] = localMap; + } + + // Set the localField pointer to use the (new or already existing) localMap pointer + localField = localMap; + } } -void ShipFieldMaker::getTransformation(const TString& volName, transformInfo& theInfo) { +void ShipFieldMaker::getTransformation(const TString& volName, transformInfo& theInfo) +{ // Find the geometry node that matches the volume name. We need to search // the geometry hierarchy recursively until we get a match. Note that nodes // have "_1" appended to the volume name. - theInfo.x0_ = 0.0; theInfo.y0_ = 0.0; theInfo.z0_ = 0.0; - theInfo.phi_ = 0.0; theInfo.theta_ = 0.0; theInfo.psi_ = 0.0; + theInfo.x0_ = 0.0; + theInfo.y0_ = 0.0; + theInfo.z0_ = 0.0; + theInfo.phi_ = 0.0; + theInfo.theta_ = 0.0; + theInfo.psi_ = 0.0; TGeoMatrix* theMatrix(0); TGeoVolume* topVolume = gGeoManager->GetTopVolume(); if (!topVolume) { - std::cout<<"Can't find the top volume in ShipFieldMaker::getTransformation"<findNode(topVolume, volName); - if (theNode_) {theMatrix = theNode_->GetMatrix();} + if (theNode_) { + theMatrix = theNode_->GetMatrix(); + } // Retrieve the translation and rotation information if (theMatrix) { - // Translation displacement components - const Double_t* theTrans = theMatrix->GetTranslation(); - theInfo.x0_ = theTrans[0]; - theInfo.y0_ = theTrans[1]; - theInfo.z0_ = theTrans[2]; - - // Euler rotation angles. First check if we have a combined translation - // and rotation, then check if we just have a pure rotation - if (theMatrix->IsCombi()) { - - TGeoCombiTrans* theCombi = dynamic_cast(theMatrix); - if (theCombi) { - TGeoRotation* combRotn = theCombi->GetRotation(); - if (combRotn) { - combRotn->GetAngles(theInfo.phi_, theInfo.theta_, theInfo.psi_); - } - } - - } else if (theMatrix->IsRotation()) { - - TGeoRotation* theRotn = dynamic_cast(theMatrix); - if (theRotn) { - theRotn->GetAngles(theInfo.phi_, theInfo.theta_, theInfo.psi_); - } - } - } + // Translation displacement components + const Double_t* theTrans = theMatrix->GetTranslation(); + theInfo.x0_ = theTrans[0]; + theInfo.y0_ = theTrans[1]; + theInfo.z0_ = theTrans[2]; + + // Euler rotation angles. First check if we have a combined translation + // and rotation, then check if we just have a pure rotation + if (theMatrix->IsCombi()) { + + TGeoCombiTrans* theCombi = dynamic_cast(theMatrix); + if (theCombi) { + TGeoRotation* combRotn = theCombi->GetRotation(); + if (combRotn) { + combRotn->GetAngles(theInfo.phi_, theInfo.theta_, theInfo.psi_); + } + } + + } else if (theMatrix->IsRotation()) { + TGeoRotation* theRotn = dynamic_cast(theMatrix); + if (theRotn) { + theRotn->GetAngles(theInfo.phi_, theInfo.theta_, theInfo.psi_); + } + } + } } -void ShipFieldMaker::findNode(TGeoVolume* aVolume, const TString& volName) { +void ShipFieldMaker::findNode(TGeoVolume* aVolume, const TString& volName) +{ // Find the geometry node that matches the required volume name // Immediately exit the function if we have already found the volume - if (gotNode_) {return;} + if (gotNode_) { + return; + } if (aVolume) { - TObjArray* volNodes = aVolume->GetNodes(); - - if (volNodes) { - - // Loop over the geometry nodes - int nNodes = volNodes->GetEntries(); - for (int i = 0; i < nNodes; i++) { - - TGeoNode* node = dynamic_cast(volNodes->At(i)); + TObjArray* volNodes = aVolume->GetNodes(); - if (node) { + if (volNodes) { - const TString nodeName(node->GetName()); - if (!nodeName.CompareTo(volName, TString::kExact)) { + // Loop over the geometry nodes + int nNodes = volNodes->GetEntries(); + for (int i = 0; i < nNodes; i++) { - // We have a match. The node has the transformation we need - theNode_ = node; - gotNode_ = kTRUE; - break; + TGeoNode* node = dynamic_cast(volNodes->At(i)); - } else if (node->GetNodes()) { + if (node) { - // We have sub-volumes. Recursively call this function - this->findNode(node->GetVolume(), volName); + const TString nodeName(node->GetName()); + if (!nodeName.CompareTo(volName, TString::kExact)) { - } + // We have a match. The node has the transformation we need + theNode_ = node; + gotNode_ = kTRUE; + break; - } - - } - - } + } else if (node->GetNodes()) { + // We have sub-volumes. Recursively call this function + this->findNode(node->GetVolume(), volName); + } + } + } + } } - } TVirtualMagField* ShipFieldMaker::getVolumeField(const TString& volName) const @@ -1163,15 +1155,16 @@ TVirtualMagField* ShipFieldMaker::getVolumeField(const TString& volName) const TVirtualMagField* theField(0); TGeoVolume* theVol(0); - if (gGeoManager) {theVol = gGeoManager->FindVolumeFast(volName.Data());} + if (gGeoManager) { + theVol = gGeoManager->FindVolumeFast(volName.Data()); + } if (theVol) { - // Need to cast the TObject* to a TVirtualMagField* - theField = dynamic_cast(theVol->GetField()); + // Need to cast the TObject* to a TVirtualMagField* + theField = dynamic_cast(theVol->GetField()); } return theField; - } Bool_t ShipFieldMaker::gotField(const TString& name) const @@ -1183,19 +1176,17 @@ Bool_t ShipFieldMaker::gotField(const TString& name) const SFMap::const_iterator iter; for (iter = theFields_.begin(); iter != theFields_.end(); ++iter) { - TString key = iter->first; - TVirtualMagField* theField = iter->second; - - // Check that we have the key already stored and the pointer is not null - if (!key.CompareTo(name, TString::kExact) && theField) { - result = kTRUE; - break; - } + TString key = iter->first; + TVirtualMagField* theField = iter->second; + // Check that we have the key already stored and the pointer is not null + if (!key.CompareTo(name, TString::kExact) && theField) { + result = kTRUE; + break; + } } return result; - } TVirtualMagField* ShipFieldMaker::getField(const TString& name) const @@ -1207,156 +1198,159 @@ TVirtualMagField* ShipFieldMaker::getField(const TString& name) const SFMap::const_iterator iter; for (iter = theFields_.begin(); iter != theFields_.end(); ++iter) { - TString key = iter->first; - TVirtualMagField* BField = iter->second; - - // Check that we have the key already stored - if (!key.CompareTo(name, TString::kExact)) { - theField = BField; - break; - } + TString key = iter->first; + TVirtualMagField* BField = iter->second; + // Check that we have the key already stored + if (!key.CompareTo(name, TString::kExact)) { + theField = BField; + break; + } } return theField; - } -void ShipFieldMaker::plotXYField(const TVector3& xAxis, const TVector3& yAxis, - const std::string& plotFile) const +void ShipFieldMaker::plotXYField(const TVector3& xAxis, const TVector3& yAxis, const std::string& plotFile) const { this->plotField(0, xAxis, yAxis, plotFile); } -void ShipFieldMaker::plotZXField(const TVector3& zAxis, const TVector3& xAxis, - const std::string& plotFile) const +void ShipFieldMaker::plotZXField(const TVector3& zAxis, const TVector3& xAxis, const std::string& plotFile) const { this->plotField(1, zAxis, xAxis, plotFile); } -void ShipFieldMaker::plotZYField(const TVector3& zAxis, const TVector3& yAxis, - const std::string& plotFile) const +void ShipFieldMaker::plotZYField(const TVector3& zAxis, const TVector3& yAxis, const std::string& plotFile) const { this->plotField(2, zAxis, yAxis, plotFile); } -void ShipFieldMaker::plotField(Int_t type, const TVector3& xAxis, const TVector3& yAxis, - const std::string& plotFile) const +void ShipFieldMaker::plotField(Int_t type, + const TVector3& xAxis, + const TVector3& yAxis, + const std::string& plotFile) const { - std::cout<<"ShipFieldMaker plotField "<GetListOfVolumes(); Int_t nVol(0); - if (theVolumes) {nVol = theVolumes->GetSize();} + if (theVolumes) { + nVol = theVolumes->GetSize(); + } // Loop over "x" axis for (Int_t ix = 0; ix < Nx; ix++) { - Double_t x = dx*ix + xMin; + Double_t x = dx * ix + xMin; - // Loop over "y" axis - for (Int_t iy = 0; iy < Ny; iy++) { + // Loop over "y" axis + for (Int_t iy = 0; iy < Ny; iy++) { - Double_t y = dy*iy + yMin; + Double_t y = dy * iy + yMin; - // Initialise the B field array to zero - Double_t B[ncoordinates] = {0.0, 0.0, 0.0}; + // Initialise the B field array to zero + Double_t B[ncoordinates] = {0.0, 0.0, 0.0}; - // Initialise the position array to zero - Double_t position[ncoordinates] = {0.0, 0.0, 0.0}; - if (type == 0) { - // x-y - position[0] = x, position[1] = y; - } else if (type == 1) { - // z-x - position[0] = y, position[2] = x; - } else if (type == 2) { - // z-y - position[1] = y; position[2] = x; - } + // Initialise the position array to zero + Double_t position[ncoordinates] = {0.0, 0.0, 0.0}; + if (type == 0) { + // x-y + position[0] = x, position[1] = y; + } else if (type == 1) { + // z-x + position[0] = y, position[2] = x; + } else if (type == 2) { + // z-y + position[1] = y; + position[2] = x; + } - // Find out if the point is inside one of the geometry volumes - Bool_t inside(kFALSE); + // Find out if the point is inside one of the geometry volumes + Bool_t inside(kFALSE); - // Find the geoemtry node (volume path) - TGeoNode* theNode = gGeoManager->FindNode(position[0], position[1], position[2]); + // Find the geoemtry node (volume path) + TGeoNode* theNode = gGeoManager->FindNode(position[0], position[1], position[2]); - if (theNode) { + if (theNode) { - // Get the volume - TGeoVolume* theVol = theNode->GetVolume(); + // Get the volume + TGeoVolume* theVol = theNode->GetVolume(); - if (theVol) { + if (theVol) { - // Get the magnetic field - TVirtualMagField* theField = dynamic_cast(theVol->GetField()); + // Get the magnetic field + TVirtualMagField* theField = dynamic_cast(theVol->GetField()); - if (theField) { + if (theField) { - // Find the "local" field inside the volume (using global co-ords) - theField->Field(position, B); - inside = kTRUE; + // Find the "local" field inside the volume (using global co-ords) + theField->Field(position, B); + inside = kTRUE; - } // theField + } // theField - } // volume + } // volume - } // node + } // node - // If no local volumes found, use global field if it exists - if (inside == kFALSE && globalField_) { - globalField_->Field(position, B); - } + // If no local volumes found, use global field if it exists + if (inside == kFALSE && globalField_) { + globalField_->Field(position, B); + } - // Divide by the Tesla_ factor, since we want to plot Tesla_ not kGauss (VMC/FairRoot units) - for (int icomponent = 0; icomponentIsBatch(); // Disable pop-up windows @@ -1368,82 +1362,94 @@ void ShipFieldMaker::plotField(Int_t type, const TVector3& xAxis, const TVector3 gStyle->SetPalette(kBird); theCanvas.UseCurrentStyle(); - theCanvas.Divide(2,2); - for (int icomponent = 0; icomponent < nhistograms; icomponent++){ - theCanvas.cd(icomponent+1); - theHist[icomponent].Draw("colz"); - } + theCanvas.Divide(2, 2); + for (int icomponent = 0; icomponent < nhistograms; icomponent++) { + theCanvas.cd(icomponent + 1); + theHist[icomponent].Draw("colz"); + } theCanvas.Print(plotFile.c_str()); // Reset the batch boolean - if (wasBatch == kFALSE) {gROOT->SetBatch(kFALSE);} - + if (wasBatch == kFALSE) { + gROOT->SetBatch(kFALSE); + } } -void ShipFieldMaker::generateFieldMap(TString fileName, const float step, const float xRange, const float yRange, const float zRange, const float zShift){ - std::ofstream myfile; - myfile.open (fileName); - int xSteps = ceil(xRange/step) + 1; //field map has X range from 0 to xMax - int ySteps = ceil(yRange/step) + 1; //from 0 up to yMax - int zSteps = ceil(zRange*2./step) + 1;//from -zMax up to zMax - Double_t position[3] = {0.0, 0.0, 0.0}; - myfile<FindNode(position[0], position[1], position[2]); - if (theNode) { - TGeoVolume* theVol = theNode->GetVolume(); - if (theVol) { - TVirtualMagField* theField = dynamic_cast(theVol->GetField()); - if (theField) { - theField->Field(position, B); - inside = kTRUE; - } - } - } - if (inside == kFALSE && globalField_) { - globalField_->Field(position, B); - } - myfile<FindNode(position[0], position[1], position[2]); + if (theNode) { + TGeoVolume* theVol = theNode->GetVolume(); + if (theVol) { + TVirtualMagField* theField = dynamic_cast(theVol->GetField()); + if (theField) { + theField->Field(position, B); + inside = kTRUE; } + } + } + if (inside == kFALSE && globalField_) { + globalField_->Field(position, B); } + myfile << x << " " << y << " " << z << " " << B[0] / Tesla_ << " " << B[1] / Tesla_ + << " " << B[2] / Tesla_ << std::endl; + } } - myfile.close(); + } + myfile.close(); } -ShipFieldMaker::stringVect ShipFieldMaker::splitString(std::string& theString, - std::string& splitter) const { +ShipFieldMaker::stringVect ShipFieldMaker::splitString(std::string& theString, std::string& splitter) const +{ // Code from STLplus stringVect result; if (!theString.empty() && !splitter.empty()) { - for (std::string::size_type offset = 0;;) { + for (std::string::size_type offset = 0;;) { - std::string::size_type found = theString.find(splitter, offset); + std::string::size_type found = theString.find(splitter, offset); - if (found != std::string::npos) { - std::string tmpString = theString.substr(offset, found-offset); - if (tmpString.size() > 0) {result.push_back(tmpString);} - offset = found + splitter.size(); - } else { - std::string tmpString = theString.substr(offset, theString.size()-offset); - if (tmpString.size() > 0) {result.push_back(tmpString);} - break; - } - } + if (found != std::string::npos) { + std::string tmpString = theString.substr(offset, found - offset); + if (tmpString.size() > 0) { + result.push_back(tmpString); + } + offset = found + splitter.size(); + } else { + std::string tmpString = theString.substr(offset, theString.size() - offset); + if (tmpString.size() > 0) { + result.push_back(tmpString); + } + break; + } + } } return result; - } diff --git a/field/ShipFieldMaker.h b/field/ShipFieldMaker.h index 105fd24b93..73b42ca507 100644 --- a/field/ShipFieldMaker.h +++ b/field/ShipFieldMaker.h @@ -17,12 +17,11 @@ #define ShipFieldMaker_H #include "ShipCompField.h" - +#include "TG4VUserPostDetConstruction.h" #include "TString.h" -#include "TVirtualMagField.h" #include "TVector2.h" #include "TVector3.h" -#include "TG4VUserPostDetConstruction.h" +#include "TVirtualMagField.h" #include #include @@ -35,8 +34,7 @@ class TGeoVolume; class ShipFieldMaker : public TG4VUserPostDetConstruction { - public: - + public: //! Constructor ShipFieldMaker(Bool_t verbose = kFALSE); @@ -50,22 +48,27 @@ class ShipFieldMaker : public TG4VUserPostDetConstruction typedef std::vector stringVect; //! Structure to hold volume name, field name and field scaling factor - struct fieldInfo { - - //! The name of the volume - TString volName_; - //! The name of the field - TString fieldName_; - //! The field scaling factor - Double_t scale_; - - //! Default constructor - fieldInfo() : volName_(""), fieldName_(""), scale_(1.0) {}; - - //! Constructor - fieldInfo(const TString& volName, const TString& fieldName, Double_t scale = 1.0) : - volName_(volName), fieldName_(fieldName), scale_(scale) {}; - + struct fieldInfo + { + + //! The name of the volume + TString volName_; + //! The name of the field + TString fieldName_; + //! The field scaling factor + Double_t scale_; + + //! Default constructor + fieldInfo() + : volName_("") + , fieldName_("") + , scale_(1.0) {}; + + //! Constructor + fieldInfo(const TString& volName, const TString& fieldName, Double_t scale = 1.0) + : volName_(volName) + , fieldName_(fieldName) + , scale_(scale) {}; }; //! Set-up all local and regional fields and assign them to volumes @@ -92,8 +95,11 @@ class ShipFieldMaker : public TG4VUserPostDetConstruction \param [in] zRange The z range as a TVector2(zMin, zMax) \param [in] BVector The vector of B field components (Bx, By, Bz) in Tesla */ - void defineConstant(const TString& name, const TVector2& xRange, const TVector2& yRange, - const TVector2& zRange, const TVector3& BVector); + void defineConstant(const TString& name, + const TVector2& xRange, + const TVector2& yRange, + const TVector2& zRange, + const TVector3& BVector); //! Define a Bell field /*! @@ -106,9 +112,14 @@ class ShipFieldMaker : public TG4VUserPostDetConstruction \param [in] z Optional target start z global position (cm) \param [in] L Optional target region length (cm) */ - void defineBell(const TString& name, Double_t BPeak, Double_t zMiddle, - Int_t orient = 1, Double_t tubeR = 500.0, - Double_t xy = 0.0, Double_t z = 0.0, Double_t L = 0.0); + void defineBell(const TString& name, + Double_t BPeak, + Double_t zMiddle, + Int_t orient = 1, + Double_t tubeR = 500.0, + Double_t xy = 0.0, + Double_t z = 0.0, + Double_t L = 0.0); // ! Define a field map /*! @@ -118,10 +129,11 @@ class ShipFieldMaker : public TG4VUserPostDetConstruction \param [in] localAngles The TVector3(phi, theta, psi) Euler rotation applied to all map coords \param [in] useSymmetry Boolean to specify if the map has quadrant symmetry (default = false) */ - void defineFieldMap(const TString& name, const TString& mapFileName, - const TVector3& localCentre = TVector3(0.0, 0.0, 0.0), - const TVector3& localAngles = TVector3(0.0, 0.0, 0.0), - Bool_t useSymmetry = kFALSE); + void defineFieldMap(const TString& name, + const TString& mapFileName, + const TVector3& localCentre = TVector3(0.0, 0.0, 0.0), + const TVector3& localAngles = TVector3(0.0, 0.0, 0.0), + Bool_t useSymmetry = kFALSE); //! Define a copy of a field map with a coordinate translation and optional rotation /*! @@ -130,9 +142,10 @@ class ShipFieldMaker : public TG4VUserPostDetConstruction \param [in] translation The TVector3(x,y,z) coordinate translation \param [in] eulerAngles The TVector3(phi, theta, psi) Euler angle rotation */ - void defineFieldMapCopy(const TString& name, const TString& mapNameToCopy, - const TVector3& translation, - const TVector3& eulerAngles = TVector3(0.0, 0.0, 0.0)); + void defineFieldMapCopy(const TString& name, + const TString& mapNameToCopy, + const TVector3& translation, + const TVector3& eulerAngles = TVector3(0.0, 0.0, 0.0)); //! Define a composite field from up to four fields /*! @@ -142,9 +155,11 @@ class ShipFieldMaker : public TG4VUserPostDetConstruction \param [in] field3Name The name of the third field (optional) \param [in] field4Name The name of the fourth field (optional) */ - void defineComposite(const TString& name, const TString& field1Name, - const TString& field2Name, const TString& field3Name = "", - const TString& field4Name = ""); + void defineComposite(const TString& name, + const TString& field1Name, + const TString& field2Name, + const TString& field3Name = "", + const TString& field4Name = ""); //! Define a composite field from a vector of field names /*! @@ -160,8 +175,10 @@ class ShipFieldMaker : public TG4VUserPostDetConstruction \param [in] field3Name The name of the third field (optional) \param [in] field4Name The name of the fourth field (optional) */ - void defineGlobalField(const TString& field1Name, const TString& field2Name = "", - const TString& field3Name = "", const TString& field4Name = ""); + void defineGlobalField(const TString& field1Name, + const TString& field2Name = "", + const TString& field3Name = "", + const TString& field4Name = ""); //! Define the Global field using a vector of field names /*! @@ -175,8 +192,7 @@ class ShipFieldMaker : public TG4VUserPostDetConstruction \param [in] fieldName The name of the field for the volume \param [in] scale Optional scale factor for field maps (default = 1.0) */ - void defineRegionField(const TString& volName, const TString& fieldName, - Double_t scale = 1.0); + void defineRegionField(const TString& volName, const TString& fieldName, Double_t scale = 1.0); //! Define a localised field and volume pairing /*! @@ -184,21 +200,19 @@ class ShipFieldMaker : public TG4VUserPostDetConstruction \param [in] fieldName The name of the local field for the volume \param [in] scale Optional scale factor for field maps (default = 1.0) */ - void defineLocalField(const TString& volName, const TString& fieldName, - Double_t scale = 1.0); - + void defineLocalField(const TString& volName, const TString& fieldName, Double_t scale = 1.0); //! Get the global magnetic field /*! \returns the global magnetic field pointer */ - ShipCompField* getGlobalField() const {return globalField_;} + ShipCompField* getGlobalField() const { return globalField_; } //! Get the map storing volume names and their associated local magnetic fields /*! \returns the map of volume names and their corresponding magnetic field pointers */ - SFMap getAllFields() const {return theFields_;} + SFMap getAllFields() const { return theFields_; } //! Get the magnetic field for the given volume /*! @@ -252,35 +266,37 @@ class ShipFieldMaker : public TG4VUserPostDetConstruction \param [in] yAxis Three vector specifying the min, max and bin width of the y axis \param [in] plotFile The name of the output file containing the plot of the magnetic field */ - void plotField(Int_t type, const TVector3& xAxis, const TVector3& yAxis, - const std::string& plotFile) const; + void plotField(Int_t type, const TVector3& xAxis, const TVector3& yAxis, const std::string& plotFile) const; - void generateFieldMap(TString fileName, const float step=2.5, const float xRange=179, const float yRange=317, const float zRange=1515.5, const float zShift=-4996); + void generateFieldMap(TString fileName, + const float step = 2.5, + const float xRange = 179, + const float yRange = 317, + const float zRange = 1515.5, + const float zShift = -4996); //! Generate fieldMap csv file in the given region //! ClassDef for ROOT - ClassDef(ShipFieldMaker,1); - - - protected: + ClassDef(ShipFieldMaker, 1); + protected: //! Structure to hold transformation information - struct transformInfo { - - //! The x translation displacement - Double_t x0_; - //! The y translation displacement - Double_t y0_; - //! The z translation displacement - Double_t z0_; - - //! The first Euler rotation angle (about Z axis) - Double_t phi_; - //! The second Euler rotation angle (about new X' axis) - Double_t theta_; - //! The third Euler rotation angle (about new Z' axis) - Double_t psi_; - + struct transformInfo + { + + //! The x translation displacement + Double_t x0_; + //! The y translation displacement + Double_t y0_; + //! The z translation displacement + Double_t z0_; + + //! The first Euler rotation angle (about Z axis) + Double_t phi_; + //! The second Euler rotation angle (about new X' axis) + Double_t theta_; + //! The third Euler rotation angle (about new Z' axis) + Double_t psi_; }; //! Define a uniform field based on information from the inputLine @@ -314,13 +330,13 @@ class ShipFieldMaker : public TG4VUserPostDetConstruction */ void defineFieldMapCopy(const stringVect& inputLine); - //! Define a composite field based on information from the inputLine + //! Define a composite field based on information from the inputLine /*! \param [in] inputLine The space separated input line */ void defineComposite(const stringVect& inputLine); - //! Define the global field based on information from the inputLine + //! Define the global field based on information from the inputLine /*! \param [in] inputLine The space separated input line */ @@ -335,7 +351,6 @@ class ShipFieldMaker : public TG4VUserPostDetConstruction // ! Setup all of the regional fields. Called by Construct() void setAllRegionFields(); - //! Define a local field only based on information from the inputLine /*! \param [in] inputLine The space separated input line @@ -353,7 +368,6 @@ class ShipFieldMaker : public TG4VUserPostDetConstruction // ! Setup all of the local fields. Called by Construct() void setAllLocalFields(); - //! Get the transformation matrix for the volume position and orientation /*! \param [in] volName The name of the volume @@ -368,8 +382,7 @@ class ShipFieldMaker : public TG4VUserPostDetConstruction */ void findNode(TGeoVolume* aVolume, const TString& volName); - private: - + private: //! The global magnetic field ShipCompField* globalField_; @@ -401,7 +414,6 @@ class ShipFieldMaker : public TG4VUserPostDetConstruction \returns a vector of the delimiter-separated strings */ stringVect splitString(std::string& theString, std::string& splitter) const; - }; #endif diff --git a/field/ShipFieldPar.cxx b/field/ShipFieldPar.cxx index c97524c9df..a82f917531 100644 --- a/field/ShipFieldPar.cxx +++ b/field/ShipFieldPar.cxx @@ -1,183 +1,185 @@ #include "ShipFieldPar.h" -#include "ShipConstField.h" #include "FairParamList.h" +#include "ShipConstField.h" #include -using std::cout; using std::cerr; +using std::cout; using std::endl; const int kMaxLen = 2048; // ------ Constructor -------------------------------------------------- -ShipFieldPar::ShipFieldPar(const char* name, const char* title, - const char* context) - : FairParGenericSet(name, title, context), - fType(-1), - fXmin(0.), - fXmax(0.), - fYmin(0.), - fYmax(0.), - fZmin(0.), - fZmax(0.), - fBx(0.), - fBy(0.), - fBz(0.), - fMapName(""), - fPosX(0.), - fPosY(0.), - fPosZ(0.), - fScale(0.), - fPeak(0.), - fMiddle(0.) - -{ -} +ShipFieldPar::ShipFieldPar(const char* name, const char* title, const char* context) + : FairParGenericSet(name, title, context) + , fType(-1) + , fXmin(0.) + , fXmax(0.) + , fYmin(0.) + , fYmax(0.) + , fZmin(0.) + , fZmax(0.) + , fBx(0.) + , fBy(0.) + , fBz(0.) + , fMapName("") + , fPosX(0.) + , fPosY(0.) + , fPosZ(0.) + , fScale(0.) + , fPeak(0.) + , fMiddle(0.) + +{} // ------------------------------------------------------------------------- ShipFieldPar::ShipFieldPar() - : FairParGenericSet(), - fType(-1), - fXmin(0.), - fXmax(0.), - fYmin(0.), - fYmax(0.), - fZmin(0.), - fZmax(0.), - fBx(0.), - fBy(0.), - fBz(0.), - fMapName(""), - fPosX(0.), - fPosY(0.), - fPosZ(0.), - fScale(0.), - fPeak(0.), - fMiddle(0.) - -{ -} + : FairParGenericSet() + , fType(-1) + , fXmin(0.) + , fXmax(0.) + , fYmin(0.) + , fYmax(0.) + , fZmin(0.) + , fZmax(0.) + , fBx(0.) + , fBy(0.) + , fBz(0.) + , fMapName("") + , fPosX(0.) + , fPosY(0.) + , fPosZ(0.) + , fScale(0.) + , fPeak(0.) + , fMiddle(0.) + +{} // ------------------------------------------------------------------------- // ------ Destructor --------------------------------------------------- -ShipFieldPar::~ShipFieldPar() { } +ShipFieldPar::~ShipFieldPar() {} // ------------------------------------------------------------------------- - - // ------ Put parameters ----------------------------------------------- -void ShipFieldPar::putParams(FairParamList* list) { - - if ( ! list ) return; - - list->add("Field Type", fType); - - if ( fType == 0 ) { // constant field - list->add("Field min x", fXmin); - list->add("Field max x", fXmax); - list->add("Field min y", fYmin); - list->add("Field max y", fYmax); - list->add("Field min z", fZmin); - list->add("Field max z", fZmax); - list->add("Field Bx", fBx); - list->add("Field By", fBy); - list->add("Field Bz", fBz); - } else if (fType >=1 && fType <= kMaxFieldMapType) { // - list->add("Field Peak", fPeak); - list->add("Field Middle", fMiddle); - } else if (fType >=2 && fType <= kMaxFieldMapType) { // field map - list->add("Field map name", fMapName); - list->add("Field x position", fPosX); - list->add("Field y position", fPosY); - list->add("Field z position", fPosZ); - list->add("Field scaling factor", fScale); - - } +void ShipFieldPar::putParams(FairParamList* list) +{ + if (!list) + return; + + list->add("Field Type", fType); + + if (fType == 0) { // constant field + list->add("Field min x", fXmin); + list->add("Field max x", fXmax); + list->add("Field min y", fYmin); + list->add("Field max y", fYmax); + list->add("Field min z", fZmin); + list->add("Field max z", fZmax); + list->add("Field Bx", fBx); + list->add("Field By", fBy); + list->add("Field Bz", fBz); + } else if (fType >= 1 && fType <= kMaxFieldMapType) { // + list->add("Field Peak", fPeak); + list->add("Field Middle", fMiddle); + } else if (fType >= 2 && fType <= kMaxFieldMapType) { // field map + list->add("Field map name", fMapName); + list->add("Field x position", fPosX); + list->add("Field y position", fPosY); + list->add("Field z position", fPosZ); + list->add("Field scaling factor", fScale); + } } // ------------------------------------------------------------------------- - - // -------- Get parameters --------------------------------------------- -Bool_t ShipFieldPar::getParams(FairParamList* list) { - - if ( ! list ) return kFALSE; - - if ( ! list->fill("Field Type", &fType) ) return kFALSE; - - if ( fType == 0 ) { // constant field - if ( ! list->fill("Field min x", &fXmin) ) return kFALSE; - if ( ! list->fill("Field max x", &fXmax) ) return kFALSE; - if ( ! list->fill("Field min y", &fYmin) ) return kFALSE; - if ( ! list->fill("Field max y", &fYmax) ) return kFALSE; - if ( ! list->fill("Field min z", &fZmin) ) return kFALSE; - if ( ! list->fill("Field max z", &fZmax) ) return kFALSE; - if ( ! list->fill("Field Bx", &fBx) ) return kFALSE; - if ( ! list->fill("Field By", &fBy) ) return kFALSE; - if ( ! list->fill("Field Bz", &fBz) ) return kFALSE; - - } else if (fType >=1 && fType <= kMaxFieldMapType) { - - if ( ! list->fill("Field Peak", &fPeak) ) return kFALSE; - if ( ! list->fill("Field Middle", &fMiddle) ) return kFALSE; - - } else if (fType >=2 && fType <= kMaxFieldMapType) { // field map - Text_t mapName[80]; - if ( ! list->fill("Field map name", mapName, 80) ) return kFALSE; - fMapName = mapName; - if ( ! list->fill("Field x position", &fPosX) ) return kFALSE; - if ( ! list->fill("Field y position", &fPosY) ) return kFALSE; - if ( ! list->fill("Field z position", &fPosZ) ) return kFALSE; - if ( ! list->fill("Field scaling factor", &fScale) ) return kFALSE; - - } - - return kTRUE; +Bool_t ShipFieldPar::getParams(FairParamList* list) +{ + if (!list) + return kFALSE; + + if (!list->fill("Field Type", &fType)) + return kFALSE; + + if (fType == 0) { // constant field + if (!list->fill("Field min x", &fXmin)) + return kFALSE; + if (!list->fill("Field max x", &fXmax)) + return kFALSE; + if (!list->fill("Field min y", &fYmin)) + return kFALSE; + if (!list->fill("Field max y", &fYmax)) + return kFALSE; + if (!list->fill("Field min z", &fZmin)) + return kFALSE; + if (!list->fill("Field max z", &fZmax)) + return kFALSE; + if (!list->fill("Field Bx", &fBx)) + return kFALSE; + if (!list->fill("Field By", &fBy)) + return kFALSE; + if (!list->fill("Field Bz", &fBz)) + return kFALSE; + + } else if (fType >= 1 && fType <= kMaxFieldMapType) { + + if (!list->fill("Field Peak", &fPeak)) + return kFALSE; + if (!list->fill("Field Middle", &fMiddle)) + return kFALSE; + + } else if (fType >= 2 && fType <= kMaxFieldMapType) { // field map + Text_t mapName[80]; + if (!list->fill("Field map name", mapName, 80)) + return kFALSE; + fMapName = mapName; + if (!list->fill("Field x position", &fPosX)) + return kFALSE; + if (!list->fill("Field y position", &fPosY)) + return kFALSE; + if (!list->fill("Field z position", &fPosZ)) + return kFALSE; + if (!list->fill("Field scaling factor", &fScale)) + return kFALSE; + } + + return kTRUE; } // ------------------------------------------------------------------------- +void ShipFieldPar::SetParameters(FairField* field) +{ + if (!field) { + cerr << "-W- ShipFieldPar::SetParameters: Empty field pointer!" << endl; + return; + } + + fType = field->GetType(); + + if (fType == 0) { // constant field + ShipConstField* fieldConst = (ShipConstField*)field; + fBx = fieldConst->GetBx(); + fBy = fieldConst->GetBy(); + fBz = fieldConst->GetBz(); + fXmin = fieldConst->GetXmin(); + fXmax = fieldConst->GetXmax(); + fYmin = fieldConst->GetYmin(); + fYmax = fieldConst->GetYmax(); + fZmin = fieldConst->GetZmin(); + fZmax = fieldConst->GetZmax(); + fMapName = ""; + fPosX = fPosY = fPosZ = fScale = 0.; + } else { + cerr << "-W- ShipFieldPar::SetParameters: Unknown field type " << fType << "!" << endl; + fBx = fBy = fBz = 0.; + fXmin = fXmax = fYmin = fYmax = fZmin = fZmax = 0.; + fMapName = ""; + fPosX = fPosY = fPosZ = fScale = 0.; + } -void ShipFieldPar::SetParameters(FairField* field) { - - if ( ! field ) { - cerr << "-W- ShipFieldPar::SetParameters: Empty field pointer!" << endl; return; - } - - fType = field->GetType(); - - if ( fType == 0 ) { // constant field - ShipConstField* fieldConst = (ShipConstField*) field; - fBx = fieldConst->GetBx(); - fBy = fieldConst->GetBy(); - fBz = fieldConst->GetBz(); - fXmin = fieldConst->GetXmin(); - fXmax = fieldConst->GetXmax(); - fYmin = fieldConst->GetYmin(); - fYmax = fieldConst->GetYmax(); - fZmin = fieldConst->GetZmin(); - fZmax = fieldConst->GetZmax(); - fMapName = ""; - fPosX = fPosY = fPosZ = fScale = 0.; - } else { - cerr << "-W- ShipFieldPar::SetParameters: Unknown field type " - << fType << "!" << endl; - fBx = fBy = fBz = 0.; - fXmin = fXmax = fYmin = fYmax = fZmin = fZmax = 0.; - fMapName = ""; - fPosX = fPosY = fPosZ = fScale = 0.; - } - - return; - } // ------------------------------------------------------------------------- - - - - - diff --git a/field/ShipFieldPar.h b/field/ShipFieldPar.h index 995925905e..29cfb18dad 100644 --- a/field/ShipFieldPar.h +++ b/field/ShipFieldPar.h @@ -11,97 +11,81 @@ const int kMaxFieldMapType = 5; class ShipFieldPar : public FairParGenericSet { - public: - - - /** Standard constructor **/ - ShipFieldPar(const char* name, const char* title, const char* context); - -/** default constructor **/ - ShipFieldPar(); - - /** Destructor **/ - ~ShipFieldPar(); - - - /** Put parameters **/ - virtual void putParams(FairParamList* list); - - - /** Get parameters **/ - virtual Bool_t getParams(FairParamList* list); - - - /** Set parameters from CbmField **/ - void SetParameters(FairField* field); - - - /** Accessors **/ - Int_t GetType() const { return fType; } - Double_t GetXmin() const { return fXmin; } - Double_t GetXmax() const { return fXmax; } - Double_t GetYmin() const { return fYmin; } - Double_t GetYmax() const { return fYmax; } - Double_t GetZmin() const { return fZmin; } - Double_t GetZmax() const { return fZmax; } - Double_t GetBx() const { return fBx; } - Double_t GetBy() const { return fBy; } - Double_t GetBz() const { return fBz; } - void MapName(TString& name) { name = fMapName; } - Double_t GetPositionX() const { return fPosX; } - Double_t GetPositionY() const { return fPosY; } - Double_t GetPositionZ() const { return fPosZ; } - Double_t GetScale() const { return fScale; } - Double_t GetPeak() const { return fPeak; } - Double_t GetMiddle() const { return fMiddle; } - Double_t GetBtube() const { return fBtube; } - - - private: - - /** Field type - ** 0 = constant field - ** 1 = field map - ** 2 = field map sym2 (symmetries in x and y) - ** 3 = field map sym3 (symmetries in x, y and z) - ** kTypeDistorted = distorted field map (its parent field can be field map or constant field) - **/ - Int_t fType; - - - /** Field limits in case of constant field **/ - Double_t fXmin, fXmax; - Double_t fYmin, fYmax; - Double_t fZmin, fZmax; - - - /** Field values in case of constant field [kG] **/ - Double_t fBx, fBy, fBz; - - - /** Field map name in case of field map **/ - TString fMapName; - - - /** Field centre position for field map **/ - Double_t fPosX, fPosY, fPosZ; - - - /** Scaling factor for field map **/ - Double_t fScale; - - /** field parameters**/ - Double_t fPeak; - Double_t fMiddle; - Double_t fBtube; - - - ShipFieldPar(const ShipFieldPar&); - ShipFieldPar& operator=(const ShipFieldPar&); - - ClassDef(ShipFieldPar,1); - + public: + /** Standard constructor **/ + ShipFieldPar(const char* name, const char* title, const char* context); + + /** default constructor **/ + ShipFieldPar(); + + /** Destructor **/ + ~ShipFieldPar(); + + /** Put parameters **/ + virtual void putParams(FairParamList* list); + + /** Get parameters **/ + virtual Bool_t getParams(FairParamList* list); + + /** Set parameters from CbmField **/ + void SetParameters(FairField* field); + + /** Accessors **/ + Int_t GetType() const { return fType; } + Double_t GetXmin() const { return fXmin; } + Double_t GetXmax() const { return fXmax; } + Double_t GetYmin() const { return fYmin; } + Double_t GetYmax() const { return fYmax; } + Double_t GetZmin() const { return fZmin; } + Double_t GetZmax() const { return fZmax; } + Double_t GetBx() const { return fBx; } + Double_t GetBy() const { return fBy; } + Double_t GetBz() const { return fBz; } + void MapName(TString& name) { name = fMapName; } + Double_t GetPositionX() const { return fPosX; } + Double_t GetPositionY() const { return fPosY; } + Double_t GetPositionZ() const { return fPosZ; } + Double_t GetScale() const { return fScale; } + Double_t GetPeak() const { return fPeak; } + Double_t GetMiddle() const { return fMiddle; } + Double_t GetBtube() const { return fBtube; } + + private: + /** Field type + ** 0 = constant field + ** 1 = field map + ** 2 = field map sym2 (symmetries in x and y) + ** 3 = field map sym3 (symmetries in x, y and z) + ** kTypeDistorted = distorted field map (its parent field can be field map or constant field) + **/ + Int_t fType; + + /** Field limits in case of constant field **/ + Double_t fXmin, fXmax; + Double_t fYmin, fYmax; + Double_t fZmin, fZmax; + + /** Field values in case of constant field [kG] **/ + Double_t fBx, fBy, fBz; + + /** Field map name in case of field map **/ + TString fMapName; + + /** Field centre position for field map **/ + Double_t fPosX, fPosY, fPosZ; + + /** Scaling factor for field map **/ + Double_t fScale; + + /** field parameters**/ + Double_t fPeak; + Double_t fMiddle; + Double_t fBtube; + + ShipFieldPar(const ShipFieldPar&); + ShipFieldPar& operator=(const ShipFieldPar&); + + ClassDef(ShipFieldPar, 1); }; - #endif diff --git a/field/ShipGoliathField.cxx b/field/ShipGoliathField.cxx index d7b3fca3ea..31f0c82e20 100644 --- a/field/ShipGoliathField.cxx +++ b/field/ShipGoliathField.cxx @@ -2,205 +2,202 @@ // ----- ShipGoliathField source file ----- // ------------------------------------------------------------------------- #include "ShipGoliathField.h" -#include "math.h" -#include "TROOT.h" + +#include "TGeoBBox.h" +#include "TGeoManager.h" #include "TGeoNavigator.h" #include "TGeoNode.h" -#include "TGeoManager.h" -#include "TGeoBBox.h" -#include "TVector3.h" +#include "TROOT.h" #include "TTreeReader.h" #include "TTreeReaderValue.h" +#include "TVector3.h" +#include "math.h" #include #include -using std::cout; using std::cerr; +using std::cout; +using std::div; using std::endl; using std::setw; -using std::div; - // ----- Default constructor ------------------------------------------- ShipGoliathField::ShipGoliathField() - : FairField() -{ -} + : FairField() +{} // ------------------------------------------------------------------------- - - // ----- Standard constructor ------------------------------------------ ShipGoliathField::ShipGoliathField(const char* name) - : FairField(name) -{ -} + : FairField(name) +{} // ------------------------------------------------------------------------- - // ----- Destructor ---------------------------------------------------- -ShipGoliathField::~ShipGoliathField() { } +ShipGoliathField::~ShipGoliathField() {} // ------------------------------------------------------------------------- -/*void ShipGoliathField::get(const double& posX, const double& posY, const double& posZ, double& Bx, double& By, double& Bz) const { - if ((posX < coords[0][0]) && (posX > coords[0][3]) && (posY < coords[0][1]) && (posY > coords[0][4]) && (posZ < coords[0][2]+5.) && (posZ>coords[0][5]+5.) ) { - Bx = GetBx(posX, posY, posZ); - By = GetBy(posX, posY, posZ); - Bz = GetBz(posX, posY, posZ); +/*void ShipGoliathField::get(const double& posX, const double& posY, const double& posZ, double& Bx, double& By, +double& Bz) const { if ((posX < coords[0][0]) && (posX > coords[0][3]) && (posY < coords[0][1]) && (posY > coords[0][4]) +&& (posZ < coords[0][2]+5.) && (posZ>coords[0][5]+5.) ) { Bx = GetBx(posX, posY, posZ); By = GetBy(posX, posY, posZ); Bz += GetBz(posX, posY, posZ); } else { for (Int_t i=1;i<13;i++){ - if ((posX < coords[i][0]) && (posX > coords[i][3]) && (posY < coords[i][1]) && (posY > coords[i][4]) && (posZ < coords[i][2]) && (posZ>coords[i][5])) { - Bx = 0.; - By = 0.5; - Bz = 0.; - break; + if ((posX < coords[i][0]) && (posX > coords[i][3]) && (posY < coords[i][1]) && (posY > coords[i][4]) && (posZ < +coords[i][2]) && (posZ>coords[i][5])) { Bx = 0.; By = 0.5; Bz = 0.; break; } } } } */ -void ShipGoliathField::Init(const char* fieldfile){ - - fieldmap = TFile::Open(fieldfile); - - - TH3D* histbx= (TH3D*)fieldmap->Get("Bx"); - TH3D* histby= (TH3D*)fieldmap->Get("By"); - TH3D* histbz= (TH3D*)fieldmap->Get("Bz"); - xmin = histbx->GetXaxis()->GetXmin(); - xmax = histbx->GetXaxis()->GetXmax(); - ymin = histbx->GetYaxis()->GetXmin(); - ymax = histbx->GetYaxis()->GetXmax(); - zmin = histbx->GetZaxis()->GetXmin(); - zmax = histbx->GetZaxis()->GetXmax(); - - ShipGoliathField::sethistbxyz(histbx, histby, histbz); - - /* - TVector3 bot,top; - std::cout<<"ShipGoliathField::setup: making string vector"< volume={"/volGoliath_1/VolVacuum_1","/volGoliath_1/volLateralS1_1","/volGoliath_1/volLateralS2_1","/volGoliath_1/volLateralSurface1low_1",\ - "/volGoliath_1/volLateralSurface2low_1","/volGoliath_1/volLateralS1_b_1","/volGoliath_1/volLateralS2_b_1","/volGoliath_1/volLateralSurface1blow_1",\ - "/volGoliath_1/volLateralSurface2blow_1","/volGoliath_1/volLateralS1_d_1","/volGoliath_1/volLateralS2_d_1","/volGoliath_1/volLateralS1_c_1",\ - "/volGoliath_1/volLateralS2_c_1"}; - for (Int_t i=0;i<13;i++){ - std::cout<<"ShipGoliathField::setup: getpos volume "<Get("Bx"); + TH3D* histby = (TH3D*)fieldmap->Get("By"); + TH3D* histbz = (TH3D*)fieldmap->Get("Bz"); + xmin = histbx->GetXaxis()->GetXmin(); + xmax = histbx->GetXaxis()->GetXmax(); + ymin = histbx->GetYaxis()->GetXmin(); + ymax = histbx->GetYaxis()->GetXmax(); + zmin = histbx->GetZaxis()->GetXmin(); + zmax = histbx->GetZaxis()->GetXmax(); + + ShipGoliathField::sethistbxyz(histbx, histby, histbz); + + /* + TVector3 bot,top; + std::cout<<"ShipGoliathField::setup: making string vector"< + volume={"/volGoliath_1/VolVacuum_1","/volGoliath_1/volLateralS1_1","/volGoliath_1/volLateralS2_1","/volGoliath_1/volLateralSurface1low_1",\ + "/volGoliath_1/volLateralSurface2low_1","/volGoliath_1/volLateralS1_b_1","/volGoliath_1/volLateralS2_b_1","/volGoliath_1/volLateralSurface1blow_1",\ + "/volGoliath_1/volLateralSurface2blow_1","/volGoliath_1/volLateralS1_d_1","/volGoliath_1/volLateralS2_d_1","/volGoliath_1/volLateralS1_c_1",\ + "/volGoliath_1/volLateralS2_c_1"}; + for (Int_t i=0;i<13;i++){ + std::cout<<"ShipGoliathField::setup: getpos volume "<GetCurrentNavigator();} - else { std::cout<<"No geomanager"<cd(volname); - if (not rc){ - cout << "ShipGoliathfield::getpos, TGeoNavigator failed "<GetCurrentNode(); - TGeoBBox* S = dynamic_cast(W->GetVolume()->GetShape()); - Double_t top[3] = {S->GetDX(),S->GetDY(),S->GetDZ()}; - Double_t bot[3] = {-S->GetDX(),-S->GetDY(),-S->GetDZ()}; - Double_t Gtop[3],Gbot[3]; - nav->LocalToMaster(top, Gtop); - nav->LocalToMaster(bot, Gbot); - vtop.SetXYZ(Gtop[0],Gtop[1],Gtop[2]); - vbot.SetXYZ(Gbot[0],Gbot[1],Gbot[2]); +void ShipGoliathField::getpos(TString volname, TVector3& vbot, TVector3& vtop) const +{ + std::cout << "ShipGoliathField::getpos: GetCurrentNavigator volname " << volname << std::endl; + TGeoNavigator* nav; + if (gGeoManager) { + nav = gGeoManager->GetCurrentNavigator(); + } else { + std::cout << "No geomanager" << std::endl; + } + std::cout << "ShipGoliathField::getpos: cd to volume " << volname << std::endl; + Bool_t rc = nav->cd(volname); + if (not rc) { + cout << "ShipGoliathfield::getpos, TGeoNavigator failed " << volname << endl; + return; + } + std::cout << "ShipGoliathField::getpos GetCurrentNode" << std::endl; + TGeoNode* W = nav->GetCurrentNode(); + TGeoBBox* S = dynamic_cast(W->GetVolume()->GetShape()); + Double_t top[3] = {S->GetDX(), S->GetDY(), S->GetDZ()}; + Double_t bot[3] = {-S->GetDX(), -S->GetDY(), -S->GetDZ()}; + Double_t Gtop[3], Gbot[3]; + nav->LocalToMaster(top, Gtop); + nav->LocalToMaster(bot, Gbot); + vtop.SetXYZ(Gtop[0], Gtop[1], Gtop[2]); + vbot.SetXYZ(Gbot[0], Gbot[1], Gbot[2]); } - -void ShipGoliathField::close(){ - //char* mypath = std::getenv("mySHIPSOFT"); - //strcat(mypath,"/FairShip/field/GoliathFieldMap.root"); - //fieldmap->Close(mypath); - //gROOT->cd(); +void ShipGoliathField::close() +{ + // char* mypath = std::getenv("mySHIPSOFT"); + // strcat(mypath,"/FairShip/field/GoliathFieldMap.root"); + // fieldmap->Close(mypath); + // gROOT->cd(); } // ----- Get x component of field -------------------------------------- -Double_t ShipGoliathField::GetBx(Double_t x, Double_t y, Double_t z) { - Double_t bx=0.; - TH3D* hbx; +Double_t ShipGoliathField::GetBx(Double_t x, Double_t y, Double_t z) +{ + Double_t bx = 0.; + TH3D* hbx; - if ((x < xmin )|| (x> xmax) || (y < ymin) || (y>ymax) || ((z-350.75)zmax)) { - return bx;} + if ((x < xmin) || (x > xmax) || (y < ymin) || (y > ymax) || ((z - 350.75) < zmin) || ((z - 350.75) > zmax)) { + return bx; + } // FairShip: 0 after absorber -384.5GetXaxis()->FindBin(x); Int_t biny = hbx->GetYaxis()->FindBin(y); Int_t binz = hbx->GetZaxis()->FindBin(z - 350.75); - bx=hbx->GetBinContent(binx,biny,binz)*tesla; - //cout << "GetBX " << x << ", binx " << binx <<" y "<< y << " biny "< 0: yMin = yArray[0] Ny1 = Ny - 1 yMax = yArray[Ny1] - dy = (yMax - yMin)/(Ny1*1.0) + dy = (yMax - yMin) / (Ny1 * 1.0) if Nz > 0: zMin = zArray[0] Nz1 = Nz - 1 zMax = zArray[Nz1] - dz = (zMax - zMin)/(Nz1*1.0) - - rangeInfo = {'Nx': Nx, 'xMin': xMin, 'xMax': xMax, 'dx': dx, - 'Ny': Ny, 'yMin': yMin, 'yMax': yMax, 'dy': dy, - 'Nz': Nz, 'zMin': zMin, 'zMax': zMax, 'dz': dz} - - #print 'rangeInfo = {0}'.format(rangeInfo) + dz = (zMax - zMin) / (Nz1 * 1.0) + + rangeInfo = { + "Nx": Nx, + "xMin": xMin, + "xMax": xMax, + "dx": dx, + "Ny": Ny, + "yMin": yMin, + "yMax": yMax, + "dy": dy, + "Nz": Nz, + "zMin": zMin, + "zMax": zMax, + "dz": dz, + } + + # print 'rangeInfo = {0}'.format(rangeInfo) return rangeInfo if __name__ == "__main__": - - run('GoliathFieldMap.txt', 'GoliathFieldMap.root', 0.1, True) - #run('BFieldTest.txt', 'BFieldTest.root', 1.0) + run("GoliathFieldMap.txt", "GoliathFieldMap.root", 0.1, True) + # run('BFieldTest.txt', 'BFieldTest.root', 1.0) diff --git a/field/convertMisisMap.py b/field/convertMisisMap.py index 58efb58d4f..10f3783e5b 100644 --- a/field/convertMisisMap.py +++ b/field/convertMisisMap.py @@ -11,7 +11,7 @@ # Struct for the ROOT file TTree data: coord range and field info ROOT.gROOT.ProcessLine( -"struct rangeStruct{\ + "struct rangeStruct{\ float xMin;\ float xMax;\ float dx;\ @@ -21,8 +21,8 @@ float zMin;\ float zMax;\ float dz;\ -};"); - +};" +) # The field map is assumed to obey the following co-ordinate bin ordering: # z is increased first, y is increased 2nd, x is increased last. # So we only store the field components (x,y,z is known from the ordering). @@ -30,42 +30,40 @@ # where Ny and Nz are the number of y and z bins ROOT.gROOT.ProcessLine( -"struct dataStruct{\ + "struct dataStruct{\ float Bx;\ float By;\ float Bz;\ -};"); - +};" +) -def run(inFileName = 'BFieldTest.txt', - rootFileName = 'BFieldTest.root'): +def run(inFileName="BFieldTest.txt", rootFileName="BFieldTest.root"): createRootMap(inFileName, rootFileName) def createRootMap(inFileName, rootFileName): - - print('Create ROOT map {0} from {1}'.format(rootFileName, inFileName)) + print("Create ROOT map {0} from {1}".format(rootFileName, inFileName)) # Define ROOT file and its TTree - theFile = ROOT.TFile.Open(rootFileName, 'recreate') + theFile = ROOT.TFile.Open(rootFileName, "recreate") - rangeTree = ROOT.TTree('Range', 'Range') + rangeTree = ROOT.TTree("Range", "Range") rangeTree.SetDirectory(theFile) # Co-ordinate ranges rStruct = ROOT.rangeStruct() - rangeTree.Branch('xMin', ROOT.AddressOf(rStruct, 'xMin'), 'xMin/F') - rangeTree.Branch('xMax', ROOT.AddressOf(rStruct, 'xMax'), 'xMax/F') - rangeTree.Branch('dx', ROOT.AddressOf(rStruct, 'dx'), 'dx/F') - rangeTree.Branch('yMin', ROOT.AddressOf(rStruct, 'yMin'), 'yMin/F') - rangeTree.Branch('yMax', ROOT.AddressOf(rStruct, 'yMax'), 'yMax/F') - rangeTree.Branch('dy', ROOT.AddressOf(rStruct, 'dy'), 'dy/F') - rangeTree.Branch('zMin', ROOT.AddressOf(rStruct, 'zMin'), 'zMin/F') - rangeTree.Branch('zMax', ROOT.AddressOf(rStruct, 'zMax'), 'zMax/F') - rangeTree.Branch('dz', ROOT.AddressOf(rStruct, 'dz'), 'dz/F') - - dataTree = ROOT.TTree('Data', 'Data') + rangeTree.Branch("xMin", ROOT.AddressOf(rStruct, "xMin"), "xMin/F") + rangeTree.Branch("xMax", ROOT.AddressOf(rStruct, "xMax"), "xMax/F") + rangeTree.Branch("dx", ROOT.AddressOf(rStruct, "dx"), "dx/F") + rangeTree.Branch("yMin", ROOT.AddressOf(rStruct, "yMin"), "yMin/F") + rangeTree.Branch("yMax", ROOT.AddressOf(rStruct, "yMax"), "yMax/F") + rangeTree.Branch("dy", ROOT.AddressOf(rStruct, "dy"), "dy/F") + rangeTree.Branch("zMin", ROOT.AddressOf(rStruct, "zMin"), "zMin/F") + rangeTree.Branch("zMax", ROOT.AddressOf(rStruct, "zMax"), "zMax/F") + rangeTree.Branch("dz", ROOT.AddressOf(rStruct, "dz"), "dz/F") + + dataTree = ROOT.TTree("Data", "Data") dataTree.SetDirectory(theFile) # Field components with (x,y,z) coordinate binning ordered such that @@ -73,9 +71,9 @@ def createRootMap(inFileName, rootFileName): # the field bin = (iX*Ny + iY)*Nz + iZ, where Ny and Nz are the number # of y and z bins dStruct = ROOT.dataStruct() - dataTree.Branch('Bx', ROOT.AddressOf(dStruct, 'Bx'), 'Bx/F') - dataTree.Branch('By', ROOT.AddressOf(dStruct, 'By'), 'By/F') - dataTree.Branch('Bz', ROOT.AddressOf(dStruct, 'Bz'), 'Bz/F') + dataTree.Branch("Bx", ROOT.AddressOf(dStruct, "Bx"), "Bx/F") + dataTree.Branch("By", ROOT.AddressOf(dStruct, "By"), "By/F") + dataTree.Branch("Bz", ROOT.AddressOf(dStruct, "Bz"), "Bz/F") # mm to cm conversion mm2cm = 0.1 @@ -96,48 +94,51 @@ def createRootMap(inFileName, rootFileName): y0 = 0.0 z0 = 0.0 - with open(inFileName, 'r') as f: - + with open(inFileName, "r") as f: for line in f: iLine += 1 # First line contains ranges if iLine == 1: # Remove extraneous, unneeded symbols in the line - line = line.replace('[','') - line = line.replace(']','') - line = line.replace('mm','') + line = line.replace("[", "") + line = line.replace("]", "") + line = line.replace("mm", "") sLine = line.split() # Bin info line assumed to be formatted as: # Grid Output Min: xMin yMin zMin Max: xMax yMax zMax Grid Size: dx dy dz # These co-ordinate limits are in mm, but the actual data lines use m - print('sLine = {0}'.format(sLine)) + print("sLine = {0}".format(sLine)) # For each value, convert from mm to cm - rStruct.xMin = float(sLine[3])*mm2cm - rStruct.xMax = float(sLine[7])*mm2cm - rStruct.dx = float(sLine[12])*mm2cm - rStruct.yMin = float(sLine[4])*mm2cm - rStruct.yMax = float(sLine[8])*mm2cm - rStruct.dy = float(sLine[13])*mm2cm - rStruct.zMin = float(sLine[5])*mm2cm - rStruct.zMax = float(sLine[9])*mm2cm - rStruct.dz = float(sLine[14])*mm2cm - - Nx = int(((rStruct.xMax - rStruct.xMin)/rStruct.dx) + 1.0) - Ny = int(((rStruct.yMax - rStruct.yMin)/rStruct.dy) + 1.0) - Nz = int(((rStruct.zMax - rStruct.zMin)/rStruct.dz) + 1.0) - Nzy = Nz*Ny - - print('Nx = {0}, Ny = {1}, Nz = {2}'.format(Nx, Ny, Nz)) + rStruct.xMin = float(sLine[3]) * mm2cm + rStruct.xMax = float(sLine[7]) * mm2cm + rStruct.dx = float(sLine[12]) * mm2cm + rStruct.yMin = float(sLine[4]) * mm2cm + rStruct.yMax = float(sLine[8]) * mm2cm + rStruct.dy = float(sLine[13]) * mm2cm + rStruct.zMin = float(sLine[5]) * mm2cm + rStruct.zMax = float(sLine[9]) * mm2cm + rStruct.dz = float(sLine[14]) * mm2cm + + Nx = int(((rStruct.xMax - rStruct.xMin) / rStruct.dx) + 1.0) + Ny = int(((rStruct.yMax - rStruct.yMin) / rStruct.dy) + 1.0) + Nz = int(((rStruct.zMax - rStruct.zMin) / rStruct.dz) + 1.0) + Nzy = Nz * Ny + + print("Nx = {0}, Ny = {1}, Nz = {2}".format(Nx, Ny, Nz)) # Centre the field map on the local origin (cm) - x0 = 0.5*(rStruct.xMin + rStruct.xMax) - y0 = 0.5*(rStruct.yMin + rStruct.yMax) - z0 = 0.5*(rStruct.zMin + rStruct.zMax) + x0 = 0.5 * (rStruct.xMin + rStruct.xMax) + y0 = 0.5 * (rStruct.yMin + rStruct.yMax) + z0 = 0.5 * (rStruct.zMin + rStruct.zMax) - print('Centering field map using co-ordinate shift {0} {1} {2} cm'.format(x0, y0, z0)) + print( + "Centering field map using co-ordinate shift {0} {1} {2} cm".format( + x0, y0, z0 + ) + ) # Center co-ordinate range limits (cm) rStruct.xMin = rStruct.xMin - x0 @@ -152,16 +153,14 @@ def createRootMap(inFileName, rootFileName): # Fill info into range tree rangeTree.Fill() - # Field data values start from line 3 elif iLine > 2: - sLine = line.split() # Bin centre coordinates (m to cm), with origin shift (cm) - dStruct.x = float(sLine[0])*m2cm - x0 - dStruct.y = float(sLine[1])*m2cm - y0 - dStruct.z = float(sLine[2])*m2cm - z0 + dStruct.x = float(sLine[0]) * m2cm - x0 + dStruct.y = float(sLine[1]) * m2cm - y0 + dStruct.z = float(sLine[2]) * m2cm - z0 # B field components (Tesla) dStruct.Bx = float(sLine[3]) @@ -177,5 +176,4 @@ def createRootMap(inFileName, rootFileName): if __name__ == "__main__": - - run('BFieldTest.txt', 'BFieldTest.root') + run("BFieldTest.txt", "BFieldTest.root") diff --git a/field/convertNoisyMap.py b/field/convertNoisyMap.py index f542ec1937..007e7c2cde 100644 --- a/field/convertNoisyMap.py +++ b/field/convertNoisyMap.py @@ -10,10 +10,11 @@ # cmScale (default = 1.0) to convert the text file distances into cm. # For example, if the input data uses mm for lengths, cmScale = 0.1. -import ROOT -import pandas as pd import os +import pandas as pd +import ROOT + # Struct for the ROOT file TTree data: coord range and field binning ROOT.gROOT.ProcessLine( @@ -27,8 +28,8 @@ float zMin;\ float zMax;\ float dz;\ - };"); - + };" +) # The field map is assumed to obey the following co-ordinate bin ordering: # z is increased first, y is increased 2nd, x is increased last. # For the coordinate bin (iX, iY, iZ), the field bin = (iX*Ny + iY)*Nz + iZ, @@ -42,53 +43,63 @@ float Bx;\ float By;\ float Bz;\ - };"); + };" +) -def run(inFileName='FieldTest.txt', rootFileName='BFieldTest.root', - cmScale=1.0, storeCoords=False): +def run( + inFileName="FieldTest.txt", + rootFileName="BFieldTest.root", + cmScale=1.0, + storeCoords=False, +): createRootMap(inFileName, rootFileName, cmScale, storeCoords) def createRootMap(inFileName, rootFileName, cmScale, storeCoords): - print ('Create map {0} from {1} using cmScale = {2}'.format(rootFileName, - inFileName, cmScale)) + print( + "Create map {0} from {1} using cmScale = {2}".format( + rootFileName, inFileName, cmScale + ) + ) if storeCoords is True: - print ('We will also store the x,y,z field coordinates in {0}'.format(rootFileName)) + print( + "We will also store the x,y,z field coordinates in {0}".format(rootFileName) + ) rangeInfo = findRanges(inFileName, cmScale) # Define ROOT file and its TTree - theFile = ROOT.TFile.Open(rootFileName, 'recreate') + theFile = ROOT.TFile.Open(rootFileName, "recreate") - rangeTree = ROOT.TTree('Range', 'Range') + rangeTree = ROOT.TTree("Range", "Range") rangeTree.SetDirectory(theFile) # Co-ordinate ranges rStruct = ROOT.rangeStruct() - rangeTree.Branch('xMin', ROOT.AddressOf(rStruct, 'xMin'), 'xMin/F') - rangeTree.Branch('xMax', ROOT.AddressOf(rStruct, 'xMax'), 'xMax/F') - rangeTree.Branch('dx', ROOT.AddressOf(rStruct, 'dx'), 'dx/F') - rangeTree.Branch('yMin', ROOT.AddressOf(rStruct, 'yMin'), 'yMin/F') - rangeTree.Branch('yMax', ROOT.AddressOf(rStruct, 'yMax'), 'yMax/F') - rangeTree.Branch('dy', ROOT.AddressOf(rStruct, 'dy'), 'dy/F') - rangeTree.Branch('zMin', ROOT.AddressOf(rStruct, 'zMin'), 'zMin/F') - rangeTree.Branch('zMax', ROOT.AddressOf(rStruct, 'zMax'), 'zMax/F') - rangeTree.Branch('dz', ROOT.AddressOf(rStruct, 'dz'), 'dz/F') - - rStruct.xMin = rangeInfo['xMin'] - rStruct.xMax = rangeInfo['xMax'] - rStruct.dx = rangeInfo['dx'] - rStruct.yMin = rangeInfo['yMin'] - rStruct.yMax = rangeInfo['yMax'] - rStruct.dy = rangeInfo['dy'] - rStruct.zMin = rangeInfo['zMin'] - rStruct.zMax = rangeInfo['zMax'] - rStruct.dz = rangeInfo['dz'] + rangeTree.Branch("xMin", ROOT.AddressOf(rStruct, "xMin"), "xMin/F") + rangeTree.Branch("xMax", ROOT.AddressOf(rStruct, "xMax"), "xMax/F") + rangeTree.Branch("dx", ROOT.AddressOf(rStruct, "dx"), "dx/F") + rangeTree.Branch("yMin", ROOT.AddressOf(rStruct, "yMin"), "yMin/F") + rangeTree.Branch("yMax", ROOT.AddressOf(rStruct, "yMax"), "yMax/F") + rangeTree.Branch("dy", ROOT.AddressOf(rStruct, "dy"), "dy/F") + rangeTree.Branch("zMin", ROOT.AddressOf(rStruct, "zMin"), "zMin/F") + rangeTree.Branch("zMax", ROOT.AddressOf(rStruct, "zMax"), "zMax/F") + rangeTree.Branch("dz", ROOT.AddressOf(rStruct, "dz"), "dz/F") + + rStruct.xMin = rangeInfo["xMin"] + rStruct.xMax = rangeInfo["xMax"] + rStruct.dx = rangeInfo["dx"] + rStruct.yMin = rangeInfo["yMin"] + rStruct.yMax = rangeInfo["yMax"] + rStruct.dy = rangeInfo["dy"] + rStruct.zMin = rangeInfo["zMin"] + rStruct.zMax = rangeInfo["zMax"] + rStruct.dz = rangeInfo["dz"] # Centre the field map on the local origin (cm) - x0 = 0#.5 * (rStruct.xMin + rStruct.xMax) - y0 = 0#.5 * (rStruct.yMin + rStruct.yMax) + x0 = 0 # .5 * (rStruct.xMin + rStruct.xMax) + y0 = 0 # .5 * (rStruct.yMin + rStruct.yMax) z0 = 0.5 * (rStruct.zMin + rStruct.zMax) # Use this if we don't want to centre the field map @@ -96,7 +107,9 @@ def createRootMap(inFileName, rootFileName, cmScale, storeCoords): # y0 = 0.0 # z0 = 0.0 - print ('Centering field map using co-ordinate shift {0} {1} {2} cm'.format(x0, y0, z0)) + print( + "Centering field map using co-ordinate shift {0} {1} {2} cm".format(x0, y0, z0) + ) # Center co-ordinate range limits (cm) rStruct.xMin = rStruct.xMin - x0 @@ -108,15 +121,15 @@ def createRootMap(inFileName, rootFileName, cmScale, storeCoords): rStruct.zMin = rStruct.zMin - z0 rStruct.zMax = rStruct.zMax - z0 - print ('x range = {0} to {1}'.format(rStruct.xMin, rStruct.xMax)) - print ('y range = {0} to {1}'.format(rStruct.yMin, rStruct.yMax)) - print ('z range = {0} to {1}'.format(rStruct.zMin, rStruct.zMax)) + print("x range = {0} to {1}".format(rStruct.xMin, rStruct.xMax)) + print("y range = {0} to {1}".format(rStruct.yMin, rStruct.yMax)) + print("z range = {0} to {1}".format(rStruct.zMin, rStruct.zMax)) # Fill info into range tree rangeTree.Fill() # Store field data components - dataTree = ROOT.TTree('Data', 'Data') + dataTree = ROOT.TTree("Data", "Data") dataTree.SetDirectory(theFile) # Field components with (x,y,z) coordinate binning ordered such that @@ -125,22 +138,22 @@ def createRootMap(inFileName, rootFileName, cmScale, storeCoords): # of y and z bins dStruct = ROOT.dataStruct() if storeCoords is True: - dataTree.Branch('x', ROOT.AddressOf(dStruct, 'x'), 'x/F') - dataTree.Branch('y', ROOT.AddressOf(dStruct, 'y'), 'y/F') - dataTree.Branch('z', ROOT.AddressOf(dStruct, 'z'), 'z/F') + dataTree.Branch("x", ROOT.AddressOf(dStruct, "x"), "x/F") + dataTree.Branch("y", ROOT.AddressOf(dStruct, "y"), "y/F") + dataTree.Branch("z", ROOT.AddressOf(dStruct, "z"), "z/F") - dataTree.Branch('Bx', ROOT.AddressOf(dStruct, 'Bx'), 'Bx/F') - dataTree.Branch('By', ROOT.AddressOf(dStruct, 'By'), 'By/F') - dataTree.Branch('Bz', ROOT.AddressOf(dStruct, 'Bz'), 'Bz/F') + dataTree.Branch("Bx", ROOT.AddressOf(dStruct, "Bx"), "Bx/F") + dataTree.Branch("By", ROOT.AddressOf(dStruct, "By"), "By/F") + dataTree.Branch("Bz", ROOT.AddressOf(dStruct, "Bz"), "Bz/F") # Reopen the file and store the information in the ROOT file inData = pd.read_csv(inFileName, delim_whitespace=True, header=None) - inData.columns=["x", "y", "z", "bx", "by", "bz"] - inData = inData.sort_values(by=["x","y","z"]) + inData.columns = ["x", "y", "z", "bx", "by", "bz"] + inData = inData.sort_values(by=["x", "y", "z"]) inData = inData.astype(float) - count = 0. + count = 0.0 data_shape = float(inData.shape[0]) for row in inData.itertuples(): if row.Index / data_shape >= count: @@ -178,14 +191,11 @@ def findRanges(inFileName, cmScale): y_set = set() z_set = set() - with open(inFileName, 'r') as f: - + with open(inFileName, "r") as f: # Read each line for line in f: - # Ignore comment lines which begin with "#" - if '#' not in line: - + if "#" not in line: sLine = line.split() x = float(sLine[0]) * cmScale @@ -230,15 +240,30 @@ def findRanges(inFileName, cmScale): zMax = zArray[Nz1] dz = (zMax - zMin) / (Nz1 * 1.0) - rangeInfo = {'Nx': Nx, 'xMin': xMin, 'xMax': xMax, 'dx': dx, - 'Ny': Ny, 'yMin': yMin, 'yMax': yMax, 'dy': dy, - 'Nz': Nz, 'zMin': zMin, 'zMax': zMax, 'dz': dz} - - print ('rangeInfo = {0}'.format(rangeInfo)) + rangeInfo = { + "Nx": Nx, + "xMin": xMin, + "xMax": xMax, + "dx": dx, + "Ny": Ny, + "yMin": yMin, + "yMax": yMax, + "dy": dy, + "Nz": Nz, + "zMin": zMin, + "zMax": zMax, + "dz": dz, + } + + print("rangeInfo = {0}".format(rangeInfo)) return rangeInfo if __name__ == "__main__": - run(os.path.expandvars("$FAIRSHIP/files/noisy_fieldMap.csv"), - os.path.expandvars("$FAIRSHIP/files/MuonShieldField.root"), 1, False) + run( + os.path.expandvars("$FAIRSHIP/files/noisy_fieldMap.csv"), + os.path.expandvars("$FAIRSHIP/files/MuonShieldField.root"), + 1, + False, + ) diff --git a/field/convertRALMap.py b/field/convertRALMap.py index 9871318ebf..77009eaecf 100644 --- a/field/convertRALMap.py +++ b/field/convertRALMap.py @@ -10,7 +10,7 @@ # Struct for the ROOT file TTree data: coord range and field info ROOT.gROOT.ProcessLine( -"struct rangeStruct{\ + "struct rangeStruct{\ float xMin;\ float xMax;\ float dx;\ @@ -20,8 +20,8 @@ float zMin;\ float zMax;\ float dz;\ -};"); - +};" +) # The field map is assumed to obey the following co-ordinate bin ordering: # z is increased first, y is increased 2nd, x is increased last. # So we only store the field components (x,y,z is known from the ordering). @@ -29,32 +29,30 @@ # where Ny and Nz are the number of y and z bins ROOT.gROOT.ProcessLine( -"struct dataStruct{\ + "struct dataStruct{\ float Bx;\ float By;\ float Bz;\ -};"); - +};" +) -def run(inFileName = 'test07_10cm_grid.table', - outFileName = 'MuonFilterBFieldMap1.txt'): +def run(inFileName="test07_10cm_grid.table", outFileName="MuonFilterBFieldMap1.txt"): # Text format createTextMap(inFileName, outFileName) # Also create ROOT file based on the restructured text output - rootFileName = outFileName.replace('.txt', '.root') + rootFileName = outFileName.replace(".txt", ".root") createRootMap(outFileName, rootFileName) def createTextMap(inFileName, outFileName): + print("Creating text map {0} from {1}".format(outFileName, inFileName)) - print('Creating text map {0} from {1}'.format(outFileName, inFileName)) + tmpFileName = "tmpFile.txt" - tmpFileName = 'tmpFile.txt' - - inFile = open(inFileName, 'r') - tmpFile = open(tmpFileName, 'w') + inFile = open(inFileName, "r") + tmpFile = open(tmpFileName, "w") iLine = 0 xMin = 0.0 @@ -68,9 +66,9 @@ def createTextMap(inFileName, outFileName): dz = 0.0 # Offsets (in cm) - #ox = 0.0 - #oy = 0.0 - #oz = 0.0 + # ox = 0.0 + # oy = 0.0 + # oz = 0.0 iLine = 0 # Convert metres to centimetres @@ -87,16 +85,15 @@ def createTextMap(inFileName, outFileName): firstDataLine = 9 for inLine in inFile: - iLine += 1 # Skip the first few lines if iLine >= firstDataLine: words = inLine.split() - #print 'words = {0}'.format(words) + # print 'words = {0}'.format(words) # Convert the x,y,z co-ords to centimetres - x = float(words[0])*m2cm - y = float(words[1])*m2cm - z = float(words[2])*m2cm + x = float(words[0]) * m2cm + y = float(words[1]) * m2cm + z = float(words[2]) * m2cm Bx = float(words[3]) By = float(words[4]) Bz = float(words[5]) @@ -107,8 +104,8 @@ def createTextMap(inFileName, outFileName): # Write out the new line. Just print out the B field components, since we # can infer x,y,z co-ords from the ordering - newLine = '{0} {1} {2}\n'.format(BxWord, ByWord, BzWord) - #newLine = '{0:.0f} {1:.0f} {2:.0f} {3:.3e} {4:.3e} {5:.3e}\n'.format(x,y,z,Bx,By,Bz) + newLine = "{0} {1} {2}\n".format(BxWord, ByWord, BzWord) + # newLine = '{0:.0f} {1:.0f} {2:.0f} {3:.3e} {4:.3e} {5:.3e}\n'.format(x,y,z,Bx,By,Bz) tmpFile.write(newLine) # Keep track of the min/max values @@ -146,75 +143,81 @@ def createTextMap(inFileName, outFileName): dz = z - zOld gotdz = 1 - print('dx = {0}, dy = {1}, dz = {2}'.format(dx,dy,dz)) - print('x = {0} to {1}, y = {2} to {3}, z = {4} to {5}'.format(xMin, xMax, yMin, yMax, zMin, zMax)) + print("dx = {0}, dy = {1}, dz = {2}".format(dx, dy, dz)) + print( + "x = {0} to {1}, y = {2} to {3}, z = {4} to {5}".format( + xMin, xMax, yMin, yMax, zMin, zMax + ) + ) tmpFile.close() inFile.close() # Write out the map containing the co-ordinate ranges and offsets etc - tmpFile2 = open(tmpFileName, 'r') - outFile = open(outFileName, 'w') - - outLine = 'CLimits {0:.0f} {1:.0f} {2:.0f} {3:.0f} {4:.0f} {5:.0f} ' \ - '{6:.0f} {7:.0f} {8:.0f}\n'.format(xMin, xMax, dx, yMin, yMax, dy, zMin, zMax, dz) + tmpFile2 = open(tmpFileName, "r") + outFile = open(outFileName, "w") + + outLine = ( + "CLimits {0:.0f} {1:.0f} {2:.0f} {3:.0f} {4:.0f} {5:.0f} " + "{6:.0f} {7:.0f} {8:.0f}\n".format( + xMin, xMax, dx, yMin, yMax, dy, zMin, zMax, dz + ) + ) outFile.write(outLine) - #outLine = 'Offsets {0:.0f} {1:.0f} {2:.0f}\n'.format(ox, oy, oz) - #outFile.write(outLine) + # outLine = 'Offsets {0:.0f} {1:.0f} {2:.0f}\n'.format(ox, oy, oz) + # outFile.write(outLine) # Write a line showing the variable names (for file readability) - outLine = 'Bx(T) By(T) Bz(T)\n' - #outLine = 'x(cm) y(cm) z(cm) Bx(T) By(T) Bz(T)\n' + outLine = "Bx(T) By(T) Bz(T)\n" + # outLine = 'x(cm) y(cm) z(cm) Bx(T) By(T) Bz(T)\n' outFile.write(outLine) # Copy the tmp file data for tLine in tmpFile2: - outFile.write(tLine) outFile.close() tmpFile2.close() -def formatNumber(x): +def formatNumber(x): # To save disk space, reduce the precision of the field value # as we go below various thresholds # Let the general precision be 0.01 mT. Anything below this # is set to zero. - xWord = '{0:.5f}'.format(x) + xWord = "{0:.5f}".format(x) if abs(x) < 1e-5: - # Set to zero - xWord = '0' + xWord = "0" return xWord -def createRootMap(inFileName, outFileName): - print('Create ROOT map {0} from {1}'.format(outFileName, inFileName)) +def createRootMap(inFileName, outFileName): + print("Create ROOT map {0} from {1}".format(outFileName, inFileName)) # Define ROOT file and its TTree - theFile = ROOT.TFile.Open(outFileName, 'recreate') + theFile = ROOT.TFile.Open(outFileName, "recreate") - rangeTree = ROOT.TTree('Range', 'Range') + rangeTree = ROOT.TTree("Range", "Range") rangeTree.SetDirectory(theFile) # Co-ordinate ranges rStruct = ROOT.rangeStruct() - rangeTree.Branch('xMin', ROOT.AddressOf(rStruct, 'xMin'), 'xMin/F') - rangeTree.Branch('xMax', ROOT.AddressOf(rStruct, 'xMax'), 'xMax/F') - rangeTree.Branch('dx', ROOT.AddressOf(rStruct, 'dx'), 'dx/F') - rangeTree.Branch('yMin', ROOT.AddressOf(rStruct, 'yMin'), 'yMin/F') - rangeTree.Branch('yMax', ROOT.AddressOf(rStruct, 'yMax'), 'yMax/F') - rangeTree.Branch('dy', ROOT.AddressOf(rStruct, 'dy'), 'dy/F') - rangeTree.Branch('zMin', ROOT.AddressOf(rStruct, 'zMin'), 'zMin/F') - rangeTree.Branch('zMax', ROOT.AddressOf(rStruct, 'zMax'), 'zMax/F') - rangeTree.Branch('dz', ROOT.AddressOf(rStruct, 'dz'), 'dz/F') - - dataTree = ROOT.TTree('Data', 'Data') + rangeTree.Branch("xMin", ROOT.AddressOf(rStruct, "xMin"), "xMin/F") + rangeTree.Branch("xMax", ROOT.AddressOf(rStruct, "xMax"), "xMax/F") + rangeTree.Branch("dx", ROOT.AddressOf(rStruct, "dx"), "dx/F") + rangeTree.Branch("yMin", ROOT.AddressOf(rStruct, "yMin"), "yMin/F") + rangeTree.Branch("yMax", ROOT.AddressOf(rStruct, "yMax"), "yMax/F") + rangeTree.Branch("dy", ROOT.AddressOf(rStruct, "dy"), "dy/F") + rangeTree.Branch("zMin", ROOT.AddressOf(rStruct, "zMin"), "zMin/F") + rangeTree.Branch("zMax", ROOT.AddressOf(rStruct, "zMax"), "zMax/F") + rangeTree.Branch("dz", ROOT.AddressOf(rStruct, "dz"), "dz/F") + + dataTree = ROOT.TTree("Data", "Data") dataTree.SetDirectory(theFile) # Field components with (x,y,z) coordinate binning ordered such that @@ -222,9 +225,9 @@ def createRootMap(inFileName, outFileName): # the field bin = (iX*Ny + iY)*Nz + iZ, where Ny and Nz are the number # of y and z bins dStruct = ROOT.dataStruct() - dataTree.Branch('Bx', ROOT.AddressOf(dStruct, 'Bx'), 'Bx/F') - dataTree.Branch('By', ROOT.AddressOf(dStruct, 'By'), 'By/F') - dataTree.Branch('Bz', ROOT.AddressOf(dStruct, 'Bz'), 'Bz/F') + dataTree.Branch("Bx", ROOT.AddressOf(dStruct, "Bx"), "Bx/F") + dataTree.Branch("By", ROOT.AddressOf(dStruct, "By"), "By/F") + dataTree.Branch("Bz", ROOT.AddressOf(dStruct, "Bz"), "Bz/F") # Open text file and process the information iLine = 0 @@ -235,8 +238,7 @@ def createRootMap(inFileName, outFileName): Nz = 0 Nzy = 0 - with open(inFileName, 'r') as f: - + with open(inFileName, "r") as f: for line in f: iLine += 1 sLine = line.split() @@ -253,17 +255,16 @@ def createRootMap(inFileName, outFileName): rStruct.zMax = float(sLine[8]) rStruct.dz = float(sLine[9]) - Nx = int(((rStruct.xMax - rStruct.xMin)/rStruct.dx) + 1.0) - Ny = int(((rStruct.yMax - rStruct.yMin)/rStruct.dy) + 1.0) - Nz = int(((rStruct.zMax - rStruct.zMin)/rStruct.dz) + 1.0) - Nzy = Nz*Ny + Nx = int(((rStruct.xMax - rStruct.xMin) / rStruct.dx) + 1.0) + Ny = int(((rStruct.yMax - rStruct.yMin) / rStruct.dy) + 1.0) + Nz = int(((rStruct.zMax - rStruct.zMin) / rStruct.dz) + 1.0) + Nzy = Nz * Ny - print('Nx = {0}, Ny = {1}, Nz = {2}'.format(Nx, Ny, Nz)) + print("Nx = {0}, Ny = {1}, Nz = {2}".format(Nx, Ny, Nz)) rangeTree.Fill() elif iLine > 2: - # B field components dStruct.Bx = float(sLine[0]) dStruct.By = float(sLine[1]) @@ -271,13 +272,13 @@ def createRootMap(inFileName, outFileName): # Also store bin centre coordinates. # Map is ordered in ascending z, y, then x - #iBin = iLine - 3 - #zBin = iBin%Nz - #yBin = int((iBin/Nz))%Ny - #xBin = int(iBin/Nzy) - #dStruct.x = rStruct.dx*(xBin + 0.5) + rStruct.xMin - #dStruct.y = rStruct.dy*(yBin + 0.5) + rStruct.yMin - #dStruct.z = rStruct.dz*(zBin + 0.5) + rStruct.zMin + # iBin = iLine - 3 + # zBin = iBin%Nz + # yBin = int((iBin/Nz))%Ny + # xBin = int(iBin/Nzy) + # dStruct.x = rStruct.dx*(xBin + 0.5) + rStruct.xMin + # dStruct.y = rStruct.dy*(yBin + 0.5) + rStruct.yMin + # dStruct.z = rStruct.dz*(zBin + 0.5) + rStruct.zMin dataTree.Fill() @@ -288,9 +289,8 @@ def createRootMap(inFileName, outFileName): if __name__ == "__main__": - - run('test07_10cm_grid.table', 'MuonFilterBFieldMap1.txt') - #run('test08_10cm_grid.table', 'MuonFilterBFieldMap2.txt') - #run('test09_10cm_grid.table', 'MuonFilterBFieldMap3.txt') - #run('test10_10cm_grid.table', 'MuonFilterBFieldMap4.txt') - #run('test12_10cm_grid.table', 'MuonFilterBFieldMap5.txt') + run("test07_10cm_grid.table", "MuonFilterBFieldMap1.txt") + # run('test08_10cm_grid.table', 'MuonFilterBFieldMap2.txt') + # run('test09_10cm_grid.table', 'MuonFilterBFieldMap3.txt') + # run('test10_10cm_grid.table', 'MuonFilterBFieldMap4.txt') + # run('test12_10cm_grid.table', 'MuonFilterBFieldMap5.txt') diff --git a/gconfig/DecayConfig.C b/gconfig/DecayConfig.C index b65616858a..9145086ddc 100644 --- a/gconfig/DecayConfig.C +++ b/gconfig/DecayConfig.C @@ -1,3 +1,4 @@ -void DecayConfig() { - // do nothing +void DecayConfig() +{ + // do nothing } diff --git a/gconfig/DecayConfigNuAge.C b/gconfig/DecayConfigNuAge.C index 1be7d1607e..6304e29359 100644 --- a/gconfig/DecayConfigNuAge.C +++ b/gconfig/DecayConfigNuAge.C @@ -1,41 +1,42 @@ -void DecayConfig() { +void DecayConfig() +{ - // This script uses the external decayer TPythia8Decayer in place of the - // concrete Monte Carlo native decay mechanisms only for the - // specific types of decays defined below. + // This script uses the external decayer TPythia8Decayer in place of the + // concrete Monte Carlo native decay mechanisms only for the + // specific types of decays defined below. - // Access the external decayer singleton and initialize it - TPythia8Decayer* decayer = new TPythia8Decayer(); - decayer->SetDebugLevel(1); - TPythia8* tp8 = TPythia8::Instance(); - tp8->ReadString("ProcessLevel:all = off"); - // example how to overwrite decay table - // tp8->ReadString("15:new tau- tau+ 2 -3 0 1.77682 0.00000 0.00000 0.00000 8.71100e-02 0 0 0 1 0"); - // tp8->ReadString("15:addChannel 1 1 0 16 13 "); - decayer->Init(); - // Tell the concrete monte carlo to use the external decayer. The - // external decayer will be used for: - // i)particle decays not defined in concrete monte carlo, or - //ii)particles for which the concrete monte carlo is told - // to use the external decayer for its type via: - // gMC->SetUserDecay(pdgId); - // If this is invoked, the external decayer will be used for particles - // of type pdgId even if the concrete monte carlo has a decay mode - // already defined for that particle type. - gMC->SetExternalDecayer(decayer); - gMC->SetUserDecay(411); - gMC->SetUserDecay(-411); - tp8->ReadString("411:mayDecay = off"); - gMC->SetUserDecay(421); - gMC->SetUserDecay(-421); - tp8->ReadString("421:mayDecay = off"); - gMC->SetUserDecay(4122); - gMC->SetUserDecay(-4122); - tp8->ReadString("15:mayDecay = off"); - gMC->SetUserDecay(431); - gMC->SetUserDecay(-431); - tp8->ReadString("431:mayDecay = off"); - gMC->SetUserDecay(15); - gMC->SetUserDecay(-15); - tp8->ReadString("15:mayDecay = off"); + // Access the external decayer singleton and initialize it + TPythia8Decayer* decayer = new TPythia8Decayer(); + decayer->SetDebugLevel(1); + TPythia8* tp8 = TPythia8::Instance(); + tp8->ReadString("ProcessLevel:all = off"); + // example how to overwrite decay table + // tp8->ReadString("15:new tau- tau+ 2 -3 0 1.77682 0.00000 0.00000 + // 0.00000 8.71100e-02 0 0 0 1 0"); tp8->ReadString("15:addChannel 1 1 0 16 13 "); + decayer->Init(); + // Tell the concrete monte carlo to use the external decayer. The + // external decayer will be used for: + // i)particle decays not defined in concrete monte carlo, or + // ii)particles for which the concrete monte carlo is told + // to use the external decayer for its type via: + // gMC->SetUserDecay(pdgId); + // If this is invoked, the external decayer will be used for particles + // of type pdgId even if the concrete monte carlo has a decay mode + // already defined for that particle type. + gMC->SetExternalDecayer(decayer); + gMC->SetUserDecay(411); + gMC->SetUserDecay(-411); + tp8->ReadString("411:mayDecay = off"); + gMC->SetUserDecay(421); + gMC->SetUserDecay(-421); + tp8->ReadString("421:mayDecay = off"); + gMC->SetUserDecay(4122); + gMC->SetUserDecay(-4122); + tp8->ReadString("15:mayDecay = off"); + gMC->SetUserDecay(431); + gMC->SetUserDecay(-431); + tp8->ReadString("431:mayDecay = off"); + gMC->SetUserDecay(15); + gMC->SetUserDecay(-15); + tp8->ReadString("15:mayDecay = off"); } diff --git a/gconfig/DecayConfigPy6.C b/gconfig/DecayConfigPy6.C index 5df6562fa9..69d5a2d38c 100644 --- a/gconfig/DecayConfigPy6.C +++ b/gconfig/DecayConfigPy6.C @@ -1,89 +1,91 @@ -void DecayConfig() { +void DecayConfig() +{ - // This script uses the external decayer TPythia6Decayer in place of the - // concrete Monte Carlo native decay mechanisms only for the - // specific types of decays defined below. + // This script uses the external decayer TPythia6Decayer in place of the + // concrete Monte Carlo native decay mechanisms only for the + // specific types of decays defined below. - // Access the external decayer singleton and initialize it - TPythia6Decayer* decayer = TPythia6Decayer::Instance(); - // The following just tells pythia6 to not decay particles only to - // certain channels. + // Access the external decayer singleton and initialize it + TPythia6Decayer* decayer = TPythia6Decayer::Instance(); + // The following just tells pythia6 to not decay particles only to + // certain channels. - decayer->SetForceDecay(TPythia6Decayer::kAll); - //example: Force the J/PSI decay channel e+e- -// Int_t products[2]; -// Int_t mult[2]; -// Int_t npart=2; + decayer->SetForceDecay(TPythia6Decayer::kAll); + // example: Force the J/PSI decay channel e+e- + // Int_t products[2]; + // Int_t mult[2]; + // Int_t npart=2; - //decay products -// products[0]=11; -// products[1]=-11; - //multiplicity -// mult[0]=1; -// mult[1]=1; - // force the decay channel -// decayer->ForceParticleDecay(443,products,mult,npart); + // decay products + // products[0]=11; + // products[1]=-11; + // multiplicity + // mult[0]=1; + // mult[1]=1; + // force the decay channel + // decayer->ForceParticleDecay(443,products,mult,npart); - decayer->Init(); + decayer->Init(); - // Tell the concrete monte carlo to use the external decayer. The - // external decayer will be used for: - // i)particle decays not defined in concrete monte carlo, or - //ii)particles for which the concrete monte carlo is told - // to use the external decayer for its type via: - // gMC->SetUserDecay(pdgId); - // If this is invoked, the external decayer will be used for particles - // of type pdgId even if the concrete monte carlo has a decay mode - // already defined for that particle type. - gMC->SetExternalDecayer(decayer); + // Tell the concrete monte carlo to use the external decayer. The + // external decayer will be used for: + // i)particle decays not defined in concrete monte carlo, or + // ii)particles for which the concrete monte carlo is told + // to use the external decayer for its type via: + // gMC->SetUserDecay(pdgId); + // If this is invoked, the external decayer will be used for particles + // of type pdgId even if the concrete monte carlo has a decay mode + // already defined for that particle type. + gMC->SetExternalDecayer(decayer); - TPythia6& pythia6 = *(TPythia6::Instance()); + TPythia6& pythia6 = *(TPythia6::Instance()); - // The pythia6 decayer is used in place of the concrete Monte Carlo - // decay for the particles type mu+/-,pi+/-, K+/-, K0L in order to preserve - // the decay product neutrino flavor, which is otherwise not preserved in - // Geant3 decays. - const Int_t npartnf = 9; - // mu-,mu+,pi+,pi-,K+,K-,K0L, Xi- - Int_t pdgnf[npartnf] = {13,-13,211,-211,321,-321,130, 3312, 443}; - for ( Int_t ipartnf = 0; ipartnf < npartnf; ipartnf++ ) { - Int_t ipdg = pdgnf[ipartnf]; + // The pythia6 decayer is used in place of the concrete Monte Carlo + // decay for the particles type mu+/-,pi+/-, K+/-, K0L in order to preserve + // the decay product neutrino flavor, which is otherwise not preserved in + // Geant3 decays. + const Int_t npartnf = 9; + // mu-,mu+,pi+,pi-,K+,K-,K0L, Xi- + Int_t pdgnf[npartnf] = {13, -13, 211, -211, 321, -321, 130, 3312, 443}; + for (Int_t ipartnf = 0; ipartnf < npartnf; ipartnf++) { + Int_t ipdg = pdgnf[ipartnf]; - if (TString(gMC->GetName()) == "TGeant3") gMC->SetUserDecay(ipdg);// Force the decay to be done w/external decayer + if (TString(gMC->GetName()) == "TGeant3") + gMC->SetUserDecay(ipdg); // Force the decay to be done w/external decayer - pythia6.SetMDCY(pythia6.Pycomp(ipdg),1,1); // Activate decay in pythia - } + pythia6.SetMDCY(pythia6.Pycomp(ipdg), 1, 1); // Activate decay in pythia + } + // The following will print the decay modes + pythia6.Pyupda(1, 6); - // The following will print the decay modes - pythia6.Pyupda(1,6); - - // rho0 (113), rho+ (213), rho- (-213) and - // D+(411) ,D-(-411),D0(421),D0bar(-421) have decay modes defined in - // TGeant3::DefineParticles, but for these particles - // those decay modes are overridden to make use of pythia6. - const Int_t nparthq = 3; - // rho0,rho+,rho-,D+,D-,D0,D0bar - //Int_t pdghq[nparthq] = {113,213,-213,411,-411,421,-421}; - Int_t pdghq[nparthq] = {421,3122,-3122}; - for ( Int_t iparthq = 0; iparthq < nparthq; iparthq++ ) { - Int_t ipdg = pdghq[iparthq]; - if (TString(gMC->GetName()) == "TGeant3") gMC->SetUserDecay(ipdg); // Force the decay to be done w/external decayer - pythia6.SetMDCY(pythia6.Pycomp(ipdg),1,1); // Activate decay in pythia - } - // Set pi0 to be stable in pythia6 so that Geant3 can handle decay. - // In general, TGeant3 is set up through TGeant3gu::gudcay to pass - // all pythia6 decay products back to the G3 transport mechanism if they - // have a lifetime > 1.E-15 sec for further transport. - // Since the pi0 lifetime is less than this, if pi0 is produced as a decay - // product in pythia6, e.g. KL0 -> pi0 pi+ pi-, the pi0 will be immediately - // decayed by pythia6 to 2 gammas, and the KL0 decay product list passed - // back to the transport mechanism will be "gamma gamma pi+ pi-", i.e. - // the pi0 will not be visible in the list of secondaries passed back to - // the transport mechanism and will not be pushed to the stack for possible - // storage to the stdhep output array. - // To avoid this, the pi0 is set to stable in pythia6, and its decay - // will be handled by Geant3. - //pythia6.SetMDCY(pythia6.Pycomp(111),1,0); - //} + // rho0 (113), rho+ (213), rho- (-213) and + // D+(411) ,D-(-411),D0(421),D0bar(-421) have decay modes defined in + // TGeant3::DefineParticles, but for these particles + // those decay modes are overridden to make use of pythia6. + const Int_t nparthq = 3; + // rho0,rho+,rho-,D+,D-,D0,D0bar + // Int_t pdghq[nparthq] = {113,213,-213,411,-411,421,-421}; + Int_t pdghq[nparthq] = {421, 3122, -3122}; + for (Int_t iparthq = 0; iparthq < nparthq; iparthq++) { + Int_t ipdg = pdghq[iparthq]; + if (TString(gMC->GetName()) == "TGeant3") + gMC->SetUserDecay(ipdg); // Force the decay to be done w/external decayer + pythia6.SetMDCY(pythia6.Pycomp(ipdg), 1, 1); // Activate decay in pythia + } + // Set pi0 to be stable in pythia6 so that Geant3 can handle decay. + // In general, TGeant3 is set up through TGeant3gu::gudcay to pass + // all pythia6 decay products back to the G3 transport mechanism if they + // have a lifetime > 1.E-15 sec for further transport. + // Since the pi0 lifetime is less than this, if pi0 is produced as a decay + // product in pythia6, e.g. KL0 -> pi0 pi+ pi-, the pi0 will be immediately + // decayed by pythia6 to 2 gammas, and the KL0 decay product list passed + // back to the transport mechanism will be "gamma gamma pi+ pi-", i.e. + // the pi0 will not be visible in the list of secondaries passed back to + // the transport mechanism and will not be pushed to the stack for possible + // storage to the stdhep output array. + // To avoid this, the pi0 is set to stable in pythia6, and its decay + // will be handled by Geant3. + // pythia6.SetMDCY(pythia6.Pycomp(111),1,0); + //} } diff --git a/gconfig/DecayConfigPy8.C b/gconfig/DecayConfigPy8.C index a633155386..87614f6ac9 100644 --- a/gconfig/DecayConfigPy8.C +++ b/gconfig/DecayConfigPy8.C @@ -1,38 +1,39 @@ -void DecayConfig() { +void DecayConfig() +{ - // This script uses the external decayer TPythia8Decayer in place of the - // concrete Monte Carlo native decay mechanisms only for the - // specific types of decays defined below. + // This script uses the external decayer TPythia8Decayer in place of the + // concrete Monte Carlo native decay mechanisms only for the + // specific types of decays defined below. - // Access the external decayer singleton and initialize it - TVirtualMCDecayer* decayer = new TPythia8Decayer(); - decayer->Init(); + // Access the external decayer singleton and initialize it + TVirtualMCDecayer* decayer = new TPythia8Decayer(); + decayer->Init(); - // Tell the concrete monte carlo to use the external decayer. The - // external decayer will be used for: - // i)particle decays not defined in concrete monte carlo, or - //ii)particles for which the concrete monte carlo is told - // to use the external decayer for its type via: - // gMC->SetUserDecay(pdgId); - // If this is invoked, the external decayer will be used for particles - // of type pdgId even if the concrete monte carlo has a decay mode - // already defined for that particle type. - gMC->SetExternalDecayer(decayer); - // to get the rare muon decays, HOWEVER does not work with Geant4 logic - //gMC->SetUserDecay(221); // eta - //gMC->SetUserDecay(223); // omega - //gMC->SetUserDecay(113); // rho0 - //gMC->SetUserDecay(331); // eta_prime - //gMC->SetUserDecay(333); // phi - gMC->SetUserDecay(411); - gMC->SetUserDecay(-411); - gMC->SetUserDecay(421); - gMC->SetUserDecay(-421); - gMC->SetUserDecay(4122); - gMC->SetUserDecay(-4122); - gMC->SetUserDecay(431); - gMC->SetUserDecay(-431); - gMC->SetUserDecay(15); - gMC->SetUserDecay(-15); - cout<< "External decayer DecayConfigPy8 initialized"<SetUserDecay(pdgId); + // If this is invoked, the external decayer will be used for particles + // of type pdgId even if the concrete monte carlo has a decay mode + // already defined for that particle type. + gMC->SetExternalDecayer(decayer); + // to get the rare muon decays, HOWEVER does not work with Geant4 logic + // gMC->SetUserDecay(221); // eta + // gMC->SetUserDecay(223); // omega + // gMC->SetUserDecay(113); // rho0 + // gMC->SetUserDecay(331); // eta_prime + // gMC->SetUserDecay(333); // phi + gMC->SetUserDecay(411); + gMC->SetUserDecay(-411); + gMC->SetUserDecay(421); + gMC->SetUserDecay(-421); + gMC->SetUserDecay(4122); + gMC->SetUserDecay(-4122); + gMC->SetUserDecay(431); + gMC->SetUserDecay(-431); + gMC->SetUserDecay(15); + gMC->SetUserDecay(-15); + cout << "External decayer DecayConfigPy8 initialized" << endl; } diff --git a/gconfig/Geane.C b/gconfig/Geane.C index 3b46ad3bda..59be6d8bb2 100644 --- a/gconfig/Geane.C +++ b/gconfig/Geane.C @@ -4,74 +4,70 @@ void Config() { - gMC3= new TGeant3TGeo("C++ Interface to Geant3"); - cout << "-I- G3Config: Geant3 with TGeo has been created for Geane." - << endl; - // create Fair Specific Stack - FairStack *st = new FairStack(10); - gMC3->SetStack( st ) ; + gMC3 = new TGeant3TGeo("C++ Interface to Geant3"); + cout << "-I- G3Config: Geant3 with TGeo has been created for Geane." << endl; + // create Fair Specific Stack + FairStack* st = new FairStack(10); + gMC3->SetStack(st); - // ******* GEANEconfiguration for simulated Runs ******* - gMC3->SetDEBU(0, 0, 1); - gMC3->SetSWIT(4, 10); + // ******* GEANEconfiguration for simulated Runs ******* + gMC3->SetDEBU(0, 0, 1); + gMC3->SetSWIT(4, 10); - gMC3->SetDCAY(0); - gMC3->SetPAIR(0); - gMC3->SetCOMP(0); - gMC3->SetPHOT(0); - gMC3->SetPFIS(0); - gMC3->SetDRAY(0); - gMC3->SetANNI(0); - gMC3->SetBREM(1); - gMC3->SetMUNU(0); - gMC3->SetCKOV(0); - gMC3->SetHADR(0); //Select pure GEANH (HADR 1) or GEANH/NUCRIN (HADR 3)//4 fluka 5 gcalor - gMC3->SetLOSS(4); - gMC3->SetMULS(1); //1=Moliere,3=Gaussian - gMC3->SetRAYL(0); - gMC3->SetSTRA(0); + gMC3->SetDCAY(0); + gMC3->SetPAIR(0); + gMC3->SetCOMP(0); + gMC3->SetPHOT(0); + gMC3->SetPFIS(0); + gMC3->SetDRAY(0); + gMC3->SetANNI(0); + gMC3->SetBREM(1); + gMC3->SetMUNU(0); + gMC3->SetCKOV(0); + gMC3->SetHADR(0); // Select pure GEANH (HADR 1) or GEANH/NUCRIN (HADR 3)//4 fluka 5 gcalor + gMC3->SetLOSS(4); + gMC3->SetMULS(1); // 1=Moliere,3=Gaussian + gMC3->SetRAYL(0); + gMC3->SetSTRA(0); - gMC3->SetAUTO(1); //Select automatic STMIN etc... calc. (AUTO 1) or manual (AUTO 0) - gMC3->SetABAN(0); //Restore 3.16 behaviour for abandoned tracks - gMC3->SetOPTI(0); //Select optimisation level for GEANT geometry searches (0,1,2) - gMC3->SetERAN(5.e-7); + gMC3->SetAUTO(1); // Select automatic STMIN etc... calc. (AUTO 1) or manual (AUTO 0) + gMC3->SetABAN(0); // Restore 3.16 behaviour for abandoned tracks + gMC3->SetOPTI(0); // Select optimisation level for GEANT geometry searches (0,1,2) + gMC3->SetERAN(5.e-7); + // -------->>>>> PAY ATTENTION!!!!! + // For a correct use of GEANE, you MUST use the cuts as set below!!! + // i.e. Since GEANE is tracking only the primary particle, DCUTE, DCUTM, BCUTE and BCUTM must be put + // at very high values (10 TeV) in order to calculate properly the energy loss. + // For a more complete explanation of the chosen values, refer to GEANT manual - // -------->>>>> PAY ATTENTION!!!!! - // For a correct use of GEANE, you MUST use the cuts as set below!!! - // i.e. Since GEANE is tracking only the primary particle, DCUTE, DCUTM, BCUTE and BCUTM must be put - // at very high values (10 TeV) in order to calculate properly the energy loss. - // For a more complete explanation of the chosen values, refer to GEANT manual + Float_t cut = 1.e-3; // 1 MeV cut by default + Float_t cutd = 1.e4; // 10 TeV - Threshold for delta-rays + Float_t cutb = cutd; // 10 TeV - Cut for bremsstrahlung + Float_t tofmax = 1.e10; // seconds + Float_t usrcuts[5] = {0., 0., 0., 0., 0.}; // usercuts + Float_t gcalpha = 0.999; // Optimal value for alpha - Float_t cut = 1.e-3; // 1 MeV cut by default - Float_t cutd = 1.e4 ; // 10 TeV - Threshold for delta-rays - Float_t cutb = cutd; // 10 TeV - Cut for bremsstrahlung - Float_t tofmax = 1.e10; // seconds - Float_t usrcuts[5] = {0.,0.,0.,0.,0.}; // usercuts - Float_t gcalpha = 0.999; // Optimal value for alpha - - - cout<<"Energy straggling area parameter from user set to: "<SetCUTS(cut, // CUTGAM = gammas - cut, // CUTELE = electrons - cut, // CUTNEU = neutral hadrons - cut, // CUTHAD = charged hadrons - cut, // CUTMUO = muons - cutb, // BCUTE = electron bremsstrahlung - cutb, // BCUTM = muon bremsstrahlung - cutd, // DCUTE = delta rays by electrons - cutd, // DCUTM = delta rays by muons - cutb, // PPCUTM = pair production by muons - tofmax, // TOFMAX = time of flight cut - usrcuts); + // set cuts here + // GAM ELEC NHAD CHAD MUON EBREM MUHAB EDEL MUDEL MUPA TOFMAX + gMC3->SetCUTS(cut, // CUTGAM = gammas + cut, // CUTELE = electrons + cut, // CUTNEU = neutral hadrons + cut, // CUTHAD = charged hadrons + cut, // CUTMUO = muons + cutb, // BCUTE = electron bremsstrahlung + cutb, // BCUTM = muon bremsstrahlung + cutd, // DCUTE = delta rays by electrons + cutd, // DCUTM = delta rays by muons + cutb, // PPCUTM = pair production by muons + tofmax, // TOFMAX = time of flight cut + usrcuts); - gMC3->SetECut(gcalpha); + gMC3->SetECut(gcalpha); } diff --git a/gconfig/SetCuts.C b/gconfig/SetCuts.C old mode 100755 new mode 100644 index d59b6ebc24..e00088a1f3 --- a/gconfig/SetCuts.C +++ b/gconfig/SetCuts.C @@ -6,47 +6,46 @@ void SetCuts() { - cout << "SetCuts Macro: Setting Processes.." <>>> IMPORTANT!!!! - // For a correct comparison between GEANE and MC (pull distributions) - // or for a simulation without the generation of secondary particles: - // 1. set LOSS = 2, DRAY = 0, BREM = 1 - // 2. set the following cut values: CUTGAM, CUTELE, CUTNEU, CUTHAD, CUTMUO = 1 MeV or less - // BCUTE, BCUTM, DCUTE, DCUTM, PPCUTM = 10 TeV - // (For an explanation of the chosen values, please refer to the GEANT User's Guide - // or to message #5362 in the PandaRoot Forum >> Monte Carlo Engines >> g3Config.C thread) - // - // The default settings refer to a complete simulation which generates and follows also the secondary particles. - - - gMC->SetProcess("PAIR",1); /** pair production*/ - gMC->SetProcess("COMP",1); /**Compton scattering*/ - gMC->SetProcess("PHOT",1); /** photo electric effect */ - gMC->SetProcess("PFIS",0); /**photofission*/ - gMC->SetProcess("DRAY",1); /**delta-ray*/ - gMC->SetProcess("ANNI",1); /**annihilation*/ - gMC->SetProcess("BREM",1); /**bremsstrahlung*/ - gMC->SetProcess("HADR",1); /**hadronic process*/ - gMC->SetProcess("MUNU",1); /**muon nuclear interaction*/ - gMC->SetProcess("DCAY",1); /**decay*/ - gMC->SetProcess("LOSS",1); /**energy loss*/ - gMC->SetProcess("MULS",1); /**multiple scattering*/ - - Double_t cut1 = 1.0E-3; // GeV --> 1 MeV - Double_t cutb = 1.0E4; // GeV --> 10 TeV - Double_t tofmax = 1.E10; // seconds - cout << "SetCuts Macro: Setting cuts.." <SetCut("CUTGAM",cut1); /** gammas (GeV)*/ - gMC->SetCut("CUTELE",cut1); /** electrons (GeV)*/ - gMC->SetCut("CUTNEU",cut1); /** neutral hadrons (GeV)*/ - gMC->SetCut("CUTHAD",cut1); /** charged hadrons (GeV)*/ - gMC->SetCut("CUTMUO",cut1); /** muons (GeV)*/ - gMC->SetCut("BCUTE",cut1); /** electron bremsstrahlung (GeV)*/ - gMC->SetCut("BCUTM",cut1); /** muon and hadron bremsstrahlung(GeV)*/ - gMC->SetCut("DCUTE",cut1); /** delta-rays by electrons (GeV)*/ - gMC->SetCut("DCUTM",cut1); /** delta-rays by muons (GeV)*/ - gMC->SetCut("PPCUTM",cut1); /** direct pair production by muons (GeV)*/ - gMC->SetCut("TOFMAX",tofmax); /**time of flight cut in seconds*/ + cout << "SetCuts Macro: Setting Processes.." << endl; + + // ------>>>> IMPORTANT!!!! + // For a correct comparison between GEANE and MC (pull distributions) + // or for a simulation without the generation of secondary particles: + // 1. set LOSS = 2, DRAY = 0, BREM = 1 + // 2. set the following cut values: CUTGAM, CUTELE, CUTNEU, CUTHAD, CUTMUO = 1 MeV or less + // BCUTE, BCUTM, DCUTE, DCUTM, PPCUTM = 10 TeV + // (For an explanation of the chosen values, please refer to the GEANT User's Guide + // or to message #5362 in the PandaRoot Forum >> Monte Carlo Engines >> g3Config.C thread) + // + // The default settings refer to a complete simulation which generates and follows also the secondary particles. + + gMC->SetProcess("PAIR", 1); /** pair production*/ + gMC->SetProcess("COMP", 1); /**Compton scattering*/ + gMC->SetProcess("PHOT", 1); /** photo electric effect */ + gMC->SetProcess("PFIS", 0); /**photofission*/ + gMC->SetProcess("DRAY", 1); /**delta-ray*/ + gMC->SetProcess("ANNI", 1); /**annihilation*/ + gMC->SetProcess("BREM", 1); /**bremsstrahlung*/ + gMC->SetProcess("HADR", 1); /**hadronic process*/ + gMC->SetProcess("MUNU", 1); /**muon nuclear interaction*/ + gMC->SetProcess("DCAY", 1); /**decay*/ + gMC->SetProcess("LOSS", 1); /**energy loss*/ + gMC->SetProcess("MULS", 1); /**multiple scattering*/ + + Double_t cut1 = 1.0E-3; // GeV --> 1 MeV + Double_t cutb = 1.0E4; // GeV --> 10 TeV + Double_t tofmax = 1.E10; // seconds + cout << "SetCuts Macro: Setting cuts.." << endl; + + gMC->SetCut("CUTGAM", cut1); /** gammas (GeV)*/ + gMC->SetCut("CUTELE", cut1); /** electrons (GeV)*/ + gMC->SetCut("CUTNEU", cut1); /** neutral hadrons (GeV)*/ + gMC->SetCut("CUTHAD", cut1); /** charged hadrons (GeV)*/ + gMC->SetCut("CUTMUO", cut1); /** muons (GeV)*/ + gMC->SetCut("BCUTE", cut1); /** electron bremsstrahlung (GeV)*/ + gMC->SetCut("BCUTM", cut1); /** muon and hadron bremsstrahlung(GeV)*/ + gMC->SetCut("DCUTE", cut1); /** delta-rays by electrons (GeV)*/ + gMC->SetCut("DCUTM", cut1); /** delta-rays by muons (GeV)*/ + gMC->SetCut("PPCUTM", cut1); /** direct pair production by muons (GeV)*/ + gMC->SetCut("TOFMAX", tofmax); /**time of flight cut in seconds*/ } diff --git a/gconfig/UserDecay.C b/gconfig/UserDecay.C index bb471a09f2..8e780bbfcd 100644 --- a/gconfig/UserDecay.C +++ b/gconfig/UserDecay.C @@ -1,34 +1,34 @@ -void UserDecayConfig() { - cout << "Loading User Decay Config from macro"<< endl; - TDatabasePDG *db= TDatabasePDG::Instance(); - TParticlePDG *p=0; +void UserDecayConfig() +{ + cout << "Loading User Decay Config from macro" << endl; + TDatabasePDG* db = TDatabasePDG::Instance(); + TParticlePDG* p = 0; - Int_t mode[6][3]; - Float_t bratio[6]; - Int_t AlphaPDG, He5PDG; - p= db->GetParticle("Alpha"); - if(p) AlphaPDG=p->PdgCode(); - p=db->GetParticle("He5"); - - if(p) He5PDG=p->PdgCode(); - for (Int_t kz = 0; kz < 6; kz++) { - bratio[kz] = 0.; - mode[kz][0] = 0; - mode[kz][1] = 0; - mode[kz][2] = 0; - // cout << mode[kz][0] << " " << mode[kz][1] << " " << mode[kz][2] << endl; - } - bratio[0] = 100.; - mode[0][0] =2112 ; - mode[0][1] =AlphaPDG ; - - /* bratio[1] = 50.; - mode[1][0] =2212 ; - mode[1][1] =AlphaPDG ; - - */ - gMC->SetDecayMode(He5PDG,bratio,mode); + Int_t mode[6][3]; + Float_t bratio[6]; + Int_t AlphaPDG, He5PDG; + p = db->GetParticle("Alpha"); + if (p) + AlphaPDG = p->PdgCode(); + p = db->GetParticle("He5"); + if (p) + He5PDG = p->PdgCode(); + for (Int_t kz = 0; kz < 6; kz++) { + bratio[kz] = 0.; + mode[kz][0] = 0; + mode[kz][1] = 0; + mode[kz][2] = 0; + // cout << mode[kz][0] << " " << mode[kz][1] << " " << mode[kz][2] << endl; + } + bratio[0] = 100.; + mode[0][0] = 2112; + mode[0][1] = AlphaPDG; + /* bratio[1] = 50.; + mode[1][0] =2212 ; + mode[1][1] =AlphaPDG ; + */ + gMC->SetDecayMode(He5PDG, bratio, mode); } diff --git a/gconfig/basiclibs.C b/gconfig/basiclibs.C index 1c60780283..ca2df4017b 100644 --- a/gconfig/basiclibs.C +++ b/gconfig/basiclibs.C @@ -4,22 +4,22 @@ void basiclibs() { - /* - gSystem->Load("libPluto"); - */ - gSystem->Load("libRIO"); - gSystem->Load("libGeom"); - gSystem->Load("libGeomPainter"); - gSystem->Load("libVMC"); - gSystem->Load("libEG"); - gSystem->Load("libEGPythia6"); - gSystem->Load("libPythia6"); - gSystem->Load("libPhysics"); - gSystem->Load("libNet"); - gSystem->Load("libTree"); - gSystem->Load("libMinuit"); - gSystem->Load("libMathMore"); - gSystem->Load("libpythia8"); - gSystem->Load("libgenfit.so"); - gSystem->Load("libLHAPDF.so"); + /* + gSystem->Load("libPluto"); + */ + gSystem->Load("libRIO"); + gSystem->Load("libGeom"); + gSystem->Load("libGeomPainter"); + gSystem->Load("libVMC"); + gSystem->Load("libEG"); + gSystem->Load("libEGPythia6"); + gSystem->Load("libPythia6"); + gSystem->Load("libPhysics"); + gSystem->Load("libNet"); + gSystem->Load("libTree"); + gSystem->Load("libMinuit"); + gSystem->Load("libMathMore"); + gSystem->Load("libpythia8"); + gSystem->Load("libgenfit.so"); + gSystem->Load("libLHAPDF.so"); } diff --git a/gconfig/flConfig.C b/gconfig/flConfig.C old mode 100755 new mode 100644 index 71f83474d5..159527b010 --- a/gconfig/flConfig.C +++ b/gconfig/flConfig.C @@ -3,19 +3,20 @@ void Config() { - new TFluka("C++ Interface to Fluka", 1/*verbositylevel*/); + new TFluka("C++ Interface to Fluka", 1 /*verbositylevel*/); cout << "GConfig: Fluka has been created." << endl; - SnoopyStack *st = new SnoopyStack(); + SnoopyStack* st = new SnoopyStack(); st->SetMinPoints(0); - gMC->SetStack( st ) ; - gMC->SetProcess("CKOV",1); + gMC->SetStack(st); + gMC->SetProcess("CKOV", 1); - // set the common cuts + // set the common cuts TString configm(gSystem->Getenv("VMCWORKDIR")); TString cuts = configm + "/gconfig/SetCuts.C"; - cout << "Physics cuts with script \n "<< cuts.Data() << endl; - Int_t cut=gROOT->LoadMacro(cuts.Data()); - if(cut==0)gInterpreter->ProcessLine("SetCuts()"); + cout << "Physics cuts with script \n " << cuts.Data() << endl; + Int_t cut = gROOT->LoadMacro(cuts.Data()); + if (cut == 0) + gInterpreter->ProcessLine("SetCuts()"); } diff --git a/gconfig/fllibs.C b/gconfig/fllibs.C old mode 100755 new mode 100644 index ac4f5a0a5a..a3bda51065 --- a/gconfig/fllibs.C +++ b/gconfig/fllibs.C @@ -16,11 +16,11 @@ void fllibs() { -/// Macro function for loading FLUKA libraries + /// Macro function for loading FLUKA libraries - cout << "Loading Fluka libraries ..." << endl; + cout << "Loading Fluka libraries ..." << endl; - gSystem->Load("libfluka.so"); + gSystem->Load("libfluka.so"); - cout << "Loading Fluka libraries ... finished" << endl; + cout << "Loading Fluka libraries ... finished" << endl; } diff --git a/gconfig/g3Config.C b/gconfig/g3Config.C old mode 100755 new mode 100644 index 7a171a8656..67a96bceb4 --- a/gconfig/g3Config.C +++ b/gconfig/g3Config.C @@ -4,37 +4,32 @@ void Config() { - FairRunSim *fRun = FairRunSim::Instance(); - TString* gModel = fRun->GetGeoModel(); - TGeant3* geant3 = NULL; - if ( strncmp(gModel->Data(),"TGeo",4) == 0 ) { - geant3 - = new TGeant3TGeo("C++ Interface to Geant3"); - cout << "-I- G3Config: Geant3 with TGeo has been created." - << endl; - }else{ - geant3 - = new TGeant3("C++ Interface to Geant3"); - cout << "-I- G3Config: Geant3 native has been created." - << endl; - } - // create Fair Specific Stack - ShipStack *st = new ShipStack(); - st->SetMinPoints(0); - st->StoreSecondaries(kTRUE); - geant3->SetStack( st ) ; + FairRunSim* fRun = FairRunSim::Instance(); + TString* gModel = fRun->GetGeoModel(); + TGeant3* geant3 = NULL; + if (strncmp(gModel->Data(), "TGeo", 4) == 0) { + geant3 = new TGeant3TGeo("C++ Interface to Geant3"); + cout << "-I- G3Config: Geant3 with TGeo has been created." << endl; + } else { + geant3 = new TGeant3("C++ Interface to Geant3"); + cout << "-I- G3Config: Geant3 native has been created." << endl; + } + // create Fair Specific Stack + ShipStack* st = new ShipStack(); + st->SetMinPoints(0); + st->StoreSecondaries(kTRUE); + geant3->SetStack(st); - // ******* GEANT3 specific configuration for simulated Runs ******* - geant3->SetTRIG(1); //Number of events to be processed + // ******* GEANT3 specific configuration for simulated Runs ******* + geant3->SetTRIG(1); // Number of events to be processed geant3->SetSWIT(4, 100); geant3->SetDEBU(0, 0, 1); geant3->SetRAYL(1); - geant3->SetSTRA(0); // change proposed by Misha, before had geant3->SetSTRA(1); - geant3->SetAUTO(0); //Select automatic STMIN etc... calc. (AUTO 1) or manual (AUTO 0) - geant3->SetABAN(0); //Restore 3.16 behaviour for abandoned tracks - geant3->SetOPTI(2); //Select optimisation level for GEANT geometry searches (0,1,2) + geant3->SetSTRA(0); // change proposed by Misha, before had geant3->SetSTRA(1); + geant3->SetAUTO(0); // Select automatic STMIN etc... calc. (AUTO 1) or manual (AUTO 0) + geant3->SetABAN(0); // Restore 3.16 behaviour for abandoned tracks + geant3->SetOPTI(2); // Select optimisation level for GEANT geometry searches (0,1,2) geant3->SetERAN(5.e-7); - geant3->SetCKOV(0); // change proposed by Misha, before had geant3->SetCKOV(1); // cerenkov photons - + geant3->SetCKOV(0); // change proposed by Misha, before had geant3->SetCKOV(1); // cerenkov photons } diff --git a/gconfig/g3libs.C b/gconfig/g3libs.C index aa3822a506..0dfd34bffb 100644 --- a/gconfig/g3libs.C +++ b/gconfig/g3libs.C @@ -2,21 +2,21 @@ Bool_t isLibrary(const char* libName) { - if (TString(gSystem->DynamicPathName(libName, kTRUE)) != TString("")) - return kTRUE; - else - return kFALSE; + if (TString(gSystem->DynamicPathName(libName, kTRUE)) != TString("")) + return kTRUE; + else + return kFALSE; } void g3libs() { - cout << "Loading Geant3 libraries ..." << endl; + cout << "Loading Geant3 libraries ..." << endl; - if (isLibrary("libdummies.so")) - gSystem->Load("libdummies.so"); - // libdummies.so needed from geant3_+vmc version 0.5 + if (isLibrary("libdummies.so")) + gSystem->Load("libdummies.so"); + // libdummies.so needed from geant3_+vmc version 0.5 - gSystem->Load("libgeant321.so"); + gSystem->Load("libgeant321.so"); - cout << "Loading Geant3 libraries ... finished" << endl; + cout << "Loading Geant3 libraries ... finished" << endl; } diff --git a/gconfig/g4Config.C b/gconfig/g4Config.C old mode 100755 new mode 100644 index 6cc6e948ca..3659b0d170 --- a/gconfig/g4Config.C +++ b/gconfig/g4Config.C @@ -1,53 +1,53 @@ // Configuration macro for Geant4 VirtualMC void Config() { -/// Create the run configuration -/// In constructor user has to specify the geometry input -/// and select geometry navigation via the following options: -/// - geomVMCtoGeant4 - geometry defined via VMC, G4 native navigation -/// - geomVMCtoRoot - geometry defined via VMC, Root navigation -/// - geomRoot - geometry defined via Root, Root navigation -/// - geomRootToGeant4 - geometry defined via Root, G4 native navigation -/// - geomGeant4 - geometry defined via Geant4, G4 native navigation -/// -/// The second argument in the constructor selects physics list: -/// - emStandard - standard em physics (default) -/// - emStandard+optical - standard em physics + optical physics -/// - XYZ - selected hadron physics list ( XYZ = LHEP, QGSP, ...) -/// - XYZ+optical - selected hadron physics list + optical physics -/// -/// The third argument activates the special processes in the TG4SpecialPhysicsList, -/// which implement VMC features: -/// - stepLimiter - step limiter (default) -/// - specialCuts - VMC cuts -/// - specialControls - VMC controls for activation/inactivation selected processes -/// - stackPopper - stackPopper process -/// When more than one options are selected, they should be separated with '+' -/// character: eg. stepLimit+specialCuts. - TG4RunConfiguration* runConfiguration - = new TG4RunConfiguration("geomRoot", "QGSP_BERT_HP_PEN", "stepLimiter+specialCuts+specialControls"); + /// Create the run configuration + /// In constructor user has to specify the geometry input + /// and select geometry navigation via the following options: + /// - geomVMCtoGeant4 - geometry defined via VMC, G4 native navigation + /// - geomVMCtoRoot - geometry defined via VMC, Root navigation + /// - geomRoot - geometry defined via Root, Root navigation + /// - geomRootToGeant4 - geometry defined via Root, G4 native navigation + /// - geomGeant4 - geometry defined via Geant4, G4 native navigation + /// + /// The second argument in the constructor selects physics list: + /// - emStandard - standard em physics (default) + /// - emStandard+optical - standard em physics + optical physics + /// - XYZ - selected hadron physics list ( XYZ = LHEP, QGSP, ...) + /// - XYZ+optical - selected hadron physics list + optical physics + /// + /// The third argument activates the special processes in the TG4SpecialPhysicsList, + /// which implement VMC features: + /// - stepLimiter - step limiter (default) + /// - specialCuts - VMC cuts + /// - specialControls - VMC controls for activation/inactivation selected processes + /// - stackPopper - stackPopper process + /// When more than one options are selected, they should be separated with '+' + /// character: eg. stepLimit+specialCuts. + TG4RunConfiguration* runConfiguration = + new TG4RunConfiguration("geomRoot", "QGSP_BERT_HP_PEN", "stepLimiter+specialCuts+specialControls"); -/// Create the G4 VMC - TGeant4* geant4 = new TGeant4("TGeant4", "The Geant4 Monte Carlo", runConfiguration); -/// create the Specific stack - ShipStack *stack = new ShipStack(1000); - stack->StoreSecondaries(kTRUE); - stack->SetMinPoints(0); - geant4->SetStack(stack); - //if(FairRunSim::Instance()->IsExtDecayer()){ - // // does not work ! TVirtualMCDecayer* decayer = TPythia8Decayer::Instance(); - // TVirtualMCDecayer* decayer = TVirtualMCDecayer* TPythia8Decayer(); - // geant4->SetExternalDecayer(decayer); - //} + /// Create the G4 VMC + TGeant4* geant4 = new TGeant4("TGeant4", "The Geant4 Monte Carlo", runConfiguration); + /// create the Specific stack + ShipStack* stack = new ShipStack(1000); + stack->StoreSecondaries(kTRUE); + stack->SetMinPoints(0); + geant4->SetStack(stack); + // if(FairRunSim::Instance()->IsExtDecayer()){ + // // does not work ! TVirtualMCDecayer* decayer = TPythia8Decayer::Instance(); + // TVirtualMCDecayer* decayer = TVirtualMCDecayer* TPythia8Decayer(); + // geant4->SetExternalDecayer(decayer); + // } -/// Customise Geant4 setting -/// (verbose level, global range cut, ..) + /// Customise Geant4 setting + /// (verbose level, global range cut, ..) - TString configm(gSystem->Getenv("VMCWORKDIR")); - TString configm1 = configm + "/gconfig/g4config.in"; - cout << " -I g4Config() using g4conf macro: " << configm1 << endl; - //set geant4 specific stuff - // still stupid bug in geant4_vmc - // geant4->SetMaxNStep(10000.); // default is 30000 - geant4->ProcessGeantMacro(configm1.Data()); + TString configm(gSystem->Getenv("VMCWORKDIR")); + TString configm1 = configm + "/gconfig/g4config.in"; + cout << " -I g4Config() using g4conf macro: " << configm1 << endl; + // set geant4 specific stuff + // still stupid bug in geant4_vmc + // geant4->SetMaxNStep(10000.); // default is 30000 + geant4->ProcessGeantMacro(configm1.Data()); } diff --git a/gconfig/g4Config_basic.C b/gconfig/g4Config_basic.C index 609c855dd9..acdaa96d90 100644 --- a/gconfig/g4Config_basic.C +++ b/gconfig/g4Config_basic.C @@ -1,53 +1,52 @@ // Configuration macro for Geant4 VirtualMC void Config() { -/// Create the run configuration -/// In constructor user has to specify the geometry input -/// and select geometry navigation via the following options: -/// - geomVMCtoGeant4 - geometry defined via VMC, G4 native navigation -/// - geomVMCtoRoot - geometry defined via VMC, Root navigation -/// - geomRoot - geometry defined via Root, Root navigation -/// - geomRootToGeant4 - geometry defined via Root, G4 native navigation -/// - geomGeant4 - geometry defined via Geant4, G4 native navigation -/// -/// The second argument in the constructor selects physics list: -/// - emStandard - standard em physics (default) -/// - emStandard+optical - standard em physics + optical physics -/// - XYZ - selected hadron physics list ( XYZ = LHEP, QGSP, ...) -/// - XYZ+optical - selected hadron physics list + optical physics -/// -/// The third argument activates the special processes in the TG4SpecialPhysicsList, -/// which implement VMC features: -/// - stepLimiter - step limiter (default) -/// - specialCuts - VMC cuts -/// - specialControls - VMC controls for activation/inactivation selected processes -/// - stackPopper - stackPopper process -/// When more than one options are selected, they should be separated with '+' -/// character: eg. stepLimit+specialCuts. - TG4RunConfiguration* runConfiguration - = new TG4RunConfiguration("geomRoot", "emStandard"); + /// Create the run configuration + /// In constructor user has to specify the geometry input + /// and select geometry navigation via the following options: + /// - geomVMCtoGeant4 - geometry defined via VMC, G4 native navigation + /// - geomVMCtoRoot - geometry defined via VMC, Root navigation + /// - geomRoot - geometry defined via Root, Root navigation + /// - geomRootToGeant4 - geometry defined via Root, G4 native navigation + /// - geomGeant4 - geometry defined via Geant4, G4 native navigation + /// + /// The second argument in the constructor selects physics list: + /// - emStandard - standard em physics (default) + /// - emStandard+optical - standard em physics + optical physics + /// - XYZ - selected hadron physics list ( XYZ = LHEP, QGSP, ...) + /// - XYZ+optical - selected hadron physics list + optical physics + /// + /// The third argument activates the special processes in the TG4SpecialPhysicsList, + /// which implement VMC features: + /// - stepLimiter - step limiter (default) + /// - specialCuts - VMC cuts + /// - specialControls - VMC controls for activation/inactivation selected processes + /// - stackPopper - stackPopper process + /// When more than one options are selected, they should be separated with '+' + /// character: eg. stepLimit+specialCuts. + TG4RunConfiguration* runConfiguration = new TG4RunConfiguration("geomRoot", "emStandard"); -/// Create the G4 VMC - TGeant4* geant4 = new TGeant4("TGeant4", "The Geant4 Monte Carlo", runConfiguration); -/// create the Specific stack - ShipStack *stack = new ShipStack(1000); - stack->StoreSecondaries(kTRUE); - stack->SetMinPoints(0); - geant4->SetStack(stack); - //if(FairRunSim::Instance()->IsExtDecayer()){ - // // does not work ! TVirtualMCDecayer* decayer = TPythia8Decayer::Instance(); - // TVirtualMCDecayer* decayer = TVirtualMCDecayer* TPythia8Decayer(); - // geant4->SetExternalDecayer(decayer); - //} + /// Create the G4 VMC + TGeant4* geant4 = new TGeant4("TGeant4", "The Geant4 Monte Carlo", runConfiguration); + /// create the Specific stack + ShipStack* stack = new ShipStack(1000); + stack->StoreSecondaries(kTRUE); + stack->SetMinPoints(0); + geant4->SetStack(stack); + // if(FairRunSim::Instance()->IsExtDecayer()){ + // // does not work ! TVirtualMCDecayer* decayer = TPythia8Decayer::Instance(); + // TVirtualMCDecayer* decayer = TVirtualMCDecayer* TPythia8Decayer(); + // geant4->SetExternalDecayer(decayer); + // } -/// Customise Geant4 setting -/// (verbose level, global range cut, ..) + /// Customise Geant4 setting + /// (verbose level, global range cut, ..) - TString configm(gSystem->Getenv("VMCWORKDIR")); - TString configm1 = configm + "/gconfig/g4config_basic.in"; - cout << " -I g4Config() using g4conf macro: " << configm1 << endl; - //set geant4 specific stuff - // still stupid bug in geant4_vmc - // geant4->SetMaxNStep(10000.); // default is 30000 - geant4->ProcessGeantMacro(configm1.Data()); + TString configm(gSystem->Getenv("VMCWORKDIR")); + TString configm1 = configm + "/gconfig/g4config_basic.in"; + cout << " -I g4Config() using g4conf macro: " << configm1 << endl; + // set geant4 specific stuff + // still stupid bug in geant4_vmc + // geant4->SetMaxNStep(10000.); // default is 30000 + geant4->ProcessGeantMacro(configm1.Data()); } diff --git a/gconfig/rootlogon.C b/gconfig/rootlogon.C index da7fdb536d..3b9c6f90ba 100644 --- a/gconfig/rootlogon.C +++ b/gconfig/rootlogon.C @@ -1,17 +1,17 @@ rootlogon() { - gROOT->LoadMacro("$VMCWORKDIR/gconfig/basiclibs.C"); - basiclibs(); + gROOT->LoadMacro("$VMCWORKDIR/gconfig/basiclibs.C"); + basiclibs(); - // Load this example libraries - gSystem->Load("libFairTools"); - gSystem->Load("libGeoBase"); - gSystem->Load("libParBase"); - gSystem->Load("libBase"); - gSystem->Load("libMCStack"); - gSystem->Load("libField"); - gSystem->Load("libPassive"); - gSystem->Load("libGen"); - gSystem->Load("libPGen"); - gSystem->Load("libGeane"); + // Load this example libraries + gSystem->Load("libFairTools"); + gSystem->Load("libGeoBase"); + gSystem->Load("libParBase"); + gSystem->Load("libBase"); + gSystem->Load("libMCStack"); + gSystem->Load("libField"); + gSystem->Load("libPassive"); + gSystem->Load("libGen"); + gSystem->Load("libPGen"); + gSystem->Load("libGeane"); } diff --git a/geometry/config_tester.py b/geometry/config_tester.py index e9ff345c2c..f409be49bc 100755 --- a/geometry/config_tester.py +++ b/geometry/config_tester.py @@ -1,9 +1,10 @@ #!/usr/bin/env python -import os +import argparse import json -from ShipGeoConfig import ConfigRegistry import logging -import argparse +import os + +from ShipGeoConfig import ConfigRegistry logging.info("") logger = logging.getLogger() @@ -11,13 +12,17 @@ def parse_arguments(): - ap = argparse.ArgumentParser( - description='test configuration file') - ap.add_argument('-d', '--debug', action='store_true') - ap.add_argument('-p', '--params', type=json.loads, - help="""config parameters in json form '{"a": 1, "b": 2}' """, default=None) + ap = argparse.ArgumentParser(description="test configuration file") + ap.add_argument("-d", "--debug", action="store_true") + ap.add_argument( + "-p", + "--params", + type=json.loads, + help="""config parameters in json form '{"a": 1, "b": 2}' """, + default=None, + ) - ap.add_argument('config_file', help='config file to test') + ap.add_argument("config_file", help="config file to test") args = ap.parse_args() if args.debug: logger.setLevel(logging.DEBUG) @@ -34,5 +39,6 @@ def main(arguments): for k, v in ConfigRegistry().items(): print("%s: %s" % (k, v)) -if __name__ == '__main__': + +if __name__ == "__main__": main(parse_arguments()) diff --git a/geometry/geometry_config.py b/geometry/geometry_config.py index 130199c1f2..ac769f4e65 100644 --- a/geometry/geometry_config.py +++ b/geometry/geometry_config.py @@ -1,6 +1,7 @@ -import shipunit as u import ROOT as r +import shipunit as u from ShipGeoConfig import AttrDict, ConfigRegistry + # the following params should be passed through 'ConfigRegistry.loadpy' method # muShieldDesign = 7 # 7 = short magnet design 9 = optimised with T4 as constraint, 8=requires config file # 10 = with field map for hadron absorber, 11 = 9 with field map for muon shield @@ -11,14 +12,122 @@ # strawOpt = 0 # 0=simplistic tracking stations defined in veto.cxx 1=detailed strawtube design 4=sophisticated straw tube design, horizontal wires (default) 10=2cm straw diameter for 2018 layout # tankDesign = 5 # 4=TP elliptical tank design, 5 = optimized conical rectangular design, 6=5 without segment-1 shield_db = { - 'combi': [ 70. , 170. , 208. , 207. , 281. , 172.82, 212.54, 168.64, - 40. , 40. , 150. , 150. , 2. , 2. , 80. , 80. , - 150. , 150. , 2. , 2. , 72. , 51. , 29. , 46. , - 10. , 7. , 54. , 38. , 46. , 192. , 14. , 9. , - 10. , 31. , 35. , 31. , 51. , 11. , 3. , 32. , - 54. , 24. , 8. , 8. , 22. , 32. , 209. , 35. , - 8. , 13. , 33. , 77. , 85. , 241. , 9. , 26. ], - 'sc_v6': [70,170,0,353.078,125.083,184.834,150.193,186.812,40,40,150,150,2,2,80,80,150,150,2,2,72,51,29,46,10,7,45.6888,45.6888,22.1839,22.1839,27.0063,16.2448,10,31,35,31,51,11,24.7961,48.7639,8,104.732,15.7991,16.7793,3,100,192,192,2,4.8004,3,100,8,172.729,46.8285,2] + "combi": [ + 70.0, + 170.0, + 208.0, + 207.0, + 281.0, + 172.82, + 212.54, + 168.64, + 40.0, + 40.0, + 150.0, + 150.0, + 2.0, + 2.0, + 80.0, + 80.0, + 150.0, + 150.0, + 2.0, + 2.0, + 72.0, + 51.0, + 29.0, + 46.0, + 10.0, + 7.0, + 54.0, + 38.0, + 46.0, + 192.0, + 14.0, + 9.0, + 10.0, + 31.0, + 35.0, + 31.0, + 51.0, + 11.0, + 3.0, + 32.0, + 54.0, + 24.0, + 8.0, + 8.0, + 22.0, + 32.0, + 209.0, + 35.0, + 8.0, + 13.0, + 33.0, + 77.0, + 85.0, + 241.0, + 9.0, + 26.0, + ], + "sc_v6": [ + 70, + 170, + 0, + 353.078, + 125.083, + 184.834, + 150.193, + 186.812, + 40, + 40, + 150, + 150, + 2, + 2, + 80, + 80, + 150, + 150, + 2, + 2, + 72, + 51, + 29, + 46, + 10, + 7, + 45.6888, + 45.6888, + 22.1839, + 22.1839, + 27.0063, + 16.2448, + 10, + 31, + 35, + 31, + 51, + 11, + 24.7961, + 48.7639, + 8, + 104.732, + 15.7991, + 16.7793, + 3, + 100, + 192, + 192, + 2, + 4.8004, + 3, + 100, + 8, + 172.729, + 46.8285, + 2, + ], } if "muShieldDesign" not in globals(): muShieldDesign = 7 @@ -29,7 +138,7 @@ if "nuTauTargetDesign" not in globals(): nuTauTargetDesign = 0 if muShieldDesign >= 7: - nuTauTargetDesign=1 + nuTauTargetDesign = 1 if "targetOpt" not in globals(): targetOpt = 18 if "strawDesign" not in globals(): @@ -39,7 +148,7 @@ if "CaloDesign" not in globals(): CaloDesign = 0 if "Yheight" not in globals(): - Yheight = 10. + Yheight = 10.0 if "EcalGeoFile" not in globals(): if tankDesign > 4: EcalGeoFile = "ecal_rect5x10m2.geo" @@ -64,132 +173,140 @@ SND = True with ConfigRegistry.register_config("basic") as c: - c.DecayVolumeMedium = DecayVolumeMedium c.SND = SND c.SC_mag = SC_mag c.scName = scName # global muShieldDesign, targetOpt, strawDesign, Yheight - c.Yheight = Yheight*u.m + c.Yheight = Yheight * u.m # decision by the SP - totalLength = 60 * u.m - extraVesselLength = totalLength - 50*u.m - windowBulge = 1*u.m - if tankDesign > 5: windowBulge = 25*u.cm -# + totalLength = 60 * u.m + extraVesselLength = totalLength - 50 * u.m + windowBulge = 1 * u.m + if tankDesign > 5: + windowBulge = 25 * u.cm + # magnet_design = 2 - if tankDesign == 5: magnet_design = 3 - if tankDesign == 6: magnet_design = 4 -# + if tankDesign == 5: + magnet_design = 3 + if tankDesign == 6: + magnet_design = 4 + # c.strawDesign = strawDesign c.tankDesign = tankDesign c.magnetDesign = magnet_design -# cave parameters - c.cave = AttrDict(z=0*u.cm) - c.cave.floorHeightMuonShield = 5*u.m - c.cave.floorHeightTankA = 4.2*u.m + # cave parameters + c.cave = AttrDict(z=0 * u.cm) + c.cave.floorHeightMuonShield = 5 * u.m + c.cave.floorHeightTankA = 4.2 * u.m if strawDesign == 10: - c.cave.floorHeightMuonShield = c.cave.floorHeightTankA # avoid the gap, for 2018 geometry - c.cave.floorHeightTankB = 2*u.m -# - #neutrino detector - c.nuTauTargetDesign=nuTauTargetDesign - - c.chambers = AttrDict(z=0*u.cm) - magnetIncrease = 100.*u.cm + c.cave.floorHeightMuonShield = ( + c.cave.floorHeightTankA + ) # avoid the gap, for 2018 geometry + c.cave.floorHeightTankB = 2 * u.m + # + # neutrino detector + c.nuTauTargetDesign = nuTauTargetDesign + + c.chambers = AttrDict(z=0 * u.cm) + magnetIncrease = 100.0 * u.cm # make z coordinates for the decay volume and tracking stations relative to T4z # eventually, the only parameter which needs to be changed when the active shielding lenght changes. - z4=2438.*u.cm+magnetIncrease+extraVesselLength + z4 = 2438.0 * u.cm + magnetIncrease + extraVesselLength if strawDesign != 4 and strawDesign != 10: - print("this design ",strawDesign," is not supported, use strawDesign = 4 or 10") - 1/0 + print( + "this design ", strawDesign, " is not supported, use strawDesign = 4 or 10" + ) + 1 / 0 else: - c.chambers.Length = totalLength - c.chambers.Tub1length = 2.5 * u.m - c.chambers.Tub2length = 17.68*u.m+extraVesselLength/2. - c.chambers.Tub3length = 0.8*u.m - c.chambers.Tub4length = 2.*u.m+magnetIncrease/2. - c.chambers.Tub5length = 0.8*u.m - c.chambers.Tub6length = 0.1*u.m+windowBulge/2. - c.chambers.Rmin = 245.*u.cm - c.chambers.Rmax = 250.*u.cm - # positions and lenghts of vacuum tube segments - zset=z4-4666.*u.cm-magnetIncrease-extraVesselLength - c.Chamber1 = AttrDict(z=zset) - zset=z4-2628.*u.cm-magnetIncrease-extraVesselLength/2. - c.Chamber2 = AttrDict(z=zset) - zset=z4-740.*u.cm-magnetIncrease - c.Chamber3 = AttrDict(z=zset) - zset=z4-420.*u.cm-magnetIncrease/2. - c.Chamber4 = AttrDict(z=zset) - zset=z4-100.*u.cm - c.Chamber5 = AttrDict(z=zset) - zset=z4+30.*u.cm+windowBulge/2. - c.Chamber6 = AttrDict(z=zset) - - c.xMax = 2 * u.m # max horizontal width at T4 - # - c.TrackStation4 = AttrDict(z=z4) - zset=z4-200.*u.cm - c.TrackStation3 = AttrDict(z=zset) - zset=z4-640.*u.cm-magnetIncrease - c.TrackStation2 = AttrDict(z=zset) - zset=z4-840.*u.cm-magnetIncrease - c.TrackStation1 = AttrDict(z=zset) - zset=z4-4406.*u.cm-magnetIncrease-extraVesselLength - c.vetoStation = AttrDict(z=zset) + c.chambers.Length = totalLength + c.chambers.Tub1length = 2.5 * u.m + c.chambers.Tub2length = 17.68 * u.m + extraVesselLength / 2.0 + c.chambers.Tub3length = 0.8 * u.m + c.chambers.Tub4length = 2.0 * u.m + magnetIncrease / 2.0 + c.chambers.Tub5length = 0.8 * u.m + c.chambers.Tub6length = 0.1 * u.m + windowBulge / 2.0 + c.chambers.Rmin = 245.0 * u.cm + c.chambers.Rmax = 250.0 * u.cm + # positions and lenghts of vacuum tube segments + zset = z4 - 4666.0 * u.cm - magnetIncrease - extraVesselLength + c.Chamber1 = AttrDict(z=zset) + zset = z4 - 2628.0 * u.cm - magnetIncrease - extraVesselLength / 2.0 + c.Chamber2 = AttrDict(z=zset) + zset = z4 - 740.0 * u.cm - magnetIncrease + c.Chamber3 = AttrDict(z=zset) + zset = z4 - 420.0 * u.cm - magnetIncrease / 2.0 + c.Chamber4 = AttrDict(z=zset) + zset = z4 - 100.0 * u.cm + c.Chamber5 = AttrDict(z=zset) + zset = z4 + 30.0 * u.cm + windowBulge / 2.0 + c.Chamber6 = AttrDict(z=zset) + + c.xMax = 2 * u.m # max horizontal width at T4 + # + c.TrackStation4 = AttrDict(z=z4) + zset = z4 - 200.0 * u.cm + c.TrackStation3 = AttrDict(z=zset) + zset = z4 - 640.0 * u.cm - magnetIncrease + c.TrackStation2 = AttrDict(z=zset) + zset = z4 - 840.0 * u.cm - magnetIncrease + c.TrackStation1 = AttrDict(z=zset) + zset = z4 - 4406.0 * u.cm - magnetIncrease - extraVesselLength + c.vetoStation = AttrDict(z=zset) c.z = c.TrackStation2.z + 0.5 * (c.TrackStation3.z - c.TrackStation2.z) - c.scintillator = AttrDict(z=0*u.cm) - c.scintillator.Rmin = 251.*u.cm - c.scintillator.Rmax = 260.*u.cm - - c.strawtubes = AttrDict(z=0*u.cm) - if strawDesign==4: - c.strawtubes.InnerStrawDiameter = 0.975*u.cm - c.strawtubes.StrawPitch = 1.76*u.cm - c.strawtubes.DeltazLayer = 1.1*u.cm - c.strawtubes.DeltazPlane = 2.6*u.cm - c.strawtubes.YLayerOffset = c.strawtubes.StrawPitch / 2. - c.strawtubes.YPlaneOffset = c.strawtubes.StrawPitch / 4. - c.strawtubes.FrameMaterial = "aluminium" - c.strawtubes.FrameLateralWidth = 1.*u.cm - c.strawtubes.DeltazFrame = 10.*u.cm - elif strawDesign==10: # 10 - baseline for 2018 - c.strawtubes.InnerStrawDiameter = 1.9928 * u.cm - c.strawtubes.StrawPitch = 2. * u.cm - c.strawtubes.DeltazLayer = 1.732 * u.cm - c.strawtubes.DeltazPlane = 0 * u.cm - c.strawtubes.YLayerOffset = 1. * u.cm - c.strawtubes.YPlaneOffset = 0 * u.cm - c.strawtubes.FrameMaterial = "steel" - c.strawtubes.FrameLateralWidth = 0.25 * u.m - c.strawtubes.DeltazFrame = 2.5 * u.cm + c.scintillator = AttrDict(z=0 * u.cm) + c.scintillator.Rmin = 251.0 * u.cm + c.scintillator.Rmax = 260.0 * u.cm + + c.strawtubes = AttrDict(z=0 * u.cm) + if strawDesign == 4: + c.strawtubes.InnerStrawDiameter = 0.975 * u.cm + c.strawtubes.StrawPitch = 1.76 * u.cm + c.strawtubes.DeltazLayer = 1.1 * u.cm + c.strawtubes.DeltazPlane = 2.6 * u.cm + c.strawtubes.YLayerOffset = c.strawtubes.StrawPitch / 2.0 + c.strawtubes.YPlaneOffset = c.strawtubes.StrawPitch / 4.0 + c.strawtubes.FrameMaterial = "aluminium" + c.strawtubes.FrameLateralWidth = 1.0 * u.cm + c.strawtubes.DeltazFrame = 10.0 * u.cm + elif strawDesign == 10: # 10 - baseline for 2018 + c.strawtubes.InnerStrawDiameter = 1.9928 * u.cm + c.strawtubes.StrawPitch = 2.0 * u.cm + c.strawtubes.DeltazLayer = 1.732 * u.cm + c.strawtubes.DeltazPlane = 0 * u.cm + c.strawtubes.YLayerOffset = 1.0 * u.cm + c.strawtubes.YPlaneOffset = 0 * u.cm + c.strawtubes.FrameMaterial = "steel" + c.strawtubes.FrameLateralWidth = 0.25 * u.m + c.strawtubes.DeltazFrame = 2.5 * u.cm c.strawtubes.WallThickness = 0.0036 * u.cm - c.strawtubes.OuterStrawDiameter = (c.strawtubes.InnerStrawDiameter + 2 * c.strawtubes.WallThickness) + c.strawtubes.OuterStrawDiameter = ( + c.strawtubes.InnerStrawDiameter + 2 * c.strawtubes.WallThickness + ) - c.strawtubes.StrawsPerLayer = int(c.Yheight/c.strawtubes.StrawPitch) + c.strawtubes.StrawsPerLayer = int(c.Yheight / c.strawtubes.StrawPitch) c.strawtubes.ViewAngle = 4.57 c.strawtubes.WireThickness = 0.003 * u.cm - c.strawtubes.DeltazView = 5. * u.cm - c.strawtubes.VacBox_x = 240. * u.cm - c.strawtubes.VacBox_y = 600. * u.cm * c.Yheight / (10. * u.m) + c.strawtubes.DeltazView = 5.0 * u.cm + c.strawtubes.VacBox_x = 240.0 * u.cm + c.strawtubes.VacBox_y = 600.0 * u.cm * c.Yheight / (10.0 * u.m) c.Bfield = AttrDict(z=c.z) - c.Bfield.max = 0 # 1.4361*u.kilogauss # was 1.15 in EOI - c.Bfield.y = c.Yheight - c.Bfield.x = 2.4 * u.m + c.Bfield.max = 0 # 1.4361*u.kilogauss # was 1.15 in EOI + c.Bfield.y = c.Yheight + c.Bfield.x = 2.4 * u.m c.Bfield.fieldMap = "field/MainSpectrometerField.txt" - if c.magnetDesign>3: # MISIS design - c.Bfield.YokeWidth = 0.8 * u.m # full width 200.*cm - c.Bfield.YokeDepth = 1.4 * u.m # half length 200 *cm; - c.Bfield.CoilThick=25.*u.cm # thickness - c.Bfield.x = 2.2 * u.m # half apertures - c.Bfield.y = 3.5 * u.m - -# TimeDet + if c.magnetDesign > 3: # MISIS design + c.Bfield.YokeWidth = 0.8 * u.m # full width 200.*cm + c.Bfield.YokeDepth = 1.4 * u.m # half length 200 *cm; + c.Bfield.CoilThick = 25.0 * u.cm # thickness + c.Bfield.x = 2.2 * u.m # half apertures + c.Bfield.y = 3.5 * u.m + + # TimeDet c.TimeDet = AttrDict(z=0) c.TimeDet.dzBarRow = 1.2 * u.cm c.TimeDet.dzBarCol = 2.4 * u.cm @@ -197,92 +314,108 @@ c.TimeDet.DZ = (c.TimeDet.dzBarRow + c.TimeDet.dzBarCol + c.TimeDet.zBar) / 2 c.TimeDet.DX = 225 * u.cm c.TimeDet.DY = 325 * u.cm - c.TimeDet.z = c.Chamber6.z + c.chambers.Tub6length + c.TimeDet.DZ + 1*u.cm # safety margin - - if CaloDesign==0: - c.HcalOption = 1 - c.EcalOption = 1 - c.splitCal = 0 - elif CaloDesign==3: - c.HcalOption = 2 - c.EcalOption = 1 - c.splitCal = 0 - elif CaloDesign==2: - c.HcalOption = -1 - c.EcalOption = 2 + c.TimeDet.z = ( + c.Chamber6.z + c.chambers.Tub6length + c.TimeDet.DZ + 1 * u.cm + ) # safety margin + + if CaloDesign == 0: + c.HcalOption = 1 + c.EcalOption = 1 + c.splitCal = 0 + elif CaloDesign == 3: + c.HcalOption = 2 + c.EcalOption = 1 + c.splitCal = 0 + elif CaloDesign == 2: + c.HcalOption = -1 + c.EcalOption = 2 else: - print("CaloDesign option wrong -> ",CaloDesign) - 1/0 + print("CaloDesign option wrong -> ", CaloDesign) + 1 / 0 c.SplitCal = AttrDict(z=0) - c.SplitCal.ZStart = c.TimeDet.z + c.TimeDet.DZ + 5*u.cm - c.SplitCal.XMax = 480.*u.cm/2. #290.*u.cm #half length - c.SplitCal.YMax = 720. * u.cm / 2. #510.*u.cm * c.Yheight / (10.*u.m) #half length - c.SplitCal.Empty = 0*u.cm - c.SplitCal.BigGap = 100*u.cm - c.SplitCal.ActiveECALThickness = 0.56*u.cm - c.SplitCal.FilterECALThickness = 0.28*u.cm # 0.56*u.cm 1.757*u.cm - c.SplitCal.FilterECALThickness_first = 0.28*u.cm - c.SplitCal.ActiveHCALThickness = 90*u.cm - c.SplitCal.FilterHCALThickness = 90*u.cm + c.SplitCal.ZStart = c.TimeDet.z + c.TimeDet.DZ + 5 * u.cm + c.SplitCal.XMax = 480.0 * u.cm / 2.0 # 290.*u.cm #half length + c.SplitCal.YMax = ( + 720.0 * u.cm / 2.0 + ) # 510.*u.cm * c.Yheight / (10.*u.m) #half length + c.SplitCal.Empty = 0 * u.cm + c.SplitCal.BigGap = 100 * u.cm + c.SplitCal.ActiveECALThickness = 0.56 * u.cm + c.SplitCal.FilterECALThickness = 0.28 * u.cm # 0.56*u.cm 1.757*u.cm + c.SplitCal.FilterECALThickness_first = 0.28 * u.cm + c.SplitCal.ActiveHCALThickness = 90 * u.cm + c.SplitCal.FilterHCALThickness = 90 * u.cm c.SplitCal.nECALSamplings = 50 c.SplitCal.nHCALSamplings = 0 c.SplitCal.ActiveHCAL = 0 - c.SplitCal.FilterECALMaterial= 3 # 1=scintillator 2=Iron 3 = lead 4 =Argon - c.SplitCal.FilterHCALMaterial= 2 - c.SplitCal.ActiveECALMaterial= 1 - c.SplitCal.ActiveHCALMaterial= 1 - c.SplitCal.ActiveECAL_gas_Thickness=1.12*u.cm - c.SplitCal.num_precision_layers=1 - c.SplitCal.first_precision_layer=6 - c.SplitCal.second_precision_layer=10 - c.SplitCal.third_precision_layer=13 - c.SplitCal.ActiveECAL_gas_gap=10*u.cm + c.SplitCal.FilterECALMaterial = 3 # 1=scintillator 2=Iron 3 = lead 4 =Argon + c.SplitCal.FilterHCALMaterial = 2 + c.SplitCal.ActiveECALMaterial = 1 + c.SplitCal.ActiveHCALMaterial = 1 + c.SplitCal.ActiveECAL_gas_Thickness = 1.12 * u.cm + c.SplitCal.num_precision_layers = 1 + c.SplitCal.first_precision_layer = 6 + c.SplitCal.second_precision_layer = 10 + c.SplitCal.third_precision_layer = 13 + c.SplitCal.ActiveECAL_gas_gap = 10 * u.cm c.SplitCal.NModulesInX = 2 c.SplitCal.NModulesInY = 4 c.SplitCal.NStripsPerModule = 50 - c.SplitCal.StripHalfWidth = 3*u.cm # c.SplitCal.XMax/(c.SplitCal.NStripsPerModule*c.SplitCal.NModulesInX) - c.SplitCal.StripHalfLength = 150*u.cm # c.SplitCal.YMax/c.SplitCal.NModulesInY - c.SplitCal.SplitCalThickness=(c.SplitCal.FilterECALThickness_first-c.SplitCal.FilterECALThickness)+(c.SplitCal.FilterECALThickness+c.SplitCal.ActiveECALThickness)*c.SplitCal.nECALSamplings+c.SplitCal.BigGap - - c.ecal = AttrDict(z = c.TimeDet.z + c.TimeDet.DZ + 5*u.cm) # + c.SplitCal.StripHalfWidth = ( + 3 * u.cm + ) # c.SplitCal.XMax/(c.SplitCal.NStripsPerModule*c.SplitCal.NModulesInX) + c.SplitCal.StripHalfLength = 150 * u.cm # c.SplitCal.YMax/c.SplitCal.NModulesInY + c.SplitCal.SplitCalThickness = ( + (c.SplitCal.FilterECALThickness_first - c.SplitCal.FilterECALThickness) + + (c.SplitCal.FilterECALThickness + c.SplitCal.ActiveECALThickness) + * c.SplitCal.nECALSamplings + + c.SplitCal.BigGap + ) + + c.ecal = AttrDict(z=c.TimeDet.z + c.TimeDet.DZ + 5 * u.cm) # c.ecal.File = EcalGeoFile - hcalThickness = 232*u.cm - if c.HcalOption == 2: hcalThickness = 110*u.cm # to have same interaction length as before + hcalThickness = 232 * u.cm + if c.HcalOption == 2: + hcalThickness = 110 * u.cm # to have same interaction length as before if not c.HcalOption < 0: - c.hcal = AttrDict(z=c.ecal.z + hcalThickness/2. + 45.*u.cm ) - c.hcal.hcalSpace = hcalThickness + 5.5*u.cm - c.hcal.File = HcalGeoFile + c.hcal = AttrDict(z=c.ecal.z + hcalThickness / 2.0 + 45.0 * u.cm) + c.hcal.hcalSpace = hcalThickness + 5.5 * u.cm + c.hcal.File = HcalGeoFile else: - c.hcal = AttrDict(z=c.ecal.z) + c.hcal = AttrDict(z=c.ecal.z) if c.EcalOption == 1: - c.MuonStation0 = AttrDict(z=c.hcal.z+hcalThickness/2.+20.5*u.cm) + c.MuonStation0 = AttrDict(z=c.hcal.z + hcalThickness / 2.0 + 20.5 * u.cm) if c.EcalOption == 2: - c.MuonStation0 = AttrDict(z=c.SplitCal.ZStart+10*u.cm+c.SplitCal.SplitCalThickness) + c.MuonStation0 = AttrDict( + z=c.SplitCal.ZStart + 10 * u.cm + c.SplitCal.SplitCalThickness + ) - c.MuonStation1 = AttrDict(z=c.MuonStation0.z+1*u.m) - c.MuonStation2 = AttrDict(z=c.MuonStation0.z+2*u.m) - c.MuonStation3 = AttrDict(z=c.MuonStation0.z+3*u.m) + c.MuonStation1 = AttrDict(z=c.MuonStation0.z + 1 * u.m) + c.MuonStation2 = AttrDict(z=c.MuonStation0.z + 2 * u.m) + c.MuonStation3 = AttrDict(z=c.MuonStation0.z + 3 * u.m) - c.MuonFilter0 = AttrDict(z=c.MuonStation0.z+50.*u.cm) - c.MuonFilter1 = AttrDict(z=c.MuonStation0.z+150.*u.cm) - c.MuonFilter2 = AttrDict(z=c.MuonStation0.z+250.*u.cm) + c.MuonFilter0 = AttrDict(z=c.MuonStation0.z + 50.0 * u.cm) + c.MuonFilter1 = AttrDict(z=c.MuonStation0.z + 150.0 * u.cm) + c.MuonFilter2 = AttrDict(z=c.MuonStation0.z + 250.0 * u.cm) c.Muon = AttrDict(z=0) - c.Muon.XMax = 250. * u.cm - c.Muon.YMax = 325. * u.cm + c.Muon.XMax = 250.0 * u.cm + c.Muon.YMax = 325.0 * u.cm - c.Muon.ActiveThickness = 0.5*u.cm - c.Muon.FilterThickness = 30.*u.cm + c.Muon.ActiveThickness = 0.5 * u.cm + c.Muon.FilterThickness = 30.0 * u.cm # target absorber muon shield setup, decayVolume.length = nominal EOI length, only kept to define z=0 - c.decayVolume = AttrDict(z=0*u.cm) - c.decayVolume.length = 50*u.m + c.decayVolume = AttrDict(z=0 * u.cm) + c.decayVolume.length = 50 * u.m - c.muShield = AttrDict(z=0*u.cm) + c.muShield = AttrDict(z=0 * u.cm) c.muShieldDesign = muShieldDesign - c.muShield.Field = 1.7 # in units of Tesla expected by ShipMuonShield - c.muShield.LE = 7 * u.m # - 0.5 m air - Goliath: 4.5 m - 0.5 m air - nu-tau mu-det: 3 m - 0.5 m air. finally 10m asked by Giovanni + c.muShield.Field = 1.7 # in units of Tesla expected by ShipMuonShield + c.muShield.LE = ( + 7 * u.m + ) # - 0.5 m air - Goliath: 4.5 m - 0.5 m air - nu-tau mu-det: 3 m - 0.5 m air. finally 10m asked by Giovanni c.muShield.dZ0 = 1 * u.m c.muShieldStepGeo = muShieldStepGeo @@ -294,13 +427,13 @@ c.muShield.Field = 1.8 # Tesla c.muShield.dZ1 = 0.7 * u.m + zGap c.muShield.dZ2 = 1.7 * u.m + zGap - c.muShield.dZ3 = 2.0*u.m + zGap - c.muShield.dZ4 = 2.0*u.m + zGap - c.muShield.dZ5 = 2.75*u.m + zGap - c.muShield.dZ6 = 2.4*u.m + zGap - c.muShield.dZ7 = 3.0*u.m + zGap - c.muShield.dZ8 = 2.35*u.m + zGap - c.muShield.dXgap = 0.*u.m + c.muShield.dZ3 = 2.0 * u.m + zGap + c.muShield.dZ4 = 2.0 * u.m + zGap + c.muShield.dZ5 = 2.75 * u.m + zGap + c.muShield.dZ6 = 2.4 * u.m + zGap + c.muShield.dZ7 = 3.0 * u.m + zGap + c.muShield.dZ8 = 2.35 * u.m + zGap + c.muShield.dXgap = 0.0 * u.m elif muShieldDesign == 9: c.muShield.dZ1 = 0.35 * u.m + zGap c.muShield.dZ2 = 2.26 * u.m + zGap @@ -310,7 +443,7 @@ c.muShield.dZ6 = 2.48 * u.m + zGap c.muShield.dZ7 = 3.05 * u.m + zGap c.muShield.dZ8 = 2.42 * u.m + zGap - c.muShield.dXgap = 0. * u.m + c.muShield.dXgap = 0.0 * u.m c.muShield.half_X_max = 179 * u.cm c.muShield.half_Y_max = 317 * u.cm elif muShieldDesign == 8: @@ -320,21 +453,21 @@ print("Load geo") f = r.TFile.Open(muShieldGeo) params = r.TVectorD() - params.Read('params') + params.Read("params") f.Close() else: assert scName params = shield_db[scName] c.muShield.params = params - c.muShield.dZ1 = 0.35*u.m + zGap - c.muShield.dZ2 = 2.26*u.m + zGap + c.muShield.dZ1 = 0.35 * u.m + zGap + c.muShield.dZ2 = 2.26 * u.m + zGap c.muShield.dZ3 = params[2] c.muShield.dZ4 = params[3] c.muShield.dZ5 = params[4] c.muShield.dZ6 = params[5] c.muShield.dZ7 = params[6] c.muShield.dZ8 = params[7] - c.muShield.dXgap = 0.*u.m + c.muShield.dXgap = 0.0 * u.m offset = 7 c.muShield.half_X_max = 0 @@ -346,232 +479,293 @@ h_r = params[offset + index * 6 + 4] g_l = params[offset + index * 6 + 5] g_r = params[offset + index * 6 + 6] - c.muShield.half_X_max = max(c.muShield.half_X_max, 2 * f_l + g_l, 2 * f_r + g_r) + c.muShield.half_X_max = max( + c.muShield.half_X_max, 2 * f_l + g_l, 2 * f_r + g_r + ) c.muShield.half_Y_max = max(c.muShield.half_Y_max, h_l + f_l, h_r + f_r) c.muShield.half_X_max += 15 * u.cm c.muShield.half_Y_max += 15 * u.cm else: raise NotImplementedError(f"muShieldDesign {muShieldDesign} not supported") - c.muShield.length = 2 * ( - c.muShield.dZ1 + c.muShield.dZ2 + - c.muShield.dZ3 + c.muShield.dZ4 + - c.muShield.dZ5 + c.muShield.dZ6 + - c.muShield.dZ7 + c.muShield.dZ8 - ) + c.muShield.LE - c.muShield.z = -(c.decayVolume.length + c.muShield.length) / 2. - - c.hadronAbsorber = AttrDict(z=0*u.cm) - c.hadronAbsorber.length = 0*u.m # magnetized, counted inside muonshield - c.hadronAbsorber.z = c.muShield.z - c.muShield.length/2. - c.hadronAbsorber.length/2. + c.muShield.length = ( + 2 + * ( + c.muShield.dZ1 + + c.muShield.dZ2 + + c.muShield.dZ3 + + c.muShield.dZ4 + + c.muShield.dZ5 + + c.muShield.dZ6 + + c.muShield.dZ7 + + c.muShield.dZ8 + ) + + c.muShield.LE + ) + c.muShield.z = -(c.decayVolume.length + c.muShield.length) / 2.0 + + c.hadronAbsorber = AttrDict(z=0 * u.cm) + c.hadronAbsorber.length = 0 * u.m # magnetized, counted inside muonshield + c.hadronAbsorber.z = ( + c.muShield.z - c.muShield.length / 2.0 - c.hadronAbsorber.length / 2.0 + ) c.hadronAbsorber.WithConstField = True c.muShield.WithConstField = True - c.target = AttrDict(z=0*u.cm) - c.targetOpt = targetOpt + c.target = AttrDict(z=0 * u.cm) + c.targetOpt = targetOpt if targetOpt < 10: - c.target.sl = 1*u.cm # air slit total length - c.target.length = 50*u.cm + c.target.sl * (targetOpt-1) + c.target.sl = 1 * u.cm # air slit total length + c.target.length = 50 * u.cm + c.target.sl * (targetOpt - 1) else: - # material,length - c.target.M1 = "molybdenum" - c.target.L1 = 8.*u.cm - c.target.M2 = "molybdenum" - c.target.L2 = 2.5*u.cm - c.target.M3 = "molybdenum" - c.target.L3 = 2.5*u.cm - c.target.M4 = "molybdenum" - c.target.L4 = 2.5*u.cm - c.target.M5 = "molybdenum" - c.target.L5 = 2.5*u.cm - c.target.M6 = "molybdenum" - c.target.L6 = 2.5*u.cm - c.target.M7 = "molybdenum" - c.target.L7 = 2.5*u.cm - c.target.M8 = "molybdenum" - c.target.L8 = 2.5*u.cm - c.target.M9 = "molybdenum" - c.target.L9 = 5.0*u.cm - c.target.M10 = "molybdenum" - c.target.L10 = 5.0*u.cm - c.target.M11 = "molybdenum" - c.target.L11 = 6.5*u.cm - c.target.M12 = "molybdenum" - c.target.L12 = 8.*u.cm - c.target.M13 = "molybdenum" - c.target.L13 = 8.*u.cm - c.target.M14 = "tungsten" - c.target.L14 = 5.*u.cm - c.target.M15 = "tungsten" - c.target.L15 = 8.*u.cm - c.target.M16 = "tungsten" - c.target.L16 = 10.*u.cm - c.target.M17 = "tungsten" - c.target.L17 = 20.*u.cm - c.target.M18 = "tungsten" - c.target.L18 = 35.*u.cm - c.target.sl = 0.5*u.cm # H20 slit *17 times - c.target.xy = 30.*u.cm # full length in x and y - c.target.length = 17*c.target.sl + c.target.L1 + 7*c.target.L2 + 3*c.target.L9 + c.target.L11 + 3*c.target.L12 + c.target.L16 + c.target.L17 + c.target.L18 + # material,length + c.target.M1 = "molybdenum" + c.target.L1 = 8.0 * u.cm + c.target.M2 = "molybdenum" + c.target.L2 = 2.5 * u.cm + c.target.M3 = "molybdenum" + c.target.L3 = 2.5 * u.cm + c.target.M4 = "molybdenum" + c.target.L4 = 2.5 * u.cm + c.target.M5 = "molybdenum" + c.target.L5 = 2.5 * u.cm + c.target.M6 = "molybdenum" + c.target.L6 = 2.5 * u.cm + c.target.M7 = "molybdenum" + c.target.L7 = 2.5 * u.cm + c.target.M8 = "molybdenum" + c.target.L8 = 2.5 * u.cm + c.target.M9 = "molybdenum" + c.target.L9 = 5.0 * u.cm + c.target.M10 = "molybdenum" + c.target.L10 = 5.0 * u.cm + c.target.M11 = "molybdenum" + c.target.L11 = 6.5 * u.cm + c.target.M12 = "molybdenum" + c.target.L12 = 8.0 * u.cm + c.target.M13 = "molybdenum" + c.target.L13 = 8.0 * u.cm + c.target.M14 = "tungsten" + c.target.L14 = 5.0 * u.cm + c.target.M15 = "tungsten" + c.target.L15 = 8.0 * u.cm + c.target.M16 = "tungsten" + c.target.L16 = 10.0 * u.cm + c.target.M17 = "tungsten" + c.target.L17 = 20.0 * u.cm + c.target.M18 = "tungsten" + c.target.L18 = 35.0 * u.cm + c.target.sl = 0.5 * u.cm # H20 slit *17 times + c.target.xy = 30.0 * u.cm # full length in x and y + c.target.length = ( + 17 * c.target.sl + + c.target.L1 + + 7 * c.target.L2 + + 3 * c.target.L9 + + c.target.L11 + + 3 * c.target.L12 + + c.target.L16 + + c.target.L17 + + c.target.L18 + ) # interaction point, start of target - c.target.z = c.hadronAbsorber.z - c.hadronAbsorber.length/2. - c.target.length/2. - c.target.z0 = c.target.z - c.target.length/2. - -# for the digitizing step - c.strawtubes.v_drift = 1./(30*u.ns/u.mm) # for baseline NA62 5mm radius straws) - c.strawtubes.sigma_spatial = 0.012*u.cm # according to Massi's TP section -# size of straws - c.strawtubes.StrawLength = c.xMax + c.target.z = ( + c.hadronAbsorber.z - c.hadronAbsorber.length / 2.0 - c.target.length / 2.0 + ) + c.target.z0 = c.target.z - c.target.length / 2.0 + + # for the digitizing step + c.strawtubes.v_drift = 1.0 / ( + 30 * u.ns / u.mm + ) # for baseline NA62 5mm radius straws) + c.strawtubes.sigma_spatial = 0.012 * u.cm # according to Massi's TP section + # size of straws + c.strawtubes.StrawLength = c.xMax if tankDesign == 5: - zF = c.target.z0+c.zFocusX - c.strawtubes.StrawLength12 = c.xMax*(c.TrackStation1.z-2*c.strawtubes.DeltazView-zF)/(z4-zF) - c.strawtubes.StrawLengthVeto = c.xMax*(c.vetoStation.z-c.strawtubes.DeltazView-zF)/(z4-zF) - zF = c.target.z0+c.zFocusY - c.strawtubes.vetoydim = c.Yheight/2.*(c.vetoStation.z-c.strawtubes.DeltazView-zF)/(z4-zF) - c.strawtubes.tr12ydim = c.Yheight/2.*(c.TrackStation1.z-2*c.strawtubes.DeltazView-zF)/(z4-zF) - c.strawtubes.tr34ydim = int(c.Yheight/2.) + zF = c.target.z0 + c.zFocusX + c.strawtubes.StrawLength12 = ( + c.xMax * (c.TrackStation1.z - 2 * c.strawtubes.DeltazView - zF) / (z4 - zF) + ) + c.strawtubes.StrawLengthVeto = ( + c.xMax * (c.vetoStation.z - c.strawtubes.DeltazView - zF) / (z4 - zF) + ) + zF = c.target.z0 + c.zFocusY + c.strawtubes.vetoydim = ( + c.Yheight + / 2.0 + * (c.vetoStation.z - c.strawtubes.DeltazView - zF) + / (z4 - zF) + ) + c.strawtubes.tr12ydim = ( + c.Yheight + / 2.0 + * (c.TrackStation1.z - 2 * c.strawtubes.DeltazView - zF) + / (z4 - zF) + ) + c.strawtubes.tr34ydim = int(c.Yheight / 2.0) else: - c.strawtubes.StrawLength12 = c.strawtubes.StrawLength - c.strawtubes.StrawLengthVeto = c.strawtubes.StrawLength - if tankDesign > 5: c.strawtubes.StrawLengthVeto = 0.5 # switch of veto strawtracker - c.strawtubes.vetoydim = int(c.Yheight/2.) - c.strawtubes.tr12ydim = int(c.Yheight/2.) - c.strawtubes.tr34ydim = int(c.Yheight/2.) - - #Parameters for tau neutrino target Magnet - c.EmuMagnet = AttrDict(z=0*u.cm) - c.EmuMagnet.MagneticField = False #activates the magnetic field - c.EmuMagnet.GapDown = 25*u.cm - if (nuTauTargetDesign!=2 and nuTauTargetDesign!= 4) : + c.strawtubes.StrawLength12 = c.strawtubes.StrawLength + c.strawtubes.StrawLengthVeto = c.strawtubes.StrawLength + if tankDesign > 5: + c.strawtubes.StrawLengthVeto = 0.5 # switch of veto strawtracker + c.strawtubes.vetoydim = int(c.Yheight / 2.0) + c.strawtubes.tr12ydim = int(c.Yheight / 2.0) + c.strawtubes.tr34ydim = int(c.Yheight / 2.0) + + # Parameters for tau neutrino target Magnet + c.EmuMagnet = AttrDict(z=0 * u.cm) + c.EmuMagnet.MagneticField = False # activates the magnetic field + c.EmuMagnet.GapDown = 25 * u.cm + if nuTauTargetDesign != 2 and nuTauTargetDesign != 4: c.EmuMagnet.Design = nuTauTargetDesign - c.EmuMagnet.B=1.25*u.tesla - if c.EmuMagnet.Design==3: - scale=1. - c.EmuMagnet.WithConstField=False #now loaded field map - c.EmuMagnet.X = scale*2.2*u.m - c.EmuMagnet.Y = scale*4.0*u.m - c.EmuMagnet.Z = 7.2*u.m - c.EmuMagnet.BaseX = scale*c.EmuMagnet.X - c.EmuMagnet.BaseY = scale*0.7*u.m - c.EmuMagnet.BaseZ = scale*c.EmuMagnet.Z - c.EmuMagnet.GapDown = 25*u.cm - c.EmuMagnet.GapUp = 27*u.cm - #c.EmuMagnet.ColX =scale*25*u.cm - c.EmuMagnet.ColX = scale*60*u.cm - c.EmuMagnet.ColY = scale*c.EmuMagnet.Y - 2 *scale * c.EmuMagnet.BaseY #avoid overlapping between bases and columns - c.EmuMagnet.ColZ = scale*c.EmuMagnet.Z - c.EmuMagnet.CutLength = scale * 45*u.cm - c.EmuMagnet.CutHeight = scale * 144*u.cm - c.EmuMagnet.CoilX = c.EmuMagnet.X-2*c.EmuMagnet.ColX - c.EmuMagnet.CoilY = 50 *u.cm - c.EmuMagnet.Height1 = c.EmuMagnet.Y-2*c.EmuMagnet.BaseY - c.EmuMagnet.Height2 = c.EmuMagnet.Height1-2*c.EmuMagnet.CoilY - c.EmuMagnet.Thickness = scale*40*u.cm - c.EmuMagnet.PillarX = 0.5*u.m - c.EmuMagnet.PillarZ = 0.5*u.m - c.EmuMagnet.PillarY = 10*u.m - c.EmuMagnet.Y/2 - 0.1*u.mm - c.cave.floorHeightMuonShield - if c.EmuMagnet.Design<2: - c.EmuMagnet.WithConstField=True #older geometries still use constant fields - c.EmuMagnet.Z = 4.5*u.m - c.EmuMagnet.GapUp = 27*u.cm + c.EmuMagnet.B = 1.25 * u.tesla + if c.EmuMagnet.Design == 3: + scale = 1.0 + c.EmuMagnet.WithConstField = False # now loaded field map + c.EmuMagnet.X = scale * 2.2 * u.m + c.EmuMagnet.Y = scale * 4.0 * u.m + c.EmuMagnet.Z = 7.2 * u.m + c.EmuMagnet.BaseX = scale * c.EmuMagnet.X + c.EmuMagnet.BaseY = scale * 0.7 * u.m + c.EmuMagnet.BaseZ = scale * c.EmuMagnet.Z + c.EmuMagnet.GapDown = 25 * u.cm + c.EmuMagnet.GapUp = 27 * u.cm + # c.EmuMagnet.ColX =scale*25*u.cm + c.EmuMagnet.ColX = scale * 60 * u.cm + c.EmuMagnet.ColY = ( + scale * c.EmuMagnet.Y - 2 * scale * c.EmuMagnet.BaseY + ) # avoid overlapping between bases and columns + c.EmuMagnet.ColZ = scale * c.EmuMagnet.Z + c.EmuMagnet.CutLength = scale * 45 * u.cm + c.EmuMagnet.CutHeight = scale * 144 * u.cm + c.EmuMagnet.CoilX = c.EmuMagnet.X - 2 * c.EmuMagnet.ColX + c.EmuMagnet.CoilY = 50 * u.cm + c.EmuMagnet.Height1 = c.EmuMagnet.Y - 2 * c.EmuMagnet.BaseY + c.EmuMagnet.Height2 = c.EmuMagnet.Height1 - 2 * c.EmuMagnet.CoilY + c.EmuMagnet.Thickness = scale * 40 * u.cm + c.EmuMagnet.PillarX = 0.5 * u.m + c.EmuMagnet.PillarZ = 0.5 * u.m + c.EmuMagnet.PillarY = ( + 10 * u.m - c.EmuMagnet.Y / 2 - 0.1 * u.mm - c.cave.floorHeightMuonShield + ) + if c.EmuMagnet.Design < 2: + c.EmuMagnet.WithConstField = ( + True # older geometries still use constant fields + ) + c.EmuMagnet.Z = 4.5 * u.m + c.EmuMagnet.GapUp = 27 * u.cm if c.EmuMagnet.Design == 1: - scale = 1. - c.EmuMagnet.X = scale*1.7*u.m - c.EmuMagnet.Y = scale*3.2*u.m - c.EmuMagnet.Radius = scale*1.1*u.m - c.EmuMagnet.Height1 = scale*30*u.cm - c.EmuMagnet.Height2 = scale*c.EmuMagnet.Height1 - c.EmuMagnet.Distance = scale*c.EmuMagnet.X-2*c.EmuMagnet.Height1 - c.EmuMagnet.ColX =scale*c.EmuMagnet.Distance - c.EmuMagnet.ColY = scale*0.7*u.m - c.EmuMagnet.ColZ = 0.9*u.m - c.EmuMagnet.BaseX = scale*c.EmuMagnet.Height1 - c.EmuMagnet.BaseY = scale*c.EmuMagnet.Y - c.EmuMagnet.BaseZ = scale*c.EmuMagnet.Z - c.EmuMagnet.PillarX = 0.5*u.m - c.EmuMagnet.PillarZ = 0.5*u.m - c.EmuMagnet.PillarY = 10*u.m - c.EmuMagnet.Y/2 - 0.1*u.mm - c.cave.floorHeightMuonShield - #10m is the half-height of the cave - if c.EmuMagnet.Design == 0: #TP MagnetConfig - c.EmuMagnet.X = 3.6*u.m - c.EmuMagnet.Radius = 1*u.m - c.EmuMagnet.Height1 = 45*u.cm - c.EmuMagnet.Height2 = 30*u.cm - c.EmuMagnet.Distance = 105*u.cm - c.EmuMagnet.BaseX = c.EmuMagnet.X - c.EmuMagnet.BaseY = 57*u.cm - c.EmuMagnet.BaseZ = c.EmuMagnet.Z - c.EmuMagnet.ColX = 0*u.m - c.EmuMagnet.ColY = c.EmuMagnet.BaseY - c.EmuMagnet.ColZ = 0*u.m - c.EmuMagnet.Y = 2*c.EmuMagnet.BaseY+c.EmuMagnet.Height1+c.EmuMagnet.Height2+c.EmuMagnet.Distance - c.EmuMagnet.PillarX = 0 *u.m - c.EmuMagnet.PillarZ = 0 * u.m - c.EmuMagnet.PillarY = 0 * u.m - - - - - #Parameters for tau muon detector - c.tauMudet = AttrDict(z=0*u.cm) - if nuTauTargetDesign<=2: + scale = 1.0 + c.EmuMagnet.X = scale * 1.7 * u.m + c.EmuMagnet.Y = scale * 3.2 * u.m + c.EmuMagnet.Radius = scale * 1.1 * u.m + c.EmuMagnet.Height1 = scale * 30 * u.cm + c.EmuMagnet.Height2 = scale * c.EmuMagnet.Height1 + c.EmuMagnet.Distance = scale * c.EmuMagnet.X - 2 * c.EmuMagnet.Height1 + c.EmuMagnet.ColX = scale * c.EmuMagnet.Distance + c.EmuMagnet.ColY = scale * 0.7 * u.m + c.EmuMagnet.ColZ = 0.9 * u.m + c.EmuMagnet.BaseX = scale * c.EmuMagnet.Height1 + c.EmuMagnet.BaseY = scale * c.EmuMagnet.Y + c.EmuMagnet.BaseZ = scale * c.EmuMagnet.Z + c.EmuMagnet.PillarX = 0.5 * u.m + c.EmuMagnet.PillarZ = 0.5 * u.m + c.EmuMagnet.PillarY = ( + 10 * u.m - c.EmuMagnet.Y / 2 - 0.1 * u.mm - c.cave.floorHeightMuonShield + ) + # 10m is the half-height of the cave + if c.EmuMagnet.Design == 0: # TP MagnetConfig + c.EmuMagnet.X = 3.6 * u.m + c.EmuMagnet.Radius = 1 * u.m + c.EmuMagnet.Height1 = 45 * u.cm + c.EmuMagnet.Height2 = 30 * u.cm + c.EmuMagnet.Distance = 105 * u.cm + c.EmuMagnet.BaseX = c.EmuMagnet.X + c.EmuMagnet.BaseY = 57 * u.cm + c.EmuMagnet.BaseZ = c.EmuMagnet.Z + c.EmuMagnet.ColX = 0 * u.m + c.EmuMagnet.ColY = c.EmuMagnet.BaseY + c.EmuMagnet.ColZ = 0 * u.m + c.EmuMagnet.Y = ( + 2 * c.EmuMagnet.BaseY + + c.EmuMagnet.Height1 + + c.EmuMagnet.Height2 + + c.EmuMagnet.Distance + ) + c.EmuMagnet.PillarX = 0 * u.m + c.EmuMagnet.PillarZ = 0 * u.m + c.EmuMagnet.PillarY = 0 * u.m + + # Parameters for tau muon detector + c.tauMudet = AttrDict(z=0 * u.cm) + if nuTauTargetDesign <= 2: c.tauMudet.NFe = 12 - c.tauMudet.NRpc= 11 - if nuTauTargetDesign==0: #TP - c.tauMudet.YRyoke = 90*u.cm - c.tauMudet.YRyoke_s = c.tauMudet.YRyoke-30*u.cm - c.tauMudet.Xtot = 4.*u.m - c.tauMudet.YFe = 8*u.m - c.tauMudet.Ytot = c.tauMudet.YFe + 2*c.tauMudet.YRyoke - c.tauMudet.PillarX = 0*u.cm - c.tauMudet.PillarZ = 0*u.cm - c.tauMudet.PillarY=0 *u.cm - if nuTauTargetDesign>=1: #NEW with Davide or without magnet - scaleMudet=1.0 - c.tauMudet.YRyoke = scaleMudet*40*u.cm - c.tauMudet.YRyoke_s = scaleMudet*27*u.cm - c.tauMudet.Xtot = scaleMudet*1.5*u.m - c.tauMudet.Ytot = scaleMudet*3.8*u.m - c.tauMudet.YFe = c.tauMudet.Ytot - 2*c.tauMudet.YRyoke - c.tauMudet.PillarX = 40*u.cm - c.tauMudet.PillarZ = 50*u.cm - c.tauMudet.PillarY = 10*u.m - c.cave.floorHeightMuonShield - c.tauMudet.Ytot/2 -10*u.cm - 0.1*u.mm - c.tauMudet.XRyoke = c.tauMudet.Xtot+20*u.cm + c.tauMudet.NRpc = 11 + if nuTauTargetDesign == 0: # TP + c.tauMudet.YRyoke = 90 * u.cm + c.tauMudet.YRyoke_s = c.tauMudet.YRyoke - 30 * u.cm + c.tauMudet.Xtot = 4.0 * u.m + c.tauMudet.YFe = 8 * u.m + c.tauMudet.Ytot = c.tauMudet.YFe + 2 * c.tauMudet.YRyoke + c.tauMudet.PillarX = 0 * u.cm + c.tauMudet.PillarZ = 0 * u.cm + c.tauMudet.PillarY = 0 * u.cm + if nuTauTargetDesign >= 1: # NEW with Davide or without magnet + scaleMudet = 1.0 + c.tauMudet.YRyoke = scaleMudet * 40 * u.cm + c.tauMudet.YRyoke_s = scaleMudet * 27 * u.cm + c.tauMudet.Xtot = scaleMudet * 1.5 * u.m + c.tauMudet.Ytot = scaleMudet * 3.8 * u.m + c.tauMudet.YFe = c.tauMudet.Ytot - 2 * c.tauMudet.YRyoke + c.tauMudet.PillarX = 40 * u.cm + c.tauMudet.PillarZ = 50 * u.cm + c.tauMudet.PillarY = ( + 10 * u.m + - c.cave.floorHeightMuonShield + - c.tauMudet.Ytot / 2 + - 10 * u.cm + - 0.1 * u.mm + ) + c.tauMudet.XRyoke = c.tauMudet.Xtot + 20 * u.cm c.tauMudet.XRyoke_s = c.tauMudet.Xtot - c.tauMudet.Ztot = 4.76*u.m + c.tauMudet.Ztot = 4.76 * u.m c.tauMudet.XFe = c.tauMudet.Xtot c.tauMudet.XRpc = c.tauMudet.Xtot - c.tauMudet.YRpc = c.tauMudet.YFe-20*u.cm - c.tauMudet.ZFe = 5.*u.cm - c.tauMudet.ZRpc = 2.*u.cm - c.tauMudet.ZArm = c.tauMudet.NFe*c.tauMudet.ZFe + c.tauMudet.NRpc*c.tauMudet.ZRpc - c.tauMudet.GapD = 27.*u.cm - c.tauMudet.GapM = 122*u.cm - c.tauMudet.ZRyoke = 2*c.tauMudet.ZArm + c.tauMudet.GapM + c.tauMudet.YRpc = c.tauMudet.YFe - 20 * u.cm + c.tauMudet.ZFe = 5.0 * u.cm + c.tauMudet.ZRpc = 2.0 * u.cm + c.tauMudet.ZArm = ( + c.tauMudet.NFe * c.tauMudet.ZFe + c.tauMudet.NRpc * c.tauMudet.ZRpc + ) + c.tauMudet.GapD = 27.0 * u.cm + c.tauMudet.GapM = 122 * u.cm + c.tauMudet.ZRyoke = 2 * c.tauMudet.ZArm + c.tauMudet.GapM c.tauMudet.ZRyoke_s = c.tauMudet.GapM - c.tauMudet.CoilH = 5*u.cm - c.tauMudet.CoilW = 2*u.cm - c.tauMudet.CoilG = 2*u.cm - c.tauMudet.N =20 - c.tauMudet.zMudetC = -c.decayVolume.length/2. - c.tauMudet.GapD - c.tauMudet.Ztot/2 + c.tauMudet.CoilH = 5 * u.cm + c.tauMudet.CoilW = 2 * u.cm + c.tauMudet.CoilG = 2 * u.cm + c.tauMudet.N = 20 + c.tauMudet.zMudetC = ( + -c.decayVolume.length / 2.0 - c.tauMudet.GapD - c.tauMudet.Ztot / 2 + ) c.tauMudet.B = 1.5 * u.tesla - if nuTauTargetDesign==3: - scaleMudet=1. - c.tauMudet.NFethick = 4 #upstream slabs, more thick - c.tauMudet.NFethin = 4 #downstream slabs, less thick - c.tauMudet.NRpc= 8 + if nuTauTargetDesign == 3: + scaleMudet = 1.0 + c.tauMudet.NFethick = 4 # upstream slabs, more thick + c.tauMudet.NFethin = 4 # downstream slabs, less thick + c.tauMudet.NRpc = 8 - c.tauMudet.XFe = scaleMudet*1.950*u.m #layer dimensions, excluded supports - c.tauMudet.YFe = scaleMudet*3.850*u.m + c.tauMudet.XFe = scaleMudet * 1.950 * u.m # layer dimensions, excluded supports + c.tauMudet.YFe = scaleMudet * 3.850 * u.m - c.tauMudet.ZFethick = 15.*u.cm - c.tauMudet.ZFethin = 10.* u.cm + c.tauMudet.ZFethick = 15.0 * u.cm + c.tauMudet.ZFethin = 10.0 * u.cm c.tauMudet.XRpc = c.tauMudet.XFe c.tauMudet.YRpc = c.tauMudet.YFe - c.tauMudet.ZRpc = 8.*u.cm - #support structure + c.tauMudet.ZRpc = 8.0 * u.cm + # support structure c.tauMudet.UpperSupportX = 30 * u.cm c.tauMudet.UpperSupportY = 32 * u.cm c.tauMudet.LowerSupportX = 30 * u.cm @@ -579,195 +773,259 @@ c.tauMudet.LateralSupportX = 30.5 * u.cm c.tauMudet.LateralSupportY = 32 * u.cm - c.tauMudet.Xtot = c.tauMudet.XFe + 2 * c.tauMudet.LateralSupportX#now we need to include also supports. - c.tauMudet.Ytot = c.tauMudet.YFe + c.tauMudet.UpperSupportY + c.tauMudet.LowerSupportY - c.tauMudet.Ztot = c.tauMudet.NRpc*c.tauMudet.ZRpc+c.tauMudet.NFethick*c.tauMudet.ZFethick + c.tauMudet.NFethin*c.tauMudet.ZFethin - - #c.tauMudet.zMudetC = -c.decayVolume.length/2. - c.tauMudet.Ztot/2 - #c.tauMudet.zMudetC = c.Chamber1.z -c.chambers.Tub1length - c.tauMudet.Ztot/2 -31*u.cm; - c.tauMudet.zMudetC = c.Chamber1.z -c.chambers.Tub1length - c.tauMudet.Ztot/2 -31*u.cm; - #lateral cuts + c.tauMudet.Xtot = ( + c.tauMudet.XFe + 2 * c.tauMudet.LateralSupportX + ) # now we need to include also supports. + c.tauMudet.Ytot = ( + c.tauMudet.YFe + c.tauMudet.UpperSupportY + c.tauMudet.LowerSupportY + ) + c.tauMudet.Ztot = ( + c.tauMudet.NRpc * c.tauMudet.ZRpc + + c.tauMudet.NFethick * c.tauMudet.ZFethick + + c.tauMudet.NFethin * c.tauMudet.ZFethin + ) + + # c.tauMudet.zMudetC = -c.decayVolume.length/2. - c.tauMudet.Ztot/2 + # c.tauMudet.zMudetC = c.Chamber1.z -c.chambers.Tub1length - c.tauMudet.Ztot/2 -31*u.cm; + c.tauMudet.zMudetC = ( + c.Chamber1.z - c.chambers.Tub1length - c.tauMudet.Ztot / 2 - 31 * u.cm + ) + # lateral cuts c.tauMudet.CutHeight = 78.548 * u.cm - c.tauMudet.CutLength = (c.tauMudet.CutHeight / 2) / (r.TMath.Tan(r.TMath.DegToRad() * 55)) - #upper cover + c.tauMudet.CutLength = (c.tauMudet.CutHeight / 2) / ( + r.TMath.Tan(r.TMath.DegToRad() * 55) + ) + # upper cover c.tauMudet.XCov = c.tauMudet.XFe - c.tauMudet.YCov = 6*u.cm - c.tauMudet.ZCov = c.tauMudet.NFethick*c.tauMudet.ZFethick+c.tauMudet.NRpc*c.tauMudet.ZRpc+c.tauMudet.NFethin*c.tauMudet.ZFethin - - c.tauMudet.YSpacing = 28.5*u.cm - #lateral cover - c.tauMudet.XLateral = 7*u.cm + c.tauMudet.YCov = 6 * u.cm + c.tauMudet.ZCov = ( + c.tauMudet.NFethick * c.tauMudet.ZFethick + + c.tauMudet.NRpc * c.tauMudet.ZRpc + + c.tauMudet.NFethin * c.tauMudet.ZFethin + ) + + c.tauMudet.YSpacing = 28.5 * u.cm + # lateral cover + c.tauMudet.XLateral = 7 * u.cm c.tauMudet.YLateral = c.tauMudet.LateralSupportY c.tauMudet.ZLateral = c.tauMudet.ZCov - #lateral cross - c.tauMudet.XCross = 2*u.cm - c.tauMudet.YCross = c.tauMudet.YFe-2*c.tauMudet.YLateral-2*c.tauMudet.YSpacing - 8*u.cm + # lateral cross + c.tauMudet.XCross = 2 * u.cm + c.tauMudet.YCross = ( + c.tauMudet.YFe + - 2 * c.tauMudet.YLateral + - 2 * c.tauMudet.YSpacing + - 8 * u.cm + ) c.tauMudet.ZCross = c.tauMudet.ZCov - c.tauMudet.WidthArm = 2* u.cm - #RPC frame - c.tauMudet.XRpc_outer = 284.5*u.cm - c.tauMudet.YRpc_outer = 428.2*u.cm - c.tauMudet.ZRpc_outer = 2.2*u.cm - c.tauMudet.XRpc_inner = 190*u.cm - c.tauMudet.YRpc_inner = 372*u.cm - c.tauMudet.ZRpc_inner = 1.7*u.cm - #RPC Gap + c.tauMudet.WidthArm = 2 * u.cm + # RPC frame + c.tauMudet.XRpc_outer = 284.5 * u.cm + c.tauMudet.YRpc_outer = 428.2 * u.cm + c.tauMudet.ZRpc_outer = 2.2 * u.cm + c.tauMudet.XRpc_inner = 190 * u.cm + c.tauMudet.YRpc_inner = 372 * u.cm + c.tauMudet.ZRpc_inner = 1.7 * u.cm + # RPC Gap c.tauMudet.XRpcGap = c.tauMudet.XRpc_inner - c.tauMudet.YRpcGap = 120*u.cm - c.tauMudet.ZRpcGap = 0.2*u.cm - - c.tauMudet.PillarX = 40*u.cm - c.tauMudet.PillarZ = 50*u.cm - c.tauMudet.PillarY = 10*u.m - c.cave.floorHeightMuonShield - c.tauMudet.Ytot/2 - 0.1*u.mm - if nuTauTargetDesign<4: - c.tauMudet.XGas = c.tauMudet.XRpc - c.tauMudet.YGas = c.tauMudet.YRpc - c.tauMudet.ZGas = 1*u.mm - c.tauMudet.XStrip = c.tauMudet.XRpc - c.tauMudet.YStrip = c.tauMudet.YRpc - c.tauMudet.ZStrip = 0.02*u.mm - c.tauMudet.XPet = c.tauMudet.XRpc - c.tauMudet.YPet = c.tauMudet.YRpc - c.tauMudet.ZPet = 0.1*u.mm - c.tauMudet.XEle = c.tauMudet.XRpc - c.tauMudet.YEle = c.tauMudet.YRpc - c.tauMudet.ZEle = 1*u.mm - - if nuTauTargetDesign==4: - c.tauMudet.XRpc = 80 *u.cm - c.tauMudet.YRpc = 140 *u.cm - c.tauMudet.ZRpc = 8 *u.cm - #magnetized region - c.tauMudet.XRyoke = 30 * u.cm - c.tauMudet.YRyoke = 25 * u.cm - c.tauMudet.CoilH = 23 * u.cm - c.tauMudet.CoilW = c.tauMudet.XRpc - - c.tauMudet.Xtot = c.tauMudet.XRpc + 2*c.tauMudet.XRyoke - c.tauMudet.Ytot = c.tauMudet.YRpc + 2*(c.tauMudet.CoilH+c.tauMudet.YRyoke) - c.tauMudet.GapM = 20 * u.cm #magnetized region length, gap between sepctrometer planes - - c.tauMudet.Ztot = 3 * u.m #space allocated to Muon spectrometer - c.tauMudet.ZRyoke = c.tauMudet.Ztot - c.tauMudet.B = 1.0 * u.tesla #magnetic field is back in MuFilter! - c.tauMudet.zMudetC = c.Chamber1.z -c.chambers.Tub1length - c.tauMudet.Ztot/2 -31*u.cm - - if nuTauTargetDesign==0 or nuTauTargetDesign==1: - c.EmuMagnet.zC = -c.decayVolume.length/2. - c.tauMudet.GapD - c.tauMudet.Ztot - c.EmuMagnet.GapDown - c.EmuMagnet.Z/2 - - if nuTauTargetDesign==3: - c.EmuMagnet.zC = c.tauMudet.zMudetC - c.tauMudet.Ztot/2 - c.EmuMagnet.GapDown - c.EmuMagnet.Z/2 - - #tau Bricks - c.NuTauTarget = AttrDict(z=0*u.cm) + c.tauMudet.YRpcGap = 120 * u.cm + c.tauMudet.ZRpcGap = 0.2 * u.cm + + c.tauMudet.PillarX = 40 * u.cm + c.tauMudet.PillarZ = 50 * u.cm + c.tauMudet.PillarY = ( + 10 * u.m - c.cave.floorHeightMuonShield - c.tauMudet.Ytot / 2 - 0.1 * u.mm + ) + if nuTauTargetDesign < 4: + c.tauMudet.XGas = c.tauMudet.XRpc + c.tauMudet.YGas = c.tauMudet.YRpc + c.tauMudet.ZGas = 1 * u.mm + c.tauMudet.XStrip = c.tauMudet.XRpc + c.tauMudet.YStrip = c.tauMudet.YRpc + c.tauMudet.ZStrip = 0.02 * u.mm + c.tauMudet.XPet = c.tauMudet.XRpc + c.tauMudet.YPet = c.tauMudet.YRpc + c.tauMudet.ZPet = 0.1 * u.mm + c.tauMudet.XEle = c.tauMudet.XRpc + c.tauMudet.YEle = c.tauMudet.YRpc + c.tauMudet.ZEle = 1 * u.mm + + if nuTauTargetDesign == 4: + c.tauMudet.XRpc = 80 * u.cm + c.tauMudet.YRpc = 140 * u.cm + c.tauMudet.ZRpc = 8 * u.cm + # magnetized region + c.tauMudet.XRyoke = 30 * u.cm + c.tauMudet.YRyoke = 25 * u.cm + c.tauMudet.CoilH = 23 * u.cm + c.tauMudet.CoilW = c.tauMudet.XRpc + + c.tauMudet.Xtot = c.tauMudet.XRpc + 2 * c.tauMudet.XRyoke + c.tauMudet.Ytot = c.tauMudet.YRpc + 2 * (c.tauMudet.CoilH + c.tauMudet.YRyoke) + c.tauMudet.GapM = ( + 20 * u.cm + ) # magnetized region length, gap between sepctrometer planes + + c.tauMudet.Ztot = 3 * u.m # space allocated to Muon spectrometer + c.tauMudet.ZRyoke = c.tauMudet.Ztot + c.tauMudet.B = 1.0 * u.tesla # magnetic field is back in MuFilter! + c.tauMudet.zMudetC = ( + c.Chamber1.z - c.chambers.Tub1length - c.tauMudet.Ztot / 2 - 31 * u.cm + ) + + if nuTauTargetDesign == 0 or nuTauTargetDesign == 1: + c.EmuMagnet.zC = ( + -c.decayVolume.length / 2.0 + - c.tauMudet.GapD + - c.tauMudet.Ztot + - c.EmuMagnet.GapDown + - c.EmuMagnet.Z / 2 + ) + + if nuTauTargetDesign == 3: + c.EmuMagnet.zC = ( + c.tauMudet.zMudetC + - c.tauMudet.Ztot / 2 + - c.EmuMagnet.GapDown + - c.EmuMagnet.Z / 2 + ) + + # tau Bricks + c.NuTauTarget = AttrDict(z=0 * u.cm) c.NuTauTarget.Design = nuTauTargetDesign - if nuTauTargetDesign!=2 and nuTauTargetDesign!=4: + if nuTauTargetDesign != 2 and nuTauTargetDesign != 4: c.NuTauTarget.zC = c.EmuMagnet.zC - if nuTauTargetDesign==2: - c.NuTauTarget.zC = -c.decayVolume.length/2. - c.tauMudet.GapD - c.tauMudet.Ztot -2.5*u.m - - if c.NuTauTarget.Design == 0: #TP - c.NuTauTarget.row=7 - c.NuTauTarget.col=15 - c.NuTauTarget.wall=11 - if c.NuTauTarget.Design == 1: #NEW with magnet - c.NuTauTarget.row=14 - c.NuTauTarget.col=6 - c.NuTauTarget.wall=11 - if c.NuTauTarget.Design == 2: #NEW with NO magnet - c.NuTauTarget.row=20 - c.NuTauTarget.col=9 - c.NuTauTarget.wall=20 - if c.NuTauTarget.Design == 3: #One unique magnet, eventually more than one target volume - #c.NuTauTarget.n_plates = 56 + if nuTauTargetDesign == 2: + c.NuTauTarget.zC = ( + -c.decayVolume.length / 2.0 - c.tauMudet.GapD - c.tauMudet.Ztot - 2.5 * u.m + ) + + if c.NuTauTarget.Design == 0: # TP + c.NuTauTarget.row = 7 + c.NuTauTarget.col = 15 + c.NuTauTarget.wall = 11 + if c.NuTauTarget.Design == 1: # NEW with magnet + c.NuTauTarget.row = 14 + c.NuTauTarget.col = 6 + c.NuTauTarget.wall = 11 + if c.NuTauTarget.Design == 2: # NEW with NO magnet + c.NuTauTarget.row = 20 + c.NuTauTarget.col = 9 + c.NuTauTarget.wall = 20 + if ( + c.NuTauTarget.Design == 3 + ): # One unique magnet, eventually more than one target volume + # c.NuTauTarget.n_plates = 56 c.NuTauTarget.row = 2 c.NuTauTarget.col = 2 c.NuTauTarget.wall = 19 c.NuTauTarget.n_plates = 56 - c.NuTauTarget.target = 1 #number of neutrino target volumes + c.NuTauTarget.target = 1 # number of neutrino target volumes c.NuTauTarget.nuTargetPassive = nuTargetPassive # space for the structure that holds the brick - c.NuTauTarget.Ydist = 0.0*u.cm + c.NuTauTarget.Ydist = 0.0 * u.cm c.NuTauTarget.SingleEmFilm = True c.NuTauTarget.EmTh = 0.0070 * u.cm c.NuTauTarget.EmX = 40.0 * u.cm c.NuTauTarget.EmY = 40.0 * u.cm c.NuTauTarget.PBTh = 0.0175 * u.cm c.NuTauTarget.LeadTh = 0.1 * u.cm - c.NuTauTarget.EPlW = 2* c.NuTauTarget.EmTh + c.NuTauTarget.PBTh + c.NuTauTarget.EPlW = 2 * c.NuTauTarget.EmTh + c.NuTauTarget.PBTh c.NuTauTarget.AllPW = c.NuTauTarget.LeadTh + c.NuTauTarget.EPlW c.NuTauTarget.BrX = 41.0 * u.cm c.NuTauTarget.BrY = 41.0 * u.cm c.NuTauTarget.BrPackZ = 0.1045 * u.cm c.NuTauTarget.BrPackX = c.NuTauTarget.BrX - c.NuTauTarget.EmX c.NuTauTarget.BrPackY = c.NuTauTarget.BrY - c.NuTauTarget.EmY - c.NuTauTarget.BrZ = c.NuTauTarget.n_plates * c.NuTauTarget.AllPW + c.NuTauTarget.EPlW + c.NuTauTarget.BrPackZ + c.NuTauTarget.BrZ = ( + c.NuTauTarget.n_plates * c.NuTauTarget.AllPW + + c.NuTauTarget.EPlW + + c.NuTauTarget.BrPackZ + ) - if c.NuTauTarget.Design == 4: #new geometry, for ECN3 + if c.NuTauTarget.Design == 4: # new geometry, for ECN3 c.NuTauTarget.row = 2 c.NuTauTarget.col = 2 c.NuTauTarget.wall = 17 c.NuTauTarget.n_plates = 59 - c.NuTauTarget.EmX = 20. * u.cm - c.NuTauTarget.EmY = 20. * u.cm + c.NuTauTarget.EmX = 20.0 * u.cm + c.NuTauTarget.EmY = 20.0 * u.cm c.NuTauTarget.BrPackX = 2 * 0.05 * u.cm c.NuTauTarget.BrPackY = 2 * 0.05 * u.cm c.NuTauTarget.BrPackZ = 2.21 * u.cm c.NuTauTarget.BrX = c.NuTauTarget.BrPackX + c.NuTauTarget.EmX c.NuTauTarget.BrY = c.NuTauTarget.BrPackY + c.NuTauTarget.EmY - c.NuTauTarget.EPlW = 2* c.NuTauTarget.EmTh + c.NuTauTarget.PBTh + c.NuTauTarget.EPlW = 2 * c.NuTauTarget.EmTh + c.NuTauTarget.PBTh c.NuTauTarget.AllPW = c.NuTauTarget.LeadTh + c.NuTauTarget.EPlW - c.NuTauTarget.BrZ = c.NuTauTarget.n_plates * c.NuTauTarget.AllPW + c.NuTauTarget.EPlW + c.NuTauTarget.BrPackZ #10 cm - #c.NuTauTarget.BrZ = 10. * u.cm #hardcoded wall width + c.NuTauTarget.BrZ = ( + c.NuTauTarget.n_plates * c.NuTauTarget.AllPW + + c.NuTauTarget.EPlW + + c.NuTauTarget.BrPackZ + ) # 10 cm + # c.NuTauTarget.BrZ = 10. * u.cm #hardcoded wall width c.NuTauTarget.SingleEmFilm = False - #TargetTrackers! - c.NuTauTT = AttrDict(z=0*u.cm) + # TargetTrackers! + c.NuTauTT = AttrDict(z=0 * u.cm) c.NuTauTT.design = nuTauTargetDesign c.NuTauTT.n_hor_planes = 11 c.NuTauTT.n_vert_planes = 7 - c.NuTauTT.scifimat_width = 13.06 * u.cm # old value 13.045 - c.NuTauTT.scifimat_hor = 94.315 * u.cm #13.045 * 7 + endpieces = length of hor. mats - c.NuTauTT.scifimat_vert = 146.495 * u.cm #13.045 * 11 + endpieces = length of vert. mats - c.NuTauTT.scifimat_z = 0.145 * u.cm # Scintillating fiber mat - c.NuTauTT.support_z = 0.02 * u.cm # Support carbon composite - c.NuTauTT.honeycomb_z = 2 * u.cm # Airex (or Nomex) + c.NuTauTT.scifimat_width = 13.06 * u.cm # old value 13.045 + c.NuTauTT.scifimat_hor = ( + 94.315 * u.cm + ) # 13.045 * 7 + endpieces = length of hor. mats + c.NuTauTT.scifimat_vert = ( + 146.495 * u.cm + ) # 13.045 * 11 + endpieces = length of vert. mats + c.NuTauTT.scifimat_z = 0.145 * u.cm # Scintillating fiber mat + c.NuTauTT.support_z = 0.02 * u.cm # Support carbon composite + c.NuTauTT.honeycomb_z = 2 * u.cm # Airex (or Nomex) c.NuTauTT.TTX = c.NuTauTT.scifimat_hor c.NuTauTT.TTY = c.NuTauTT.scifimat_vert - c.NuTauTT.TTZ = 2 * c.NuTauTT.support_z + 2 * c.NuTauTT.scifimat_z + c.NuTauTT.honeycomb_z + c.NuTauTT.TTZ = ( + 2 * c.NuTauTT.support_z + 2 * c.NuTauTT.scifimat_z + c.NuTauTT.honeycomb_z + ) c.NuTauTT.n = c.NuTauTarget.wall # should be called after TTX, TTY c.NuTauTarget.xdim = c.NuTauTT.TTX c.NuTauTarget.ydim = c.NuTauTT.TTY - c.NuTauTarget.WallXDim = c.NuTauTarget.col*c.NuTauTarget.BrX - c.NuTauTarget.WallYDim = c.NuTauTarget.row*c.NuTauTarget.BrY+(c.NuTauTarget.row-1)*c.NuTauTarget.Ydist + c.NuTauTarget.WallXDim = c.NuTauTarget.col * c.NuTauTarget.BrX + c.NuTauTarget.WallYDim = ( + c.NuTauTarget.row * c.NuTauTarget.BrY + + (c.NuTauTarget.row - 1) * c.NuTauTarget.Ydist + ) c.NuTauTarget.WallZDim = c.NuTauTarget.BrZ - if (c.NuTauTT.design==4): + if c.NuTauTT.design == 4: c.NuTauTT.n_hor_planes = 4 - c.NuTauTT.n_vert_planes = 4 #now same number, walls are squared - c.NuTauTT.scifimat_width = 13.06 * u.cm # old value 13.045 - c.NuTauTT.scifimat_hor = c.NuTauTT.n_hor_planes * c.NuTauTT.scifimat_width + 2.9 * u.cm # endpieces (~2.9cm from previous geom) - c.NuTauTT.scifimat_vert = c.NuTauTT.n_vert_planes * c.NuTauTT.scifimat_width + 2.9 * u.cm # endpieces (~2.9cm from previous geom) - c.NuTauTT.scifimat_z = 0.145 * u.cm # Scintillating fiber mat - c.NuTauTT.support_z = 1.355 * u.cm # More space for support (total TTZ 5 cm) - c.NuTauTT.honeycomb_z = 2 * u.cm # Airex (or Nomex) + c.NuTauTT.n_vert_planes = 4 # now same number, walls are squared + c.NuTauTT.scifimat_width = 13.06 * u.cm # old value 13.045 + c.NuTauTT.scifimat_hor = ( + c.NuTauTT.n_hor_planes * c.NuTauTT.scifimat_width + 2.9 * u.cm + ) # endpieces (~2.9cm from previous geom) + c.NuTauTT.scifimat_vert = ( + c.NuTauTT.n_vert_planes * c.NuTauTT.scifimat_width + 2.9 * u.cm + ) # endpieces (~2.9cm from previous geom) + c.NuTauTT.scifimat_z = 0.145 * u.cm # Scintillating fiber mat + c.NuTauTT.support_z = 1.355 * u.cm # More space for support (total TTZ 5 cm) + c.NuTauTT.honeycomb_z = 2 * u.cm # Airex (or Nomex) c.NuTauTT.TTX = c.NuTauTT.scifimat_hor c.NuTauTT.TTY = c.NuTauTT.scifimat_vert - c.NuTauTT.TTZ = 2 * c.NuTauTT.support_z + 2 * c.NuTauTT.scifimat_z + c.NuTauTT.honeycomb_z - c.NuTauTT.n = c.NuTauTarget.wall + 1 #starts and end with TT, no HPT + c.NuTauTT.TTZ = ( + 2 * c.NuTauTT.support_z + 2 * c.NuTauTT.scifimat_z + c.NuTauTT.honeycomb_z + ) + c.NuTauTT.n = c.NuTauTarget.wall + 1 # starts and end with TT, no HPT # should be called after TTX, TTY c.NuTauTarget.xdim = c.NuTauTT.TTX c.NuTauTarget.ydim = c.NuTauTT.TTY - - #HPT - c.tauHPT = AttrDict(z=0*u.cm) + # HPT + c.tauHPT = AttrDict(z=0 * u.cm) c.tauHPT.design = nuTauTargetDesign c.tauHPT.n_hor_planes = 11 c.tauHPT.n_vert_planes = 7 @@ -779,86 +1037,113 @@ c.tauHPT.honeycomb_z = c.NuTauTT.honeycomb_z c.tauHPT.TX = c.tauHPT.scifimat_hor c.tauHPT.TY = c.tauHPT.scifimat_vert - c.tauHPT.TZ = 2 * c.tauHPT.support_z + 2 * c.tauHPT.scifimat_z + c.tauHPT.honeycomb_z + c.tauHPT.TZ = ( + 2 * c.tauHPT.support_z + 2 * c.tauHPT.scifimat_z + c.tauHPT.honeycomb_z + ) - if nuTauTargetDesign<3: - c.tauHPT.DZ = 15*u.cm + if nuTauTargetDesign < 3: + c.tauHPT.DZ = 15 * u.cm c.tauHPT.DX = c.tauMudet.XFe c.tauHPT.DY = c.tauMudet.YFe c.tauHPT.ConcreteX = c.tauHPT.DX - c.tauHPT.ConcreteY = c.tauMudet.Ytot/2 - c.tauHPT.DY/2 + c.tauHPT.ConcreteY = c.tauMudet.Ytot / 2 - c.tauHPT.DY / 2 c.tauHPT.ConcreteZ = c.tauHPT.DZ - if nuTauTargetDesign==3: - c.tauHPT.SRDY = 10 * u.cm #additional detectors for improving acceptance + if nuTauTargetDesign == 3: + c.tauHPT.SRDY = 10 * u.cm # additional detectors for improving acceptance c.tauHPT.DX = c.tauHPT.TX c.tauHPT.DY = c.tauHPT.TY c.tauHPT.DZ = c.tauHPT.TZ - c.tauHPT.nHPT = 5 # number of downstream trackers after neutrino target + c.tauHPT.nHPT = 5 # number of downstream trackers after neutrino target - if nuTauTargetDesign!=2 and nuTauTargetDesign!=4: #TP or NEW with magnet + if nuTauTargetDesign != 2 and nuTauTargetDesign != 4: # TP or NEW with magnet c.NuTauTarget.RohG = 1.5 * u.cm c.NuTauTarget.LayerCESW = c.NuTauTarget.RohG + c.NuTauTarget.EPlW c.NuTauTarget.CESPack = 0.3055 * u.cm - c.NuTauTarget.CESW = 2 * c.NuTauTarget.LayerCESW + c.NuTauTarget.EPlW + c.NuTauTarget.CESPack + c.NuTauTarget.CESW = ( + 2 * c.NuTauTarget.LayerCESW + c.NuTauTarget.EPlW + c.NuTauTarget.CESPack + ) c.NuTauTarget.CellW = c.NuTauTarget.BrZ + c.NuTauTarget.CESW - if nuTauTargetDesign!=3: - c.NuTauTarget.zdim = c.NuTauTarget.wall* c.NuTauTarget.CellW + (c.NuTauTarget.wall+1)*c.NuTauTT.TTZ - if nuTauTargetDesign ==3: - c.NuTauTarget.zdim = c.NuTauTarget.wall* c.NuTauTarget.CellW + c.NuTauTarget.wall*c.NuTauTT.TTZ - c.NuTauTarget.zC = c.EmuMagnet.zC - c.NuTauTarget.zdim/2. - c.tauHPT.TotalDZ = (c.EmuMagnet.Z - c.EmuMagnet.Height1) - c.NuTauTarget.zdim # MagRegion-Target - c.tauHPT.distHPT = (c.tauHPT.TotalDZ - c.tauHPT.nHPT * c.tauHPT.DZ) / (c.tauHPT.nHPT - 1) - - if nuTauTargetDesign == 2 or nuTauTargetDesign == 4: #NEW with NO magnet + if nuTauTargetDesign != 3: + c.NuTauTarget.zdim = ( + c.NuTauTarget.wall * c.NuTauTarget.CellW + + (c.NuTauTarget.wall + 1) * c.NuTauTT.TTZ + ) + if nuTauTargetDesign == 3: + c.NuTauTarget.zdim = ( + c.NuTauTarget.wall * c.NuTauTarget.CellW + + c.NuTauTarget.wall * c.NuTauTT.TTZ + ) + c.NuTauTarget.zC = c.EmuMagnet.zC - c.NuTauTarget.zdim / 2.0 + c.tauHPT.TotalDZ = ( + c.EmuMagnet.Z - c.EmuMagnet.Height1 + ) - c.NuTauTarget.zdim # MagRegion-Target + c.tauHPT.distHPT = (c.tauHPT.TotalDZ - c.tauHPT.nHPT * c.tauHPT.DZ) / ( + c.tauHPT.nHPT - 1 + ) + + if nuTauTargetDesign == 2 or nuTauTargetDesign == 4: # NEW with NO magnet c.NuTauTarget.RohG = 0 * u.cm - c.NuTauTarget.LayerCESW =0 *u.cm - c.NuTauTarget.CESPack = 0* u.cm - c.NuTauTarget.CESW = 0*u.cm + c.NuTauTarget.LayerCESW = 0 * u.cm + c.NuTauTarget.CESPack = 0 * u.cm + c.NuTauTarget.CESW = 0 * u.cm c.NuTauTarget.CellW = c.NuTauTarget.BrZ - c.NuTauTarget.zdim = c.NuTauTarget.wall* c.NuTauTarget.CellW + (c.NuTauTarget.wall+1)*c.NuTauTT.TTZ - if nuTauTargetDesign==4: + c.NuTauTarget.zdim = ( + c.NuTauTarget.wall * c.NuTauTarget.CellW + + (c.NuTauTarget.wall + 1) * c.NuTauTT.TTZ + ) + if nuTauTargetDesign == 4: c.EmuMagnet.GapDown = 20 * u.cm - c.NuTauTarget.zC = c.tauMudet.zMudetC - c.tauMudet.Ztot/2 - c.EmuMagnet.GapDown - c.NuTauTarget.zdim/2. - - c.NuTauTarget.BaseX = c.NuTauTarget.xdim + 20*u.cm - c.NuTauTarget.BaseY = 20*u.cm - if nuTauTargetDesign!=4: - c.NuTauTarget.BaseZ = c.NuTauTarget.zdim +40*u.cm - if nuTauTargetDesign==4: - c.NuTauTarget.BaseZ = c.NuTauTarget.zdim +10*u.cm - - - c.NuTauTarget.PillarX = 0.5*u.m - c.NuTauTarget.PillarZ = 0.5*u.m - c.NuTauTarget.PillarY = 10*u.m - c.NuTauTarget.ydim/2 -c.NuTauTarget.BaseY- 0.1*u.mm - c.cave.floorHeightMuonShield - - #Upstream Tagger + c.NuTauTarget.zC = ( + c.tauMudet.zMudetC + - c.tauMudet.Ztot / 2 + - c.EmuMagnet.GapDown + - c.NuTauTarget.zdim / 2.0 + ) + + c.NuTauTarget.BaseX = c.NuTauTarget.xdim + 20 * u.cm + c.NuTauTarget.BaseY = 20 * u.cm + if nuTauTargetDesign != 4: + c.NuTauTarget.BaseZ = c.NuTauTarget.zdim + 40 * u.cm + if nuTauTargetDesign == 4: + c.NuTauTarget.BaseZ = c.NuTauTarget.zdim + 10 * u.cm + + c.NuTauTarget.PillarX = 0.5 * u.m + c.NuTauTarget.PillarZ = 0.5 * u.m + c.NuTauTarget.PillarY = ( + 10 * u.m + - c.NuTauTarget.ydim / 2 + - c.NuTauTarget.BaseY + - 0.1 * u.mm + - c.cave.floorHeightMuonShield + ) + + # Upstream Tagger UBT_x_crop = 113.4 * u.cm c.UpstreamTagger = AttrDict(z=0) c.UpstreamTagger.Z_Glass = 0.2 * u.cm c.UpstreamTagger.Y_Glass = 105 * u.cm - c.UpstreamTagger.X_Glass = 223. * u.cm - UBT_x_crop + c.UpstreamTagger.X_Glass = 223.0 * u.cm - UBT_x_crop c.UpstreamTagger.Z_Glass_Border = 0.2 * u.cm c.UpstreamTagger.Y_Glass_Border = 1.0 * u.cm c.UpstreamTagger.X_Glass_Border = 1.0 * u.cm c.UpstreamTagger.Z_PMMA = 0.8 * u.cm c.UpstreamTagger.Y_PMMA = 108 * u.cm - c.UpstreamTagger.X_PMMA = 226 * u.cm - UBT_x_crop + c.UpstreamTagger.X_PMMA = 226 * u.cm - UBT_x_crop c.UpstreamTagger.DY_PMMA = 1.5 * u.cm c.UpstreamTagger.DX_PMMA = 1.5 * u.cm c.UpstreamTagger.DZ_PMMA = 0.1 * u.cm c.UpstreamTagger.Z_FreonSF6 = 0.1 * u.cm c.UpstreamTagger.Y_FreonSF6 = 107 * u.cm - c.UpstreamTagger.X_FreonSF6 = 225 * u.cm - UBT_x_crop + c.UpstreamTagger.X_FreonSF6 = 225 * u.cm - UBT_x_crop c.UpstreamTagger.Z_FreonSF6_2 = 0.8 * u.cm c.UpstreamTagger.Y_FreonSF6_2 = 0.5 * u.cm c.UpstreamTagger.X_FreonSF6_2 = 0.5 * u.cm c.UpstreamTagger.Z_FR4 = 0.15 * u.cm c.UpstreamTagger.Y_FR4 = 111 * u.cm - c.UpstreamTagger.X_FR4 = 229 * u.cm - UBT_x_crop + c.UpstreamTagger.X_FR4 = 229 * u.cm - UBT_x_crop c.UpstreamTagger.Z_Aluminium = 1.1503 * u.cm c.UpstreamTagger.Y_Aluminium = 111 * u.cm - c.UpstreamTagger.X_Aluminium = 233 * u.cm - UBT_x_crop + c.UpstreamTagger.X_Aluminium = 233 * u.cm - UBT_x_crop c.UpstreamTagger.DZ_Aluminium = 0.1 * u.cm c.UpstreamTagger.DY_Aluminium = 1 * u.cm c.UpstreamTagger.DX_Aluminium = 0.2 * u.cm @@ -867,7 +1152,9 @@ c.UpstreamTagger.X_Air = 2 * u.cm c.UpstreamTagger.Z_Strip = 0.0003 * u.cm c.UpstreamTagger.Y_Strip = 3.1 * u.cm - c.UpstreamTagger.X_Strip = 229 * u.cm - UBT_x_crop + c.UpstreamTagger.X_Strip = 229 * u.cm - UBT_x_crop c.UpstreamTagger.X_Strip64 = 1.534 * u.cm c.UpstreamTagger.Y_Strip64 = 111 * u.cm - c.UpstreamTagger.Z_Position = c.tauMudet.zMudetC + (c.tauMudet.Ztot)/2 + 12.0*u.cm + c.UpstreamTagger.Z_Position = ( + c.tauMudet.zMudetC + (c.tauMudet.Ztot) / 2 + 12.0 * u.cm + ) diff --git a/geometry/media.geo b/geometry/media.geo index 8913bd8fdc..c694490231 100644 --- a/geometry/media.geo +++ b/geometry/media.geo @@ -19,7 +19,7 @@ // basic helium for Decay Volume; June 2024 helium 1 4.00 2 1.78e-4 0 1 30. .001 - 0 + 0 air 3 14.01 16. 39.95 7. 8. 18. 1.205e-3 .755 .231 .014 0 1 30. .001 diff --git a/geometry/veto_config_helium.yaml b/geometry/veto_config_helium.yaml index bcc4da35ca..a98204d357 100644 --- a/geometry/veto_config_helium.yaml +++ b/geometry/veto_config_helium.yaml @@ -17,4 +17,3 @@ ystartInner : 270.0 # cm xendInner : 400.0 # cm #FocusLineX at z= target.z0 + 16.8m yendInner : 600.0 # cm #FocusLineY at z= target.z0 - 7.4m z0: -2478.0 # cm Decay Vessel Start - diff --git a/geometry/veto_config_vacuums.yaml b/geometry/veto_config_vacuums.yaml index 7d07c47b21..6497ff4d8c 100644 --- a/geometry/veto_config_vacuums.yaml +++ b/geometry/veto_config_vacuums.yaml @@ -9,7 +9,7 @@ outerSupportMed: "steel" lidThickness: 0.0 # cm sensitiveThickness: 20 # cm sensitiveMed: "Scintillator" -decayMed: "vacuums" +decayMed: "vacuums" rib: 1.5 # cm ribMed: "steel" xstartInner : 100.0 # cm @@ -17,4 +17,3 @@ ystartInner : 270.0 # cm xendInner : 400.0 # cm #FocusLineX at z= target.z0 + 16.8m yendInner : 600.0 # cm #FocusLineY at z= target.z0 - 7.4m z0: -2478.0 # cm Decay Vessel Start - diff --git a/hcal/CMakeLists.txt b/hcal/CMakeLists.txt index 1be1203a65..88335c8e4f 100644 --- a/hcal/CMakeLists.txt +++ b/hcal/CMakeLists.txt @@ -1,42 +1,34 @@ -# Create a library called "libhcal" which includes the source files given in -# the array . -# The extension is already found. Any number of sources could be listed here. +# Create a library called "libhcal" which includes the source files given in the +# array . The extension is already found. Any number of sources could be listed +# here. -set(INCLUDE_DIRECTORIES -${CMAKE_SOURCE_DIR}/shipdata -${CMAKE_SOURCE_DIR}/hcal -${genfit2_INCDIR} -) +set(INCLUDE_DIRECTORIES ${CMAKE_SOURCE_DIR}/shipdata ${CMAKE_SOURCE_DIR}/hcal + ${genfit2_INCDIR}) -include_directories(${INCLUDE_DIRECTORIES} ${VMC_INCLUDE_DIRS} ${FAIRROOT_INCLUDE_DIR}) +include_directories(${INCLUDE_DIRECTORIES} ${VMC_INCLUDE_DIRS} + ${FAIRROOT_INCLUDE_DIR}) include_directories(SYSTEM ${SYSTEM_INCLUDE_DIRECTORIES}) -set(LINK_DIRECTORIES -${ROOT_LIBRARY_DIR} -${FAIRROOT_LIBRARY_DIR} -${genfit2_LIBDIR} -) +set(LINK_DIRECTORIES ${ROOT_LIBRARY_DIR} ${FAIRROOT_LIBRARY_DIR} + ${genfit2_LIBDIR}) -link_directories( ${LINK_DIRECTORIES}) +link_directories(${LINK_DIRECTORIES}) set(SRCS -#Put here your sourcefiles -hcalContFact.cxx -hcalPoint.cxx -hcal.cxx -hcalLightMap.cxx -hcalInf.cxx -hcalModule.cxx -hcalModuleMC.cxx -hcalStructure.cxx -hcalStructureFiller.cxx -hcalAnalysisSimple.cxx -) + # Put here your sourcefiles + hcalContFact.cxx + hcalPoint.cxx + hcal.cxx + hcalLightMap.cxx + hcalInf.cxx + hcalModule.cxx + hcalModuleMC.cxx + hcalStructure.cxx + hcalStructureFiller.cxx + hcalAnalysisSimple.cxx) -Set(LINKDEF hcalLinkDef.h) -Set(LIBRARY_NAME hcal) -Set(DEPENDENCIES - Base ShipData FairLogger::FairLogger -) +set(LINKDEF hcalLinkDef.h) +set(LIBRARY_NAME hcal) +set(DEPENDENCIES Base ShipData FairLogger::FairLogger) -GENERATE_LIBRARY() +generate_library() diff --git a/hcal/hcal.cxx b/hcal/hcal.cxx index 781a58e6b9..1d9e1e2a7d 100644 --- a/hcal/hcal.cxx +++ b/hcal/hcal.cxx @@ -7,32 +7,30 @@ #include "hcal.h" -#include "hcalPoint.h" -#include "hcalLightMap.h" - #include "FairGeoInterface.h" #include "FairGeoLoader.h" +#include "FairGeoMedia.h" +#include "FairGeoMedium.h" #include "FairGeoNode.h" #include "FairGeoRootBuilder.h" -#include "FairRuntimeDb.h" #include "FairRootManager.h" #include "FairRun.h" #include "FairRunAna.h" -#include "ShipStack.h" +#include "FairRuntimeDb.h" #include "FairVolume.h" -#include "FairGeoMedium.h" -#include "FairGeoMedia.h" - +#include "ShipStack.h" #include "TClonesArray.h" +#include "TGeoBBox.h" #include "TGeoMCGeometry.h" #include "TGeoManager.h" -#include "TParticle.h" -#include "TVirtualMC.h" -#include "TGeoBBox.h" +#include "TGeoMatrix.h" #include "TGeoPgon.h" #include "TGeoTube.h" -#include "TGeoMatrix.h" #include "TList.h" +#include "TParticle.h" +#include "TVirtualMC.h" +#include "hcalLightMap.h" +#include "hcalPoint.h" #include #include @@ -43,1164 +41,1279 @@ using namespace std; // ----- Default constructor ------------------------------------------- hcal::hcal() - : FairDetector("HCAL", kTRUE, khcal), - fInf(NULL), - fDebug(NULL), - fTrackID(-1), - fVolumeID(-1), - fPos(), - fMom(), - fTime(-1.), - fLength(-1.), - fELoss(-1.), - fPosIndex(0), - fHcalCollection(new TClonesArray("hcalPoint")), - fLiteCollection(new TClonesArray("hcalPoint")), - fHcalSize(), - fSimpleGeo(0), - fFastMC(0), - fXSize(0), - fYSize(0), - fDX(0.), - fDY(0.), - fModuleSize(0.), - fZHcal(0.), - fSemiX(0.), - fSemiY(0.), - fAbsorber("Lead"), - fThicknessAbsorber(0.), - fThicknessScin(0.), - fThicknessTyvk(0.), - fThicknessLayer(0.), - fThicknessSteel(0.), - fEdging(0.), - fHoleRad(0.), - fFiberRad(0.), - fXCell(0), - fYCell(0), - fNH(0), - fCF(0), - fLightMapName(""), - fLightMap(NULL), - fNLayers(0), - fModuleLength(0.), - fVolIdMax(0), - fFirstNumber(0), - fVolArr(), - fModule(NULL), - fScTile(NULL), - fTileEdging(NULL), - fPbTile(NULL), - fTvTile(NULL), - fHoleVol(), - fFiberVol(), - fSteelTapes(), - fHolePos(), - fModules(0), - fRawNumber(), - fStructureId(0) + : FairDetector("HCAL", kTRUE, khcal) + , fInf(NULL) + , fDebug(NULL) + , fTrackID(-1) + , fVolumeID(-1) + , fPos() + , fMom() + , fTime(-1.) + , fLength(-1.) + , fELoss(-1.) + , fPosIndex(0) + , fHcalCollection(new TClonesArray("hcalPoint")) + , fLiteCollection(new TClonesArray("hcalPoint")) + , fHcalSize() + , fSimpleGeo(0) + , fFastMC(0) + , fXSize(0) + , fYSize(0) + , fDX(0.) + , fDY(0.) + , fModuleSize(0.) + , fZHcal(0.) + , fSemiX(0.) + , fSemiY(0.) + , fAbsorber("Lead") + , fThicknessAbsorber(0.) + , fThicknessScin(0.) + , fThicknessTyvk(0.) + , fThicknessLayer(0.) + , fThicknessSteel(0.) + , fEdging(0.) + , fHoleRad(0.) + , fFiberRad(0.) + , fXCell(0) + , fYCell(0) + , fNH(0) + , fCF(0) + , fLightMapName("") + , fLightMap(NULL) + , fNLayers(0) + , fModuleLength(0.) + , fVolIdMax(0) + , fFirstNumber(0) + , fVolArr() + , fModule(NULL) + , fScTile(NULL) + , fTileEdging(NULL) + , fPbTile(NULL) + , fTvTile(NULL) + , fHoleVol() + , fFiberVol() + , fSteelTapes() + , fHolePos() + , fModules(0) + , fRawNumber() + , fStructureId(0) { - fVerboseLevel = 1; + fVerboseLevel = 1; - Int_t i; + Int_t i; - for(i=kN-1;i>-1;i--) - fVolArr[i]=-1111; + for (i = kN - 1; i > -1; i--) + fVolArr[i] = -1111; } // ------------------------------------------------------------------------- - - // ----- Standard constructor ------------------------------------------ hcal::hcal(const char* name, Bool_t active, const char* fileGeo) - : FairDetector(name, active, khcal), - fInf(NULL), - fDebug(NULL), - fTrackID(-1), - fVolumeID(-1), - fPos(), - fMom(), - fTime(-1.), - fLength(-1.), - fELoss(-1.), - fPosIndex(0), - fHcalCollection(new TClonesArray("hcalPoint")), - fLiteCollection(new TClonesArray("hcalPoint")), - fHcalSize(), - fSimpleGeo(0), - fFastMC(0), - fXSize(0), - fYSize(0), - fDX(0.), - fDY(0.), - fModuleSize(0.), - fZHcal(0.), - fSemiX(0.), - fSemiY(0.), - fAbsorber("Lead"), - fThicknessAbsorber(0.), - fThicknessScin(0.), - fThicknessTyvk(0.), - fThicknessLayer(0.), - fThicknessSteel(0.), - fEdging(0.), - fHoleRad(0.), - fFiberRad(0.), - fXCell(0), - fYCell(0), - fNH(0), - fCF(0), - fLightMapName(""), - fLightMap(NULL), - fNLayers(0), - fModuleLength(0.), - fVolIdMax(0), - fFirstNumber(0), - fVolArr(), - fModule(NULL), - fScTile(NULL), - fTileEdging(NULL), - fPbTile(NULL), - fTvTile(NULL), - fHoleVol(), - fFiberVol(), - fSteelTapes(), - fHolePos(), - fModules(0), - fRawNumber(), - fStructureId(0) + : FairDetector(name, active, khcal) + , fInf(NULL) + , fDebug(NULL) + , fTrackID(-1) + , fVolumeID(-1) + , fPos() + , fMom() + , fTime(-1.) + , fLength(-1.) + , fELoss(-1.) + , fPosIndex(0) + , fHcalCollection(new TClonesArray("hcalPoint")) + , fLiteCollection(new TClonesArray("hcalPoint")) + , fHcalSize() + , fSimpleGeo(0) + , fFastMC(0) + , fXSize(0) + , fYSize(0) + , fDX(0.) + , fDY(0.) + , fModuleSize(0.) + , fZHcal(0.) + , fSemiX(0.) + , fSemiY(0.) + , fAbsorber("Lead") + , fThicknessAbsorber(0.) + , fThicknessScin(0.) + , fThicknessTyvk(0.) + , fThicknessLayer(0.) + , fThicknessSteel(0.) + , fEdging(0.) + , fHoleRad(0.) + , fFiberRad(0.) + , fXCell(0) + , fYCell(0) + , fNH(0) + , fCF(0) + , fLightMapName("") + , fLightMap(NULL) + , fNLayers(0) + , fModuleLength(0.) + , fVolIdMax(0) + , fFirstNumber(0) + , fVolArr() + , fModule(NULL) + , fScTile(NULL) + , fTileEdging(NULL) + , fPbTile(NULL) + , fTvTile(NULL) + , fHoleVol() + , fFiberVol() + , fSteelTapes() + , fHolePos() + , fModules(0) + , fRawNumber() + , fStructureId(0) { - /** hcal constructor: - ** reads geometry parameters from the ascii file , - ** creates the ECAL geometry container hcalInf - ** and initializes basic geometry parameters needed to construct - ** TGeo geometry - **/ - - fVerboseLevel=0; - Int_t i; - Int_t j; - TString nm; - Info("hcal","Geometry is read from file %s.", fileGeo); - fInf=hcalInf::GetInstance(fileGeo); - if (fInf==NULL) - { - Fatal("hcal"," Can't read geometry from %s.", fileGeo); - return; - } - fHcalSize[0]=fInf->GetHcalSize(0); - fHcalSize[1]=fInf->GetHcalSize(1); - fHcalSize[2]=fInf->GetHcalSize(2); - - fZHcal=fInf->GetZPos(); - - fThicknessAbsorber=fInf->GetAbsorber(); - fThicknessScin=fInf->GetScin(); - fThicknessTyvk=fInf->GetTyveec(); - fNLayers=fInf->GetNLayers(); - - fXSize=fInf->GetXSize(); - fYSize=fInf->GetYSize(); - - fPosIndex=0; - fDebug=""; - - fSemiX=fInf->GetVariableStrict("xsemiaxis"); - fSemiY=fInf->GetVariableStrict("ysemiaxis"); - fHoleRad=fInf->GetVariableStrict("holeradius"); - fFiberRad=fInf->GetVariableStrict("fiberradius"); - fThicknessSteel=fInf->GetVariableStrict("steel"); - fEdging=fInf->GetVariableStrict("tileedging"); - fModuleSize=fInf->GetVariableStrict("modulesize"); - fSimpleGeo=(Int_t)fInf->GetVariableStrict("usesimplegeo"); - fFastMC=(Int_t)fInf->GetVariableStrict("fastmc"); - fDX=fInf->GetVariableStrict("xpos"); - fDY=fInf->GetVariableStrict("ypos"); - fNLayers1=fInf->GetN1Layers(); - - for(i=kN-1;i>-1;i--) - fVolArr[i]=-1111; - - for(i=0;i<2;i++) - { - fSteelTapes[i]=NULL; - } - for(i=0;i<3;i++) - { - fHoleVol[i]=NULL; - fFiberVol[i]=NULL; - } - /** Counting modules **/ - for(i=0;iGetXSize();i++) - for(j=0;jGetYSize();j++) - { - if (fInf->GetType(i,j)==0) continue; - if (fInf->GetType(i,j)==1) - fModules++; + /** hcal constructor: + ** reads geometry parameters from the ascii file , + ** creates the ECAL geometry container hcalInf + ** and initializes basic geometry parameters needed to construct + ** TGeo geometry + **/ + + fVerboseLevel = 0; + Int_t i; + Int_t j; + TString nm; + Info("hcal", "Geometry is read from file %s.", fileGeo); + fInf = hcalInf::GetInstance(fileGeo); + if (fInf == NULL) { + Fatal("hcal", " Can't read geometry from %s.", fileGeo); + return; + } + fHcalSize[0] = fInf->GetHcalSize(0); + fHcalSize[1] = fInf->GetHcalSize(1); + fHcalSize[2] = fInf->GetHcalSize(2); + + fZHcal = fInf->GetZPos(); + + fThicknessAbsorber = fInf->GetAbsorber(); + fThicknessScin = fInf->GetScin(); + fThicknessTyvk = fInf->GetTyveec(); + fNLayers = fInf->GetNLayers(); + + fXSize = fInf->GetXSize(); + fYSize = fInf->GetYSize(); + + fPosIndex = 0; + fDebug = ""; + + fSemiX = fInf->GetVariableStrict("xsemiaxis"); + fSemiY = fInf->GetVariableStrict("ysemiaxis"); + fHoleRad = fInf->GetVariableStrict("holeradius"); + fFiberRad = fInf->GetVariableStrict("fiberradius"); + fThicknessSteel = fInf->GetVariableStrict("steel"); + fEdging = fInf->GetVariableStrict("tileedging"); + fModuleSize = fInf->GetVariableStrict("modulesize"); + fSimpleGeo = (Int_t)fInf->GetVariableStrict("usesimplegeo"); + fFastMC = (Int_t)fInf->GetVariableStrict("fastmc"); + fDX = fInf->GetVariableStrict("xpos"); + fDY = fInf->GetVariableStrict("ypos"); + fNLayers1 = fInf->GetN1Layers(); + + for (i = kN - 1; i > -1; i--) + fVolArr[i] = -1111; + + for (i = 0; i < 2; i++) { + fSteelTapes[i] = NULL; + } + for (i = 0; i < 3; i++) { + fHoleVol[i] = NULL; + fFiberVol[i] = NULL; + } + /** Counting modules **/ + for (i = 0; i < fInf->GetXSize(); i++) + for (j = 0; j < fInf->GetYSize(); j++) { + if (fInf->GetType(i, j) == 0) + continue; + if (fInf->GetType(i, j) == 1) + fModules++; + else + Fatal("hcal", "Wrong module type"); + } + + fCF = (Int_t)fInf->GetVariableStrict("cf"); + fNH = (Int_t)fInf->GetVariableStrict("nh"); + fLightMapName = fInf->GetStringVariable("lightmap"); + if (fLightMapName != "none") + fLightMap = new hcalLightMap(fLightMapName, nm); else - Fatal("hcal", "Wrong module type"); - } - - fCF=(Int_t)fInf->GetVariableStrict("cf"); - fNH=(Int_t)fInf->GetVariableStrict("nh"); - fLightMapName=fInf->GetStringVariable("lightmap"); - if (fLightMapName!="none") - fLightMap=new hcalLightMap(fLightMapName, nm); - else - fLightMap=NULL; - fAbsorber=fInf->GetStringVariable("absorbermaterial"); - Info("hcal", "Number of modules is %d, lightmap %s", fModules, fLightMapName.Data()); - fXCell=(fModuleSize-2.0*fThicknessSteel)-2.0*fEdging; - fYCell=(fModuleSize-2.0*fThicknessSteel)-2.0*fEdging; - Info("hcal", "Size of cell of type %d is %f cm.", i, fXCell); + fLightMap = NULL; + fAbsorber = fInf->GetStringVariable("absorbermaterial"); + Info("hcal", "Number of modules is %d, lightmap %s", fModules, fLightMapName.Data()); + fXCell = (fModuleSize - 2.0 * fThicknessSteel) - 2.0 * fEdging; + fYCell = (fModuleSize - 2.0 * fThicknessSteel) - 2.0 * fEdging; + Info("hcal", "Size of cell of type %d is %f cm.", i, fXCell); } // ------------------------------------------------------------------------- void hcal::Initialize() { - FairDetector::Initialize(); -/* - FairRun* sim = FairRun::Instance(); - FairRuntimeDb* rtdb=sim->GetRuntimeDb(); - CbmGeoHcalPar *par=new CbmGeoHcalPar(); -// fInf->FillGeoPar(par,0); - rtdb->addContainer(par); -*/ + FairDetector::Initialize(); + /* + FairRun* sim = FairRun::Instance(); + FairRuntimeDb* rtdb=sim->GetRuntimeDb(); + CbmGeoHcalPar *par=new CbmGeoHcalPar(); + // fInf->FillGeoPar(par,0); + rtdb->addContainer(par); + */ } // ----- Destructor ---------------------------------------------------- hcal::~hcal() { - if (fHcalCollection) { - fHcalCollection->Delete(); - delete fHcalCollection; - fHcalCollection=NULL; - } - if (fLiteCollection) { - fLiteCollection->Delete(); - delete fLiteCollection; - fLiteCollection=NULL; - } + if (fHcalCollection) { + fHcalCollection->Delete(); + delete fHcalCollection; + fHcalCollection = NULL; + } + if (fLiteCollection) { + fLiteCollection->Delete(); + delete fLiteCollection; + fLiteCollection = NULL; + } } // ------------------------------------------------------------------------- // ----- Private method SetHcalCuts ------------------------------------ void hcal::SetHcalCuts(Int_t medium) { - /** Set GEANT3 tracking energy cuts for selected medium **/ - if (fInf->GetElectronCut() > 0) { - gMC->Gstpar(medium,"CUTGAM",fInf->GetElectronCut()); - gMC->Gstpar(medium,"CUTELE",fInf->GetElectronCut()); - gMC->Gstpar(medium,"BCUTE" ,fInf->GetElectronCut()); - gMC->Gstpar(medium,"BCUTM" ,fInf->GetElectronCut()); - } - - if (fInf->GetHadronCut() > 0) { - gMC->Gstpar(medium,"CUTNEU",fInf->GetHadronCut()); - gMC->Gstpar(medium,"CUTHAD",fInf->GetHadronCut()); - gMC->Gstpar(medium,"CUTMUO",fInf->GetHadronCut()); -// gMC->Gstpar(medium,"PPCUTM",fInf->GetHadronCut()); - } - ; + /** Set GEANT3 tracking energy cuts for selected medium **/ + if (fInf->GetElectronCut() > 0) { + gMC->Gstpar(medium, "CUTGAM", fInf->GetElectronCut()); + gMC->Gstpar(medium, "CUTELE", fInf->GetElectronCut()); + gMC->Gstpar(medium, "BCUTE", fInf->GetElectronCut()); + gMC->Gstpar(medium, "BCUTM", fInf->GetElectronCut()); + } + + if (fInf->GetHadronCut() > 0) { + gMC->Gstpar(medium, "CUTNEU", fInf->GetHadronCut()); + gMC->Gstpar(medium, "CUTHAD", fInf->GetHadronCut()); + gMC->Gstpar(medium, "CUTMUO", fInf->GetHadronCut()); + // gMC->Gstpar(medium,"PPCUTM",fInf->GetHadronCut()); + }; } // ------------------------------------------------------------------------- void hcal::FinishPrimary() { - fFirstNumber=fLiteCollection->GetEntriesFast(); + fFirstNumber = fLiteCollection->GetEntriesFast(); } //_____________________________________________________________________________ void hcal::ChangeHit(hcalPoint* oldHit) { - Double_t edep = fELoss; - Double_t el=oldHit->GetEnergyLoss(); - Double_t ttime=gMC->TrackTime()*1.0e9; - oldHit->SetEnergyLoss(el+edep); - if(ttimeGetTime()) - oldHit->SetTime(ttime); + Double_t edep = fELoss; + Double_t el = oldHit->GetEnergyLoss(); + Double_t ttime = gMC->TrackTime() * 1.0e9; + oldHit->SetEnergyLoss(el + edep); + if (ttime < oldHit->GetTime()) + oldHit->SetTime(ttime); } //_____________________________________________________________________________ void hcal::SetSpecialPhysicsCuts() { - FairRun* fRun = FairRun::Instance(); -// if (strcmp(fRun->GetName(),"TGeant3") == 0) - { - Int_t mediumID; - mediumID = gGeoManager->GetMedium("Scintillator")->GetId(); - SetHcalCuts(mediumID); - mediumID = gGeoManager->GetMedium(fAbsorber)->GetId(); - SetHcalCuts(mediumID); - mediumID = gGeoManager->GetMedium("Tyvek")->GetId(); - SetHcalCuts(mediumID); - mediumID = gGeoManager->GetMedium("SensVacuum")->GetId(); - SetHcalCuts(mediumID); - mediumID = gGeoManager->GetMedium("ECALAir")->GetId(); - SetHcalCuts(mediumID); - mediumID = gGeoManager->GetMedium("ECALFiber")->GetId(); - SetHcalCuts(mediumID); - mediumID = gGeoManager->GetMedium("ECALTileEdging")->GetId(); - SetHcalCuts(mediumID); - mediumID = gGeoManager->GetMedium("ECALSteel")->GetId(); - SetHcalCuts(mediumID); - } + FairRun* fRun = FairRun::Instance(); + // if (strcmp(fRun->GetName(),"TGeant3") == 0) + { + Int_t mediumID; + mediumID = gGeoManager->GetMedium("Scintillator")->GetId(); + SetHcalCuts(mediumID); + mediumID = gGeoManager->GetMedium(fAbsorber)->GetId(); + SetHcalCuts(mediumID); + mediumID = gGeoManager->GetMedium("Tyvek")->GetId(); + SetHcalCuts(mediumID); + mediumID = gGeoManager->GetMedium("SensVacuum")->GetId(); + SetHcalCuts(mediumID); + mediumID = gGeoManager->GetMedium("ECALAir")->GetId(); + SetHcalCuts(mediumID); + mediumID = gGeoManager->GetMedium("ECALFiber")->GetId(); + SetHcalCuts(mediumID); + mediumID = gGeoManager->GetMedium("ECALTileEdging")->GetId(); + SetHcalCuts(mediumID); + mediumID = gGeoManager->GetMedium("ECALSteel")->GetId(); + SetHcalCuts(mediumID); + } } // ----- Public method ProcessHits -------------------------------------- -Bool_t hcal::ProcessHits(FairVolume* vol) +Bool_t hcal::ProcessHits(FairVolume* vol) { - /** Fill MC point for sensitive ECAL volumes **/ - TString Hcal="Hcal"; - fELoss = gMC->Edep(); - fTrackID = gMC->GetStack()->GetCurrentTrackNumber(); - fTime = gMC->TrackTime()*1.0e09; - fLength = gMC->TrackLength(); - - //if (vol->getVolumeId()==fStructureId) { - if (Hcal.CompareTo(gMC->CurrentVolName())==0) { - if (gMC->IsTrackEntering()) { - FillWallPoint(); - ((ShipStack*)gMC->GetStack())->AddPoint(khcal, fTrackID); - - ResetParameters(); - - return kTRUE; - } else { - return kFALSE; + /** Fill MC point for sensitive ECAL volumes **/ + TString Hcal = "Hcal"; + fELoss = gMC->Edep(); + fTrackID = gMC->GetStack()->GetCurrentTrackNumber(); + fTime = gMC->TrackTime() * 1.0e09; + fLength = gMC->TrackLength(); + + // if (vol->getVolumeId()==fStructureId) { + if (Hcal.CompareTo(gMC->CurrentVolName()) == 0) { + if (gMC->IsTrackEntering()) { + FillWallPoint(); + ((ShipStack*)gMC->GetStack())->AddPoint(khcal, fTrackID); + + ResetParameters(); + + return kTRUE; + } else { + return kFALSE; + } } - } - if (fELoss<=0) return kFALSE; - - if (fELoss>0) - { - Int_t i; - TParticle* p=gMC->GetStack()->GetCurrentTrack(); - Double_t x, y, z; - Double_t px; - Double_t py; - Double_t dx; - Int_t mx; - Int_t my; - Int_t type; - Int_t cx; - Int_t cy; - Int_t layer; - gMC->TrackPosition(x, y, z); -// cout << "Id: " << p->GetPdgCode() << " (" << x << ", " << y << ", "; -// cout << z << "): "; -// cout << endl; -/* - for(i=0;i<10;i++) - { - gMC->CurrentVolOffID(i, mx); cout << i << ":" << mx << ", "; - } - cout << endl; -*/ - if (fSimpleGeo==0) - { - gMC->CurrentVolOffID(1, layer); layer--; - gMC->CurrentVolOffID(2, mx); mx--; - gMC->CurrentVolOffID(3, my); my--; - } - else - { - gMC->CurrentVolOffID(0, layer); layer--; - gMC->CurrentVolOffID(1, mx); mx--; - gMC->CurrentVolOffID(2, my); my--; - } - Int_t id=(my*100+mx)*10; - if (layer>fNLayers1) id++; -// cout << mx << "(" << x << "), " << my << "(" << y << "), layer="<< layer << endl; -/* - Float_t rx; Float_t ry; Int_t ten; - GetCellCoordInf(id, rx, ry, ten); rx--; ry--; - type=fInf->GetType(mx, my); - Float_t d=fInf->GetVariableStrict("modulesize")/type; - if (x>rx-0.001&&xry-0.001&&y 0) { + Int_t i; + TParticle* p = gMC->GetStack()->GetCurrentTrack(); + Double_t x, y, z; + Double_t px; + Double_t py; + Double_t dx; + Int_t mx; + Int_t my; + Int_t type; + Int_t cx; + Int_t cy; + Int_t layer; + gMC->TrackPosition(x, y, z); + // cout << "Id: " << p->GetPdgCode() << " (" << x << ", " << y << ", "; + // cout << z << "): "; + // cout << endl; + /* + for(i=0;i<10;i++) + { + gMC->CurrentVolOffID(i, mx); cout << i << ":" << mx << ", "; + } + cout << endl; + */ + if (fSimpleGeo == 0) { + gMC->CurrentVolOffID(1, layer); + layer--; + gMC->CurrentVolOffID(2, mx); + mx--; + gMC->CurrentVolOffID(3, my); + my--; + } else { + gMC->CurrentVolOffID(0, layer); + layer--; + gMC->CurrentVolOffID(1, mx); + mx--; + gMC->CurrentVolOffID(2, my); + my--; + } + Int_t id = (my * 100 + mx) * 10; + if (layer > fNLayers1) + id++; + // cout << mx << "(" << x << "), " << my << "(" << y << "), layer="<< layer << endl; + /* + Float_t rx; Float_t ry; Int_t ten; + GetCellCoordInf(id, rx, ry, ten); rx--; ry--; + type=fInf->GetType(mx, my); + Float_t d=fInf->GetVariableStrict("modulesize")/type; + if (x>rx-0.001&&xry-0.001&&y= 0 && px < 1 && py >= 0 && py < 1) { + fELoss *= fLightMap->Data(px - 0.5, py - 0.5); + FillLitePoint(0); + } + } else + FillLitePoint(0); + // for(i=0;i<8;i++) + // { + // Int_t t; + // + // gMC->CurrentVolOffID(i, t); + // cout << i << ": " << gMC->CurrentVolOffName(i) << " " << t << "; "; + // } + // cout << endl; } -*/ - fVolumeID=id; - if (fSimpleGeo==0) - { - // An old version - // px=mx*fModuleSize-fHcalSize[0]/2.0+cx*fModuleSize/type; - // py=my*fModuleSize-fHcalSize[1]/2.0+cy*fModuleSize/type; - // With correction for steel tapes and edging - // TODO: Check this - px=mx*fModuleSize-fHcalSize[0]/2.0+fEdging+fThicknessSteel; - py=my*fModuleSize-fHcalSize[1]/2.0+fEdging+fThicknessSteel; - - px=(x-px)/fXCell; - py=(y-py)/fYCell; - if (px>=0&&px<1&&py>=0&&py<1) - { - fELoss*=fLightMap->Data(px-0.5, py-0.5); - FillLitePoint(0); - } - } - else - FillLitePoint(0); -// for(i=0;i<8;i++) -// { -// Int_t t; -// -// gMC->CurrentVolOffID(i, t); -// cout << i << ": " << gMC->CurrentVolOffName(i) << " " << t << "; "; -// } -// cout << endl; - } - ((ShipStack*)gMC->GetStack())->AddPoint(khcal, fTrackID); - - ResetParameters(); - - return kTRUE; + ((ShipStack*)gMC->GetStack())->AddPoint(khcal, fTrackID); + + ResetParameters(); + return kTRUE; } /** returns type of volume **/ Int_t hcal::GetVolType(Int_t volnum) { - Int_t i; - for(i=kN-1;i>-1;i--) { - if (fVolArr[i]==volnum) break; - } + Int_t i; + for (i = kN - 1; i > -1; i--) { + if (fVolArr[i] == volnum) + break; + } - return i; + return i; } //----------------------------------------------------------------------------- void hcal::FillWallPoint() { - /** Fill MC points on the ECAL front wall **/ - - gMC->TrackPosition(fPos); - gMC->TrackMomentum(fMom); - fVolumeID = -1; - Double_t mass = gMC->TrackMass(); - // Calculate kinetic energy - Double_t ekin = TMath::Sqrt( fMom.Px()*fMom.Px() + - fMom.Py()*fMom.Py() + - fMom.Pz()*fMom.Pz() + - mass * mass ) - mass; - fELoss = ekin; - // Create hcalPoint at the entrance of calorimeter - // for particles with pz>0 coming through the front wall - if (fMom.Pz() > 0 && fPos.Z() < fZHcal+0.01) - { - TParticle* part=((ShipStack*)gMC->GetStack())->GetParticle(fTrackID); - AddHit(fTrackID, fVolumeID, TVector3(fPos.X(), fPos.Y(), fPos.Z()), - TVector3(fMom.Px(), fMom.Py(), fMom.Pz()), fTime, fLength, - fELoss, part->GetPdgCode()); - } - fTrackID=gMC->GetStack()->GetCurrentTrackNumber(); + /** Fill MC points on the ECAL front wall **/ + + gMC->TrackPosition(fPos); + gMC->TrackMomentum(fMom); + fVolumeID = -1; + Double_t mass = gMC->TrackMass(); + // Calculate kinetic energy + Double_t ekin = + TMath::Sqrt(fMom.Px() * fMom.Px() + fMom.Py() * fMom.Py() + fMom.Pz() * fMom.Pz() + mass * mass) - mass; + fELoss = ekin; + // Create hcalPoint at the entrance of calorimeter + // for particles with pz>0 coming through the front wall + if (fMom.Pz() > 0 && fPos.Z() < fZHcal + 0.01) { + TParticle* part = ((ShipStack*)gMC->GetStack())->GetParticle(fTrackID); + AddHit(fTrackID, + fVolumeID, + TVector3(fPos.X(), fPos.Y(), fPos.Z()), + TVector3(fMom.Px(), fMom.Py(), fMom.Pz()), + fTime, + fLength, + fELoss, + part->GetPdgCode()); + } + fTrackID = gMC->GetStack()->GetCurrentTrackNumber(); } hcalPoint* hcal::FindHit(Int_t VolId, Int_t TrackId) { - for(Int_t i=fFirstNumber;iGetEntriesFast();i++) - { - hcalPoint* point=(hcalPoint*)fLiteCollection->At(i); - if (point->GetTrackID()==TrackId&&point->GetDetectorID()==VolId) - return point; - } - return NULL; + for (Int_t i = fFirstNumber; i < fLiteCollection->GetEntriesFast(); i++) { + hcalPoint* point = (hcalPoint*)fLiteCollection->At(i); + if (point->GetTrackID() == TrackId && point->GetDetectorID() == VolId) + return point; + } + return NULL; } //----------------------------------------------------------------------------- Bool_t hcal::FillLitePoint(Int_t volnum) { - /** Fill MC points inside the ECAL for non-zero deposited energy **/ - - //Search for input track - - static Float_t zmin=fZHcal-0.0001; - static Float_t zmax=fZHcal+fHcalSize[2]; - static Float_t xhcal=fHcalSize[0]/2; - static Float_t yhcal=fHcalSize[1]/2; - TParticle* part=gMC->GetStack()->GetCurrentTrack(); - fTrackID=gMC->GetStack()->GetCurrentTrackNumber(); - -// cout << zmin << " : " << zmax << " : " << xhcal << ", " << yhcal << endl; -// cout << part->GetFirstMother() << " : " << part->Vx() << ", " << part->Vy() << ", " << part->Vz() << endl; - /** Need to rewrite this part **/ - while (part->GetFirstMother()>=0&&part->Vz()>=zmin&&part->Vz()<=zmax&&TMath::Abs(part->Vx())<=xhcal&&TMath::Abs(part->Vy())<=yhcal) - { - fTrackID=part->GetFirstMother(); - part =((ShipStack*)gMC->GetStack())->GetParticle(fTrackID); -// cout << "-> " << part->GetFirstMother() << " : " << part->Vx() << ", " << part->Vy() << ", " << part->Vz() << endl; + /** Fill MC points inside the ECAL for non-zero deposited energy **/ + + // Search for input track + + static Float_t zmin = fZHcal - 0.0001; + static Float_t zmax = fZHcal + fHcalSize[2]; + static Float_t xhcal = fHcalSize[0] / 2; + static Float_t yhcal = fHcalSize[1] / 2; + TParticle* part = gMC->GetStack()->GetCurrentTrack(); + fTrackID = gMC->GetStack()->GetCurrentTrackNumber(); + + // cout << zmin << " : " << zmax << " : " << xhcal << ", " << yhcal << endl; + // cout << part->GetFirstMother() << " : " << part->Vx() << ", " << part->Vy() << ", " << part->Vz() << endl; + /** Need to rewrite this part **/ + while (part->GetFirstMother() >= 0 && part->Vz() >= zmin && part->Vz() <= zmax && TMath::Abs(part->Vx()) <= xhcal + && TMath::Abs(part->Vy()) <= yhcal) { + fTrackID = part->GetFirstMother(); + part = ((ShipStack*)gMC->GetStack())->GetParticle(fTrackID); + // cout << "-> " << part->GetFirstMother() << " : " << part->Vx() << ", " << part->Vy() << ", " << + // part->Vz() << endl; } // if (part->Vz()>500) // cout << part->Vx() << ", " << part->Vy() << ", " << part->Vz() << endl; #ifdef _DECAL - if (fTrackID<0) cout<<"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!fTrackID="<GetEntriesFast(); - cout << "-I- hcal: " << nLiteHits << " lite points registered in this event."; - cout << endl; - - if (fVerboseLevel>1) - { - for (i=0;iPrint(); - for (i=0;iPrint(); - } + Int_t nHits = fHcalCollection->GetEntriesFast(); + Int_t nLiteHits; + Int_t i; + + cout << "-I- hcal: " << nHits << " points registered in this event."; + cout << endl; + + nLiteHits = fLiteCollection->GetEntriesFast(); + cout << "-I- hcal: " << nLiteHits << " lite points registered in this event."; + cout << endl; + + if (fVerboseLevel > 1) { + for (i = 0; i < nHits; i++) + (*fHcalCollection)[i]->Print(); + for (i = 0; i < nLiteHits; i++) + (*fLiteCollection)[i]->Print(); + } } // ------------------------------------------------------------------------- // ----- Public method CopyClones -------------------------------------- void hcal::CopyClones(TClonesArray* cl1, TClonesArray* cl2, Int_t offset) { - Int_t nEntries = cl1->GetEntriesFast(); - Int_t i; - Int_t index; - cout << "-I- hcal: " << nEntries << " entries to add." << endl; - TClonesArray& clref = *cl2; - if (cl1->GetClass()==hcalPoint::Class()) { - hcalPoint* oldpoint = NULL; - for (i=0; iAt(i); - index = oldpoint->GetTrackID()+offset; - oldpoint->SetTrackID(index); - new (clref[fPosIndex]) hcalPoint(*oldpoint); - fPosIndex++; - } - cout << "-I- hcal: " << cl2->GetEntriesFast() << " merged entries." - << endl; - } - else if (cl1->GetClass()==hcalPoint::Class()) { - hcalPoint* oldpoint = NULL; - for (i=0; iAt(i); - index = oldpoint->GetTrackID()+offset; - oldpoint->SetTrackID(index); - new (clref[fPosIndex]) hcalPoint(*oldpoint); - fPosIndex++; + Int_t nEntries = cl1->GetEntriesFast(); + Int_t i; + Int_t index; + cout << "-I- hcal: " << nEntries << " entries to add." << endl; + TClonesArray& clref = *cl2; + if (cl1->GetClass() == hcalPoint::Class()) { + hcalPoint* oldpoint = NULL; + for (i = 0; i < nEntries; i++) { + oldpoint = (hcalPoint*)cl1->At(i); + index = oldpoint->GetTrackID() + offset; + oldpoint->SetTrackID(index); + new (clref[fPosIndex]) hcalPoint(*oldpoint); + fPosIndex++; + } + cout << "-I- hcal: " << cl2->GetEntriesFast() << " merged entries." << endl; + } else if (cl1->GetClass() == hcalPoint::Class()) { + hcalPoint* oldpoint = NULL; + for (i = 0; i < nEntries; i++) { + oldpoint = (hcalPoint*)cl1->At(i); + index = oldpoint->GetTrackID() + offset; + oldpoint->SetTrackID(index); + new (clref[fPosIndex]) hcalPoint(*oldpoint); + fPosIndex++; + } + cout << "-I- hcal: " << cl2->GetEntriesFast() << " merged entries." << endl; } - cout << "-I- hcal: " << cl2->GetEntriesFast() << " merged entries." - << endl; - } } // ------------------------------------------------------------------------- // ----- Public method Register ---------------------------------------- void hcal::Register() { - FairRootManager::Instance()->Register("HcalPoint","Hcal",fHcalCollection,kTRUE); - FairRootManager::Instance()->Register("HcalPointLite","HcalLite",fLiteCollection,kTRUE); - ; + FairRootManager::Instance()->Register("HcalPoint", "Hcal", fHcalCollection, kTRUE); + FairRootManager::Instance()->Register("HcalPointLite", "HcalLite", fLiteCollection, kTRUE); + ; } // ------------------------------------------------------------------------- // ----- Public method ConstructGeometry ------------------------------- void hcal::ConstructGeometry() { - FairGeoLoader*geoLoad = FairGeoLoader::Instance(); - FairGeoInterface *geoFace = geoLoad->getGeoInterface(); - FairGeoMedia *Media = geoFace->getMedia(); - FairGeoBuilder *geobuild=geoLoad->getGeoBuilder(); - - TGeoVolume *top=gGeoManager->GetTopVolume(); - - // cout << top->GetName() << endl; - TGeoVolume *volume; - FairGeoMedium *CbmMedium; - TGeoPgon *spl; - - Float_t *buf = 0; - Int_t i; - Double_t par[10]; - Float_t y; - TString nm; - Double_t thickness=fThicknessAbsorber+fThicknessScin+fThicknessTyvk*2; - Double_t moduleth=thickness*fNLayers; -// Float_t sumWeight; -// Int_t i; - - // create SensVacuum which is defined in the media file - - /** Initialize all media **/ - InitMedia(); - par[0]=fSemiX; - par[1]=fSemiY; - par[2]=fHcalSize[2]/2.0; - - if (!IsActive()){ - Double_t fudgeFactor = 6.34 / 13.7 ; // to have same interaction length as before - par[2] = par[2]*fudgeFactor; - volume=gGeoManager->Volume("Hcal", "BOX", gGeoManager->GetMedium("iron")->GetId(), par, 3); - gGeoManager->Node("Hcal", 1, top->GetName(), 0.0,0.0, fZHcal, 0, kTRUE, buf, 0); - return; - } - - volume=gGeoManager->Volume("Hcal", "BOX", gGeoManager->GetMedium("SensVacuum")->GetId(), par, 3); - gGeoManager->Node("Hcal", 1, top->GetName(), 0.0,0.0, fZHcal, 0, kTRUE, buf, 0); - volume->SetVisLeaves(kTRUE); - volume->SetVisContainers(kFALSE); - volume->SetVisibility(kFALSE); - - - AddSensitiveVolume(volume); - fStructureId=volume->GetNumber(); - - if (fFastMC==0) - { - if (fSimpleGeo==0) - ConstructModule(); - else - ConstructModuleSimple(); - - TGeoVolume* vol=new TGeoVolumeAssembly("HcalStructure"); -//To suppress warring - vol->SetMedium(gGeoManager->GetMedium("SensVacuum")); - for(i=0;iGetName(); - y=(i-fYSize/2.0+0.5)*fModuleSize; - gGeoManager->Node(nm.Data(), i+1, "HcalStructure", 0.0, y, 0.0, 0, kTRUE, buf, 0); + FairGeoLoader* geoLoad = FairGeoLoader::Instance(); + FairGeoInterface* geoFace = geoLoad->getGeoInterface(); + FairGeoMedia* Media = geoFace->getMedia(); + FairGeoBuilder* geobuild = geoLoad->getGeoBuilder(); + + TGeoVolume* top = gGeoManager->GetTopVolume(); + + // cout << top->GetName() << endl; + TGeoVolume* volume; + FairGeoMedium* CbmMedium; + TGeoPgon* spl; + + Float_t* buf = 0; + Int_t i; + Double_t par[10]; + Float_t y; + TString nm; + Double_t thickness = fThicknessAbsorber + fThicknessScin + fThicknessTyvk * 2; + Double_t moduleth = thickness * fNLayers; + // Float_t sumWeight; + // Int_t i; + + // create SensVacuum which is defined in the media file + + /** Initialize all media **/ + InitMedia(); + par[0] = fSemiX; + par[1] = fSemiY; + par[2] = fHcalSize[2] / 2.0; + + if (!IsActive()) { + Double_t fudgeFactor = 6.34 / 13.7; // to have same interaction length as before + par[2] = par[2] * fudgeFactor; + volume = gGeoManager->Volume("Hcal", "BOX", gGeoManager->GetMedium("iron")->GetId(), par, 3); + gGeoManager->Node("Hcal", 1, top->GetName(), 0.0, 0.0, fZHcal, 0, kTRUE, buf, 0); + return; + } + + volume = gGeoManager->Volume("Hcal", "BOX", gGeoManager->GetMedium("SensVacuum")->GetId(), par, 3); + gGeoManager->Node("Hcal", 1, top->GetName(), 0.0, 0.0, fZHcal, 0, kTRUE, buf, 0); + volume->SetVisLeaves(kTRUE); + volume->SetVisContainers(kFALSE); + volume->SetVisibility(kFALSE); + + AddSensitiveVolume(volume); + fStructureId = volume->GetNumber(); + + if (fFastMC == 0) { + if (fSimpleGeo == 0) + ConstructModule(); + else + ConstructModuleSimple(); + + TGeoVolume* vol = new TGeoVolumeAssembly("HcalStructure"); + // To suppress warring + vol->SetMedium(gGeoManager->GetMedium("SensVacuum")); + for (i = 0; i < fYSize; i++) { + volume = ConstructRaw(i); + if (volume == NULL) { + continue; + } + nm = volume->GetName(); + y = (i - fYSize / 2.0 + 0.5) * fModuleSize; + gGeoManager->Node(nm.Data(), i + 1, "HcalStructure", 0.0, y, 0.0, 0, kTRUE, buf, 0); + } + // TODO: + // Should move the guarding volume, not structure itself + gGeoManager->Node("HcalStructure", 1, "Hcal", fDX, fDY, 0.0, 0, kTRUE, buf, 0); } -//TODO: -//Should move the guarding volume, not structure itself - gGeoManager->Node("HcalStructure", 1, "Hcal", fDX, fDY, 0.0, 0, kTRUE, buf, 0); - } } // ------------------------------------------------------------------------- // ----- Public method ConstructRaw ---------------------------------------- TGeoVolume* hcal::ConstructRaw(Int_t num) { - Int_t i; - list >::const_iterator p=fRawNumber.begin(); - pair out; - Float_t x; - Float_t* buf=NULL; - for(i=0;iGetType(i, num)!=0) break; - if (i==fXSize) - return NULL; - for(;p!=fRawNumber.end();++p) - { - for(i=0;iGetType(i, num)!=fInf->GetType(i, (*p).first)) - break; - if (i==fXSize) - break; - } - if (p!=fRawNumber.end()) - return (*p).second; - TString nm="HCALRaw"; nm+=num; - TString md; - TGeoVolume* vol=new TGeoVolumeAssembly(nm); -//To suppress warring - vol->SetMedium(gGeoManager->GetMedium("SensVacuum")); - for(i=0;iGetType(i, num)==0) continue; - md="HcalModule"; - gGeoManager->Node(md.Data(),i+1, nm.Data(), x, 0.0, 0.0, 0, kTRUE, buf, 0); - } - - out.first=num; - out.second=vol; - fRawNumber.push_back(out); - return out.second; + Int_t i; + list>::const_iterator p = fRawNumber.begin(); + pair out; + Float_t x; + Float_t* buf = NULL; + for (i = 0; i < fXSize; i++) + if ((Int_t)fInf->GetType(i, num) != 0) + break; + if (i == fXSize) + return NULL; + for (; p != fRawNumber.end(); ++p) { + for (i = 0; i < fXSize; i++) + if (fInf->GetType(i, num) != fInf->GetType(i, (*p).first)) + break; + if (i == fXSize) + break; + } + if (p != fRawNumber.end()) + return (*p).second; + TString nm = "HCALRaw"; + nm += num; + TString md; + TGeoVolume* vol = new TGeoVolumeAssembly(nm); + // To suppress warring + vol->SetMedium(gGeoManager->GetMedium("SensVacuum")); + for (i = 0; i < fXSize; i++) { + x = (i - fXSize / 2.0 + 0.5) * fModuleSize; + if (fInf->GetType(i, num) == 0) + continue; + md = "HcalModule"; + gGeoManager->Node(md.Data(), i + 1, nm.Data(), x, 0.0, 0.0, 0, kTRUE, buf, 0); + } + + out.first = num; + out.second = vol; + fRawNumber.push_back(out); + return out.second; } // ------------------------------------------------------------------------- - // ----- Public method BeginEvent ----------------------------------------- void hcal::BeginEvent() { - ; + ; } // ------------------------------------------------------------------------- - // ------------------------------------------------------------------------- // ----- Private method AddHit ----------------------------------------- -hcalPoint* hcal::AddHit(Int_t trackID, Int_t detID, TVector3 pos, - TVector3 mom, Double_t time, Double_t length, - Double_t eLoss, Int_t pdgcode) +hcalPoint* hcal::AddHit(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t time, + Double_t length, + Double_t eLoss, + Int_t pdgcode) { - TClonesArray& clref = *fHcalCollection; - Int_t size = clref.GetEntriesFast(); - return new(clref[size]) hcalPoint(trackID, detID, pos, mom, - time, length, eLoss, pdgcode); + TClonesArray& clref = *fHcalCollection; + Int_t size = clref.GetEntriesFast(); + return new (clref[size]) hcalPoint(trackID, detID, pos, mom, time, length, eLoss, pdgcode); } // ------------------------------------------------------------------------- // ----- Private method AddHit ----------------------------------------- hcalPoint* hcal::AddLiteHit(Int_t trackID, Int_t detID, Double32_t time, Double32_t eLoss) { - TClonesArray& clref = *fLiteCollection; - Int_t size = clref.GetEntriesFast(); - return new(clref[size]) hcalPoint(trackID, detID, time, eLoss); + TClonesArray& clref = *fLiteCollection; + Int_t size = clref.GetEntriesFast(); + return new (clref[size]) hcalPoint(trackID, detID, time, eLoss); } // ------------------------------------------------------------------------- // ----- Private method ConstructModule ---------------------------------- void hcal::ConstructModule() { - if (fModule!=NULL) return; - - ConstructTile(0); - ConstructTile(1); - if (fThicknessTyvk>0) ConstructTile(2); - - TString nm="HcalModule"; - TString nm1; - TString cellname="HcalCell"; - TString scin="ScTile"; - TString lead="LeadTile"; - TString tyvek="TvTile"; - Int_t i; - Int_t j; - Int_t n; - Float_t x; - Float_t y; - Float_t* buf=NULL; - Double_t thickness=fThicknessAbsorber+fThicknessScin+fThicknessTyvk*2; - Double_t moduleth=thickness*fNLayers; - Double_t par[3]={fModuleSize/2.0, fModuleSize/2.0, moduleth/2.0}; - - if (fSteelTapes[0]==NULL) - { - TGeoBBox* st1=new TGeoBBox(fThicknessSteel/2.0, fModuleSize/2.0-fThicknessSteel, moduleth/2.0); - nm1="HcalModuleSteelTape1"; - fSteelTapes[0]=new TGeoVolume(nm1.Data(), st1, gGeoManager->GetMedium("ECALSteel")); - } - if (fSteelTapes[1]==NULL) - { - TGeoBBox* st2=new TGeoBBox(fModuleSize/2.0-fThicknessSteel, fThicknessSteel/2.0, moduleth/2.0); - nm1="HcalModuleSteelTape2"; - fSteelTapes[1]=new TGeoVolume(nm1.Data(), st2, gGeoManager->GetMedium("ECALSteel")); - } - - -// TGeoVolume* modulev=new TGeoVolumeAssembly(nm); - TGeoVolume* modulev=gGeoManager->Volume(nm.Data(), "BOX", gGeoManager->GetMedium("ECALAir")->GetId(), par, 3); - modulev->SetLineColor(kOrange+3); - for(i=0;iNode(scin.Data(), i+1, nm.Data(), 0.0, 0.0, -thickness*fNLayers/2.0+fThicknessScin/2.0+i*thickness, 0, kTRUE, buf, 0); - gGeoManager->Node(lead.Data(), i+1, nm.Data(), 0.0, 0.0, -thickness*fNLayers/2.0+fThicknessScin+i*thickness+fThicknessTyvk+fThicknessAbsorber/2.0, 0, kTRUE, buf, 0); - if (fThicknessTyvk>0.0) - { - gGeoManager->Node(tyvek.Data(), 2*i+1, nm.Data(), 0.0, 0.0, -thickness*fNLayers/2.0+fThicknessScin+i*thickness+1.5*fThicknessTyvk+fThicknessAbsorber, 0, kTRUE, buf, 0); - gGeoManager->Node(tyvek.Data(), 2*i+2, nm.Data(), 0.0, 0.0, -thickness*fNLayers/2.0+fThicknessScin+i*thickness+0.5*fThicknessTyvk, 0, kTRUE, buf, 0); + if (fModule != NULL) + return; + + ConstructTile(0); + ConstructTile(1); + if (fThicknessTyvk > 0) + ConstructTile(2); + + TString nm = "HcalModule"; + TString nm1; + TString cellname = "HcalCell"; + TString scin = "ScTile"; + TString lead = "LeadTile"; + TString tyvek = "TvTile"; + Int_t i; + Int_t j; + Int_t n; + Float_t x; + Float_t y; + Float_t* buf = NULL; + Double_t thickness = fThicknessAbsorber + fThicknessScin + fThicknessTyvk * 2; + Double_t moduleth = thickness * fNLayers; + Double_t par[3] = {fModuleSize / 2.0, fModuleSize / 2.0, moduleth / 2.0}; + + if (fSteelTapes[0] == NULL) { + TGeoBBox* st1 = new TGeoBBox(fThicknessSteel / 2.0, fModuleSize / 2.0 - fThicknessSteel, moduleth / 2.0); + nm1 = "HcalModuleSteelTape1"; + fSteelTapes[0] = new TGeoVolume(nm1.Data(), st1, gGeoManager->GetMedium("ECALSteel")); + } + if (fSteelTapes[1] == NULL) { + TGeoBBox* st2 = new TGeoBBox(fModuleSize / 2.0 - fThicknessSteel, fThicknessSteel / 2.0, moduleth / 2.0); + nm1 = "HcalModuleSteelTape2"; + fSteelTapes[1] = new TGeoVolume(nm1.Data(), st2, gGeoManager->GetMedium("ECALSteel")); } - } - nm1="HcalModuleSteelTape1"; - gGeoManager->Node(nm1.Data(), 1, nm.Data(), -fThicknessSteel/2.0+fModuleSize/2.0, 0.0, 0.0, 0, kTRUE, buf, 0); - gGeoManager->Node(nm1.Data(), 2, nm.Data(), +fThicknessSteel/2.0-fModuleSize/2.0, 0.0, 0.0, 0, kTRUE, buf, 0); - nm1="HcalModuleSteelTape2"; - gGeoManager->Node(nm1.Data(), 1, nm.Data(), 0.0, -fThicknessSteel/2.0+fModuleSize/2.0, 0.0, 0, kTRUE, buf, 0); - gGeoManager->Node(nm1.Data(), 2, nm.Data(), 0.0, +fThicknessSteel/2.0-fModuleSize/2.0, 0.0, 0, kTRUE, buf, 0); + // TGeoVolume* modulev=new TGeoVolumeAssembly(nm); + TGeoVolume* modulev = gGeoManager->Volume(nm.Data(), "BOX", gGeoManager->GetMedium("ECALAir")->GetId(), par, 3); + modulev->SetLineColor(kOrange + 3); + for (i = 0; i < fNLayers; i++) { + gGeoManager->Node(scin.Data(), + i + 1, + nm.Data(), + 0.0, + 0.0, + -thickness * fNLayers / 2.0 + fThicknessScin / 2.0 + i * thickness, + 0, + kTRUE, + buf, + 0); + gGeoManager->Node(lead.Data(), + i + 1, + nm.Data(), + 0.0, + 0.0, + -thickness * fNLayers / 2.0 + fThicknessScin + i * thickness + fThicknessTyvk + + fThicknessAbsorber / 2.0, + 0, + kTRUE, + buf, + 0); + if (fThicknessTyvk > 0.0) { + gGeoManager->Node(tyvek.Data(), + 2 * i + 1, + nm.Data(), + 0.0, + 0.0, + -thickness * fNLayers / 2.0 + fThicknessScin + i * thickness + 1.5 * fThicknessTyvk + + fThicknessAbsorber, + 0, + kTRUE, + buf, + 0); + gGeoManager->Node(tyvek.Data(), + 2 * i + 2, + nm.Data(), + 0.0, + 0.0, + -thickness * fNLayers / 2.0 + fThicknessScin + i * thickness + 0.5 * fThicknessTyvk, + 0, + kTRUE, + buf, + 0); + } + } + + nm1 = "HcalModuleSteelTape1"; + gGeoManager->Node(nm1.Data(), 1, nm.Data(), -fThicknessSteel / 2.0 + fModuleSize / 2.0, 0.0, 0.0, 0, kTRUE, buf, 0); + gGeoManager->Node(nm1.Data(), 2, nm.Data(), +fThicknessSteel / 2.0 - fModuleSize / 2.0, 0.0, 0.0, 0, kTRUE, buf, 0); + nm1 = "HcalModuleSteelTape2"; + gGeoManager->Node(nm1.Data(), 1, nm.Data(), 0.0, -fThicknessSteel / 2.0 + fModuleSize / 2.0, 0.0, 0, kTRUE, buf, 0); + gGeoManager->Node(nm1.Data(), 2, nm.Data(), 0.0, +fThicknessSteel / 2.0 - fModuleSize / 2.0, 0.0, 0, kTRUE, buf, 0); - fModuleLength=moduleth; - fModule=modulev; + fModuleLength = moduleth; + fModule = modulev; } // ------------------------------------------------------------------------- // ----- Private method ConstructModuleSimple----------------------------- void hcal::ConstructModuleSimple() { - if (fModule!=NULL) return; - - ConstructTileSimple(0); - ConstructTileSimple(1); - if (fThicknessTyvk>0) ConstructTileSimple(2); - - TString nm="HcalModule"; - TString nm1; - TString cellname="HcalCell"; - TString scin="ScTile"; - TString lead="LeadTile"; - TString tyvek="TvTile"; - Int_t i; - Int_t j; - Int_t n; - Float_t x; - Float_t y; - Float_t* buf=NULL; - Double_t thickness=fThicknessAbsorber+fThicknessScin+fThicknessTyvk*2; - Double_t moduleth=thickness*fNLayers; - Double_t par[3]={fModuleSize/2.0, fModuleSize/2.0, moduleth/2.0}; - -// TGeoVolume* modulev=new TGeoVolumeAssembly(nm); - TGeoVolume* modulev=gGeoManager->Volume(nm.Data(), "BOX", gGeoManager->GetMedium("ECALAir")->GetId(), par, 3); - modulev->SetLineColor(kOrange+3); - for(i=0;iNode(scin.Data(), i+1, nm.Data(), 0.0, 0.0, -thickness*fNLayers/2.0+fThicknessScin/2.0+i*thickness, 0, kTRUE, buf, 0); - gGeoManager->Node(lead.Data(), i+1, nm.Data(), 0.0, 0.0, -thickness*fNLayers/2.0+fThicknessScin+i*thickness+fThicknessTyvk+fThicknessAbsorber/2.0, 0, kTRUE, buf, 0); - if (fThicknessTyvk>0.0) - { - gGeoManager->Node(tyvek.Data(), 2*i+1, nm.Data(), 0.0, 0.0, -thickness*fNLayers/2.0+fThicknessScin+i*thickness+1.5*fThicknessTyvk+fThicknessAbsorber, 0, kTRUE, buf, 0); - gGeoManager->Node(tyvek.Data(), 2*i+2, nm.Data(), 0.0, 0.0, -thickness*fNLayers/2.0+fThicknessScin+i*thickness+0.5*fThicknessTyvk, 0, kTRUE, buf, 0); + if (fModule != NULL) + return; + + ConstructTileSimple(0); + ConstructTileSimple(1); + if (fThicknessTyvk > 0) + ConstructTileSimple(2); + + TString nm = "HcalModule"; + TString nm1; + TString cellname = "HcalCell"; + TString scin = "ScTile"; + TString lead = "LeadTile"; + TString tyvek = "TvTile"; + Int_t i; + Int_t j; + Int_t n; + Float_t x; + Float_t y; + Float_t* buf = NULL; + Double_t thickness = fThicknessAbsorber + fThicknessScin + fThicknessTyvk * 2; + Double_t moduleth = thickness * fNLayers; + Double_t par[3] = {fModuleSize / 2.0, fModuleSize / 2.0, moduleth / 2.0}; + + // TGeoVolume* modulev=new TGeoVolumeAssembly(nm); + TGeoVolume* modulev = gGeoManager->Volume(nm.Data(), "BOX", gGeoManager->GetMedium("ECALAir")->GetId(), par, 3); + modulev->SetLineColor(kOrange + 3); + for (i = 0; i < fNLayers; i++) { + gGeoManager->Node(scin.Data(), + i + 1, + nm.Data(), + 0.0, + 0.0, + -thickness * fNLayers / 2.0 + fThicknessScin / 2.0 + i * thickness, + 0, + kTRUE, + buf, + 0); + gGeoManager->Node(lead.Data(), + i + 1, + nm.Data(), + 0.0, + 0.0, + -thickness * fNLayers / 2.0 + fThicknessScin + i * thickness + fThicknessTyvk + + fThicknessAbsorber / 2.0, + 0, + kTRUE, + buf, + 0); + if (fThicknessTyvk > 0.0) { + gGeoManager->Node(tyvek.Data(), + 2 * i + 1, + nm.Data(), + 0.0, + 0.0, + -thickness * fNLayers / 2.0 + fThicknessScin + i * thickness + 1.5 * fThicknessTyvk + + fThicknessAbsorber, + 0, + kTRUE, + buf, + 0); + gGeoManager->Node(tyvek.Data(), + 2 * i + 2, + nm.Data(), + 0.0, + 0.0, + -thickness * fNLayers / 2.0 + fThicknessScin + i * thickness + 0.5 * fThicknessTyvk, + 0, + kTRUE, + buf, + 0); + } } - } - fModuleLength=moduleth; - fModule=modulev; + fModuleLength = moduleth; + fModule = modulev; } // ------------------------------------------------------------------------- // ----- Private method InitMedium --------------------------------------- Int_t hcal::InitMedium(const char* name) { - static FairGeoLoader *geoLoad=FairGeoLoader::Instance(); - static FairGeoInterface *geoFace=geoLoad->getGeoInterface(); - static FairGeoMedia *media=geoFace->getMedia(); - static FairGeoBuilder *geoBuild=geoLoad->getGeoBuilder(); - - FairGeoMedium *CbmMedium=media->getMedium(name); - - if (!CbmMedium) - { - Fatal("InitMedium","Material %s not defined in media file.", name); - return -1111; - } - TGeoMedium* medium=gGeoManager->GetMedium(name); - if (medium!=NULL) - return CbmMedium->getMediumIndex(); - - return geoBuild->createMedium(CbmMedium); + static FairGeoLoader* geoLoad = FairGeoLoader::Instance(); + static FairGeoInterface* geoFace = geoLoad->getGeoInterface(); + static FairGeoMedia* media = geoFace->getMedia(); + static FairGeoBuilder* geoBuild = geoLoad->getGeoBuilder(); + + FairGeoMedium* CbmMedium = media->getMedium(name); + + if (!CbmMedium) { + Fatal("InitMedium", "Material %s not defined in media file.", name); + return -1111; + } + TGeoMedium* medium = gGeoManager->GetMedium(name); + if (medium != NULL) + return CbmMedium->getMediumIndex(); + + return geoBuild->createMedium(CbmMedium); } // ------------------------------------------------------------------------- // ----- Private method InitMedia ---------------------------------------- void hcal::InitMedia() { - Info("InitMedia", "Initializing media."); - InitMedium("SensVacuum"); - InitMedium("ECALVacuum"); - InitMedium(fAbsorber.Data()); - InitMedium("Scintillator"); - InitMedium("Tyvek"); - InitMedium("ECALAir"); - InitMedium("ECALFiber"); - InitMedium("ECALSteel"); - InitMedium("ECALTileEdging"); + Info("InitMedia", "Initializing media."); + InitMedium("SensVacuum"); + InitMedium("ECALVacuum"); + InitMedium(fAbsorber.Data()); + InitMedium("Scintillator"); + InitMedium("Tyvek"); + InitMedium("ECALAir"); + InitMedium("ECALFiber"); + InitMedium("ECALSteel"); + InitMedium("ECALTileEdging"); } // ------------------------------------------------------------------------- // ----- Private method ConstructTile ------------------------------------ void hcal::ConstructTile(Int_t material) { - switch (material) - { - case 0: if (fScTile!=NULL) return; break; - case 1: if (fPbTile!=NULL) return; break; - case 2: if (fTvTile!=NULL) return; break; - default: Error("ConstructTile", "Can't construct a tile of type %d.", material); - } - Double_t thickness; - TGeoVolume* hole; - TGeoVolume* fiber; - TGeoTranslation** tr; - TGeoTranslation* tm; - Int_t nh=fNH; - Int_t i; - Int_t j; - TString nm; - TString nm1; - TString nm2; - TString medium; - Double_t x; - Double_t y; - TGeoBBox* tile; - TGeoVolume* tilev; - TGeoBBox* edging; - TGeoVolume* edgingv; - Double_t* buf=NULL; - - switch (material) - { - case 0: thickness=fThicknessScin/2.0; break; - case 1: thickness=fThicknessAbsorber/2.0; break; - case 2: thickness=fThicknessTyvk/2.0; break; - default: Error("ConstructTile", "Can't construct a tile of type %d.", material); - } - - if (thickness<=0.0) return; - // Holes in the tiles - if (fHoleRad>0) - { - nm1="ECALHole_"; nm1+=material; - nm2="ECALFiber_"; nm2+=material; - if (fHoleVol[material]==NULL) - { - TGeoTube* holetube=new TGeoTube(0, fHoleRad, thickness); - fHoleVol[material]=new TGeoVolume(nm1.Data(), holetube, gGeoManager->GetMedium("ECALAir")); + switch (material) { + case 0: + if (fScTile != NULL) + return; + break; + case 1: + if (fPbTile != NULL) + return; + break; + case 2: + if (fTvTile != NULL) + return; + break; + default: + Error("ConstructTile", "Can't construct a tile of type %d.", material); } - hole=fHoleVol[material]; - // Fibers in holes - if (fFiberRad>0) - { - if (fFiberVol[material]==NULL) + Double_t thickness; + TGeoVolume* hole; + TGeoVolume* fiber; + TGeoTranslation** tr; + TGeoTranslation* tm; + Int_t nh = fNH; + Int_t i; + Int_t j; + TString nm; + TString nm1; + TString nm2; + TString medium; + Double_t x; + Double_t y; + TGeoBBox* tile; + TGeoVolume* tilev; + TGeoBBox* edging; + TGeoVolume* edgingv; + Double_t* buf = NULL; + + switch (material) { + case 0: + thickness = fThicknessScin / 2.0; + break; + case 1: + thickness = fThicknessAbsorber / 2.0; + break; + case 2: + thickness = fThicknessTyvk / 2.0; + break; + default: + Error("ConstructTile", "Can't construct a tile of type %d.", material); + } + + if (thickness <= 0.0) + return; + // Holes in the tiles + if (fHoleRad > 0) { + nm1 = "ECALHole_"; + nm1 += material; + nm2 = "ECALFiber_"; + nm2 += material; + if (fHoleVol[material] == NULL) { + TGeoTube* holetube = new TGeoTube(0, fHoleRad, thickness); + fHoleVol[material] = new TGeoVolume(nm1.Data(), holetube, gGeoManager->GetMedium("ECALAir")); + } + hole = fHoleVol[material]; + // Fibers in holes + if (fFiberRad > 0) { + if (fFiberVol[material] == NULL) { + TGeoTube* fibertube = new TGeoTube(0, fFiberRad, thickness); + fFiberVol[material] = new TGeoVolume(nm2.Data(), fibertube, gGeoManager->GetMedium("ECALFiber")); + gGeoManager->Node(nm2.Data(), 1, nm1.Data(), 0.0, 0.0, 0.0, 0, kTRUE, buf, 0); + } + fiber = fFiberVol[material]; + // TODO: Cerenkoff !!! + // AddSensitiveVolume(fiber); + } + } + /* + if (fHolePos==NULL) { - TGeoTube* fibertube=new TGeoTube(0, fFiberRad, thickness); - fFiberVol[material]=new TGeoVolume(nm2.Data(), fibertube, gGeoManager->GetMedium("ECALFiber")); - gGeoManager->Node(nm2.Data(), 1, nm1.Data(), 0.0, 0.0, 0.0, 0, kTRUE, buf, 0); + tr=new TGeoTranslation*[nh*nh]; + for(i=0;iAddTransformation(tm); + tr[j*nh+i]=tm; + } + fHolePos=tr; } - fiber=fFiberVol[material]; - // TODO: Cerenkoff !!! - //AddSensitiveVolume(fiber); + tr=fHolePos; + */ + /** Building tile **/ + switch (material) { + case 0: + nm = "ScTile"; + medium = "Scintillator"; + break; + case 1: + nm = "LeadTile"; + medium = fAbsorber; + break; + case 2: + nm = "TvTile"; + medium = "Tyvek"; + break; + default: + Error("ConstructTile", "Can't construct a tile of type %d.", material); } - } -/* - if (fHolePos==NULL) - { - tr=new TGeoTranslation*[nh*nh]; - for(i=0;iAddTransformation(tm); - tr[j*nh+i]=tm; + if (material == 0) + tile = new TGeoBBox(fXCell / 2.0, fYCell / 2.0, thickness); + else + tile = new TGeoBBox(fXCell / 2.0 + fEdging, fYCell / 2.0 + fEdging, thickness); + tilev = new TGeoVolume(nm, tile, gGeoManager->GetMedium(medium)); + if (fHoleRad > 0) { + nm1 = "ECALHole_"; + nm1 += material; + for (i = 0; i < nh; i++) + for (j = 0; j < nh; j++) { + x = (i - nh / 2 + 0.5) * fXCell / nh; + y = (j - nh / 2 + 0.5) * fYCell / nh; + gGeoManager->Node(nm1.Data(), j * nh + i + 1, nm.Data(), x, y, 0.0, 0, kTRUE, buf, 0); + } + // clear fiber + if (nh % 2 == 0 && fCF != 0) + gGeoManager->Node(nm1.Data(), j * nh + i + 1, nm.Data(), 0.0, 0.0, 0.0, 0, kTRUE, buf, 0); } - fHolePos=tr; - } - tr=fHolePos; -*/ - /** Building tile **/ - switch (material) - { - case 0: nm="ScTile"; medium="Scintillator"; break; - case 1: nm="LeadTile"; medium=fAbsorber; break; - case 2: nm="TvTile"; medium="Tyvek"; break; - default: Error("ConstructTile", "Can't construct a tile of type %d.", material); - } - - if (material==0) - tile=new TGeoBBox(fXCell/2.0, fYCell/2.0, thickness); - else - tile=new TGeoBBox(fXCell/2.0+fEdging, fYCell/2.0+fEdging, thickness); - tilev=new TGeoVolume(nm, tile, gGeoManager->GetMedium(medium)); - if (fHoleRad>0) - { - nm1="ECALHole_"; nm1+=material; - for(i=0;iNode(nm1.Data(), j*nh+i+1, nm.Data(), x, y, 0.0, 0, kTRUE, buf, 0); + /* + if (fHoleRad>0) + { + for(i=0;iAddNode(hole, j*nh+i+1, tr[j*nh+i]); + // Clear Fiber + if (nh%2==0) + tilev->AddNode(hole, j*nh+i+1); + } + */ + /** Adding edging to scintillator **/ + if (material == 0) { + AddSensitiveVolume(tilev); + edging = new TGeoBBox(fXCell / 2.0 + fEdging, fYCell / 2.0 + fEdging, thickness); + + edgingv = new TGeoVolume(nm + "_edging", edging, gGeoManager->GetMedium("ECALTileEdging")); + edgingv->AddNode(tilev, 1); + fScTile = tilev; + fTileEdging = edgingv; + } else { + if (material == 1) // Lead + fPbTile = tilev; + else + fTvTile = tilev; + return; } - // clear fiber - if (nh%2==0&&fCF!=0) - gGeoManager->Node(nm1.Data(), j*nh+i+1, nm.Data(), 0.0, 0.0, 0.0, 0, kTRUE, buf, 0); - - } -/* - if (fHoleRad>0) - { - for(i=0;iAddNode(hole, j*nh+i+1, tr[j*nh+i]); - // Clear Fiber - if (nh%2==0) - tilev->AddNode(hole, j*nh+i+1); - } -*/ - /** Adding edging to scintillator **/ - if (material==0) - { - AddSensitiveVolume(tilev); - edging=new TGeoBBox(fXCell/2.0+fEdging, fYCell/2.0+fEdging, thickness); - - edgingv=new TGeoVolume(nm+"_edging", edging, gGeoManager->GetMedium("ECALTileEdging")); - edgingv->AddNode(tilev, 1); - fScTile=tilev; - fTileEdging=edgingv; - } - else - { - if (material==1) //Lead - fPbTile=tilev; - else - fTvTile=tilev; - return; - } } // ------------------------------------------------------------------------- // ----- Private method ConstructTileSimple ------------------------------ void hcal::ConstructTileSimple(Int_t material) { - switch (material) - { - case 0: if (fScTile!=NULL) return; break; - case 1: if (fPbTile!=NULL) return; break; - case 2: if (fTvTile!=NULL) return; break; - default: Error("ConstructTileSimple", "Can't construct a tile of type %d.", material); - } - Double_t thickness; - TGeoVolume* hole; - TGeoVolume* fiber; - TGeoTranslation** tr; - TGeoTranslation* tm; - Int_t nh=fNH; - Int_t i; - Int_t j; - TString nm; - TString nm1; - TString nm2; - TString medium; - Double_t x; - Double_t y; - TGeoBBox* tile; - TGeoVolume* tilev; - TGeoBBox* edging; - TGeoVolume* edgingv; - Double_t* buf=NULL; - - switch (material) - { - case 0: thickness=fThicknessScin/2.0; break; - case 1: thickness=fThicknessAbsorber/2.0; break; - case 2: thickness=fThicknessTyvk/2.0; break; - default: Error("ConstructTile", "Can't construct a tile of type %d.", material); - } - - if (thickness<=0.0) return; - /** Building tile **/ - switch (material) - { - case 0: nm="ScTile"; medium="Scintillator"; break; - case 1: nm="LeadTile"; medium=fAbsorber; break; - case 2: nm="TvTile"; medium="Tyvek"; break; - default: Error("ConstructTile", "Can't construct a tile of type %d.", material); - } - - tile=new TGeoBBox(fModuleSize/2.0, fModuleSize/2.0, thickness); - tilev=new TGeoVolume(nm, tile, gGeoManager->GetMedium(medium)); - /** Adding edging to scintillator **/ - if (material==0) - { - AddSensitiveVolume(tilev); - fScTile=tilev; - fTileEdging=tilev; - } - else - { - if (material==1) //Absorber - fPbTile=tilev; - else - fTvTile=tilev; - return; - } + switch (material) { + case 0: + if (fScTile != NULL) + return; + break; + case 1: + if (fPbTile != NULL) + return; + break; + case 2: + if (fTvTile != NULL) + return; + break; + default: + Error("ConstructTileSimple", "Can't construct a tile of type %d.", material); + } + Double_t thickness; + TGeoVolume* hole; + TGeoVolume* fiber; + TGeoTranslation** tr; + TGeoTranslation* tm; + Int_t nh = fNH; + Int_t i; + Int_t j; + TString nm; + TString nm1; + TString nm2; + TString medium; + Double_t x; + Double_t y; + TGeoBBox* tile; + TGeoVolume* tilev; + TGeoBBox* edging; + TGeoVolume* edgingv; + Double_t* buf = NULL; + + switch (material) { + case 0: + thickness = fThicknessScin / 2.0; + break; + case 1: + thickness = fThicknessAbsorber / 2.0; + break; + case 2: + thickness = fThicknessTyvk / 2.0; + break; + default: + Error("ConstructTile", "Can't construct a tile of type %d.", material); + } + + if (thickness <= 0.0) + return; + /** Building tile **/ + switch (material) { + case 0: + nm = "ScTile"; + medium = "Scintillator"; + break; + case 1: + nm = "LeadTile"; + medium = fAbsorber; + break; + case 2: + nm = "TvTile"; + medium = "Tyvek"; + break; + default: + Error("ConstructTile", "Can't construct a tile of type %d.", material); + } + + tile = new TGeoBBox(fModuleSize / 2.0, fModuleSize / 2.0, thickness); + tilev = new TGeoVolume(nm, tile, gGeoManager->GetMedium(medium)); + /** Adding edging to scintillator **/ + if (material == 0) { + AddSensitiveVolume(tilev); + fScTile = tilev; + fTileEdging = tilev; + } else { + if (material == 1) // Absorber + fPbTile = tilev; + else + fTvTile = tilev; + return; + } } // ------------------------------------------------------------------------- // ----- Public method GetCellCoordInf ---------------------------------------- -Bool_t hcal::GetCellCoordInf(Int_t fVolID, Float_t &x, Float_t &y, Int_t& section) +Bool_t hcal::GetCellCoordInf(Int_t fVolID, Float_t& x, Float_t& y, Int_t& section) { - static hcalInf* inf=NULL; - if (inf==NULL) - { - inf=hcalInf::GetInstance(NULL); - if (inf==NULL) - { - cerr << "hcal::GetCellCoordInf(): Can't get geometry information." << endl; - return kFALSE; + static hcalInf* inf = NULL; + if (inf == NULL) { + inf = hcalInf::GetInstance(NULL); + if (inf == NULL) { + cerr << "hcal::GetCellCoordInf(): Can't get geometry information." << endl; + return kFALSE; + } } - } - Int_t volid=fVolID; - section=volid%10; volid=volid-section; volid/=10; - Int_t mx=volid%100; volid-=mx; volid/=100; - Int_t my=volid%100; volid-=my; volid/=100; - static Float_t modulesize=inf->GetVariableStrict("modulesize"); - static Float_t xcalosize=inf->GetHcalSize(0); - static Float_t ycalosize=inf->GetHcalSize(1); - static Float_t dx=inf->GetVariableStrict("xpos"); - static Float_t dy=inf->GetVariableStrict("ypos"); - x=mx*modulesize-xcalosize/2.0+1.0; x+=dx; - y=my*modulesize-ycalosize/2.0+1.0; y+=dy; - - return kFALSE; + Int_t volid = fVolID; + section = volid % 10; + volid = volid - section; + volid /= 10; + Int_t mx = volid % 100; + volid -= mx; + volid /= 100; + Int_t my = volid % 100; + volid -= my; + volid /= 100; + static Float_t modulesize = inf->GetVariableStrict("modulesize"); + static Float_t xcalosize = inf->GetHcalSize(0); + static Float_t ycalosize = inf->GetHcalSize(1); + static Float_t dx = inf->GetVariableStrict("xpos"); + static Float_t dy = inf->GetVariableStrict("ypos"); + x = mx * modulesize - xcalosize / 2.0 + 1.0; + x += dx; + y = my * modulesize - ycalosize / 2.0 + 1.0; + y += dy; + + return kFALSE; } // ------------------------------------------------------------------------------ -Bool_t hcal::GetCellCoord(Int_t fVolID, Float_t &x, Float_t &y, Int_t& section) +Bool_t hcal::GetCellCoord(Int_t fVolID, Float_t& x, Float_t& y, Int_t& section) { - return GetCellCoordInf(fVolID, x, y, section); + return GetCellCoordInf(fVolID, x, y, section); } diff --git a/hcal/hcal.h b/hcal/hcal.h index 66ba6ef5ce..0986948b0e 100644 --- a/hcal/hcal.h +++ b/hcal/hcal.h @@ -4,20 +4,16 @@ ** Defines the active detector HCAL with geometry coded here. **/ - #ifndef HCAL_H #define HCAL_H - -#include "hcalPoint.h" -#include "hcalStructure.h" -#include "hcalInf.h" - #include "FairDetector.h" - #include "TClonesArray.h" #include "TLorentzVector.h" #include "TVector3.h" +#include "hcalInf.h" +#include "hcalPoint.h" +#include "hcalStructure.h" #include @@ -31,218 +27,217 @@ class hcalLightMap; class hcal : public FairDetector { -public: - - /** Default constructor **/ - hcal(); - - - /** Standard constructor. - *@param name detetcor name - *@param active sensitivity flag - **/ - hcal(const char* name, Bool_t active, - const char* fileGeo="hcal.geo"); - - - /** Destructor **/ - virtual ~hcal(); - - - /** Virtual method ProcessHits - ** - ** Defines the action to be taken when a step is inside the - ** active volume. Creates hcal and adds them to the - ** collection. - *@param vol Pointer to the active volume - **/ - virtual Bool_t ProcessHits(FairVolume* vol = NULL); - - - /** Virtual method Construct geometry - ** - ** Constructs the HCAL geometry - **/ - virtual void ConstructGeometry(); - - virtual void EndOfEvent(); - virtual void BeginEvent(); - virtual void Reset(); - virtual void Print() const; - virtual void CopyClones(TClonesArray* cl1, TClonesArray* cl2, Int_t offset); - virtual void Register(); - virtual void ChangeHit(hcalPoint* oldHit=NULL); - virtual void FinishPrimary(); - - virtual void Initialize(); - - /** Accessor to the hit collection **/ - virtual TClonesArray* GetCollection(Int_t iColl) const; - virtual void SetSpecialPhysicsCuts(); - - /** Get cell coordinates according - ** to parameter container **/ - static Bool_t GetCellCoord(Int_t fVolumeID, Float_t &x, Float_t &y, Int_t& section); - /** Get cell coordinates according - ** to current hcalInf **/ - static Bool_t GetCellCoordInf(Int_t fVolumeID, Float_t &x, Float_t &y, Int_t& section); -protected: - hcalPoint* AddHit(Int_t trackID, Int_t detID, TVector3 pos, - TVector3 mom, Double_t time, Double_t length, - Double_t eLoss, Int_t pdgcode); - hcalPoint* AddLiteHit(Int_t trackID, Int_t detID, Double32_t time, Double32_t eLoss); - -private: - Bool_t FillLitePoint(Int_t volnum); - void FillWallPoint(); - /** Private method ResetParameters - ** - ** Resets the private members for the track parameters - **/ - void ResetParameters(); - void SetHcalCuts(Int_t medium); - hcalPoint* FindHit(Int_t VolId, Int_t TrackId); - -private: - hcalInf* fInf; //! - Option_t* fDebug; //! - - /** returns type of volume **/ - Int_t GetVolType(Int_t volnum); - /** Track information to be stored until the track leaves the - active volume. **/ - /** track index **/ - Int_t fTrackID; //! - /** volume id **/ - Int_t fVolumeID; //! - /** position **/ - TLorentzVector fPos; //! - /** momentum **/ - TLorentzVector fMom; //! - /** time **/ - Double32_t fTime; //! - /** length **/ - Double32_t fLength; //! - /** energy loss **/ - Double32_t fELoss; //! - /** **/ - Int_t fPosIndex; //! - - /** MC point collection on HCAL wall **/ - TClonesArray* fHcalCollection; //! - /** MC point collection inside HCAL **/ - TClonesArray* fLiteCollection; //! - /** HCAL geometry parameters **/ - /** x,y,z size of outer HCAL box [cm] **/ - Float_t fHcalSize[3]; //! - /** Use simple geometry. - ** Try to be as compatible to hcal in physics as possible **/ - Int_t fSimpleGeo; //! - /** Just construct guarding volume **/ - Int_t fFastMC; //! - /** Size of the HCAL in modules **/ - Int_t fXSize; //! - Int_t fYSize; //! - /** Position of calorimeter center **/ - Float_t fDX; //! - Float_t fDY; //! - /** Size of calorimeter module [cm] **/ - Float_t fModuleSize; //! - /** Z-position of HCAL from the target [cm] **/ - Float_t fZHcal; //! - /** Semiaxises of keeping volume for ecal **/ - Float_t fSemiX; - Float_t fSemiY; - /** Name of absorber material/media **/ - TString fAbsorber; //! - /** thickness of one lead layer [cm] **/ - Float_t fThicknessAbsorber; //! - /** thickness of one scintillator layer [cm] **/ - Float_t fThicknessScin; //! - /** thickness of one tyvek layer [cm] **/ - Float_t fThicknessTyvk; //! - /** total thickness of one layer [cm] **/ - Float_t fThicknessLayer; //! - /** total thickness of steel layer [cm] **/ - Float_t fThicknessSteel; //! - /** Thickness of tile edging [cm] **/ - Float_t fEdging; //! - /** Radius of holes in the calorimeter [cm] **/ - Float_t fHoleRad; //! - /** Radius of fibers in calorimeter [cm] **/ - Float_t fFiberRad; //! - /** XY Size of cell **/ - Float_t fXCell; //! - Float_t fYCell; //! - /** Number of holes in modules **/ - Int_t fNH; //! - Int_t fCF; //! - /** Names of light maps **/ - TString fLightMapName; //! - /** Light maps **/ - hcalLightMap* fLightMap; //! - /** number of layers per module **/ - Int_t fNLayers; //! - /** number of layers in first section **/ - Int_t fNLayers1; //! - /** Lenght of calorimeter module **/ - Float_t fModuleLength; //! - /** Max number of HCAL cells **/ - Int_t fVolIdMax; //! - /** Number of first hit for current primary **/ - Int_t fFirstNumber; //! - /** Map of volumes in HCAL - ** fVolArr[0]==code of sensivite wall - ** fVolArr[4]==code of Lead - ** fVolArr[3]==code of Tyveec - ** fVolArr[5]==code of scintillator - **/ - Int_t fVolArr[kNumberOfHCALSensitiveVolumes]; //! - - /** Construct a raw of modules **/ - TGeoVolume* ConstructRaw(Int_t number); - /** Construct a module **/ - void ConstructModule(); - /** Construct a tile **/ - void ConstructTile(Int_t material); - /** Next method for simplified geometry **/ - /** Construct a module **/ - void ConstructModuleSimple(); - /** Construct a tile **/ - void ConstructTileSimple(Int_t material); - TGeoVolume* fModule; //! Calorimeter Modules - TGeoVolume* fScTile; //! Pb tiles - TGeoVolume* fTileEdging; //! Edging of scintillator tiles - TGeoVolume* fPbTile; //! Scintillator tiles - TGeoVolume* fTvTile; //! Tyvek sheets - TGeoVolume* fHoleVol[3]; //! Hole volume - TGeoVolume* fFiberVol[3]; //! Fiber volume - TGeoVolume* fSteelTapes[2]; //! Steel tapes - TGeoTranslation** fHolePos; //! Positions of holes - Int_t fModules; //! Number of mudules - std::list > fRawNumber; //! List of constructed raws - - /** Volume ID of calorimeter structure **/ - Int_t fStructureId; //! - /** Initialize medium with given name **/ - Int_t InitMedium(const char* name); - /** Initialize all calorimter media **/ - void InitMedia(); - - hcal(const hcal&); - hcal& operator=(const hcal&); - - ClassDef(hcal,1) + public: + /** Default constructor **/ + hcal(); + + /** Standard constructor. + *@param name detetcor name + *@param active sensitivity flag + **/ + hcal(const char* name, Bool_t active, const char* fileGeo = "hcal.geo"); + + /** Destructor **/ + virtual ~hcal(); + + /** Virtual method ProcessHits + ** + ** Defines the action to be taken when a step is inside the + ** active volume. Creates hcal and adds them to the + ** collection. + *@param vol Pointer to the active volume + **/ + virtual Bool_t ProcessHits(FairVolume* vol = NULL); + + /** Virtual method Construct geometry + ** + ** Constructs the HCAL geometry + **/ + virtual void ConstructGeometry(); + + virtual void EndOfEvent(); + virtual void BeginEvent(); + virtual void Reset(); + virtual void Print() const; + virtual void CopyClones(TClonesArray* cl1, TClonesArray* cl2, Int_t offset); + virtual void Register(); + virtual void ChangeHit(hcalPoint* oldHit = NULL); + virtual void FinishPrimary(); + + virtual void Initialize(); + + /** Accessor to the hit collection **/ + virtual TClonesArray* GetCollection(Int_t iColl) const; + virtual void SetSpecialPhysicsCuts(); + + /** Get cell coordinates according + ** to parameter container **/ + static Bool_t GetCellCoord(Int_t fVolumeID, Float_t& x, Float_t& y, Int_t& section); + /** Get cell coordinates according + ** to current hcalInf **/ + static Bool_t GetCellCoordInf(Int_t fVolumeID, Float_t& x, Float_t& y, Int_t& section); + + protected: + hcalPoint* AddHit(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t time, + Double_t length, + Double_t eLoss, + Int_t pdgcode); + hcalPoint* AddLiteHit(Int_t trackID, Int_t detID, Double32_t time, Double32_t eLoss); + + private: + Bool_t FillLitePoint(Int_t volnum); + void FillWallPoint(); + /** Private method ResetParameters + ** + ** Resets the private members for the track parameters + **/ + void ResetParameters(); + void SetHcalCuts(Int_t medium); + hcalPoint* FindHit(Int_t VolId, Int_t TrackId); + + private: + hcalInf* fInf; //! + Option_t* fDebug; //! + + /** returns type of volume **/ + Int_t GetVolType(Int_t volnum); + /** Track information to be stored until the track leaves the + active volume. **/ + /** track index **/ + Int_t fTrackID; //! + /** volume id **/ + Int_t fVolumeID; //! + /** position **/ + TLorentzVector fPos; //! + /** momentum **/ + TLorentzVector fMom; //! + /** time **/ + Double32_t fTime; //! + /** length **/ + Double32_t fLength; //! + /** energy loss **/ + Double32_t fELoss; //! + /** **/ + Int_t fPosIndex; //! + + /** MC point collection on HCAL wall **/ + TClonesArray* fHcalCollection; //! + /** MC point collection inside HCAL **/ + TClonesArray* fLiteCollection; //! + /** HCAL geometry parameters **/ + /** x,y,z size of outer HCAL box [cm] **/ + Float_t fHcalSize[3]; //! + /** Use simple geometry. + ** Try to be as compatible to hcal in physics as possible **/ + Int_t fSimpleGeo; //! + /** Just construct guarding volume **/ + Int_t fFastMC; //! + /** Size of the HCAL in modules **/ + Int_t fXSize; //! + Int_t fYSize; //! + /** Position of calorimeter center **/ + Float_t fDX; //! + Float_t fDY; //! + /** Size of calorimeter module [cm] **/ + Float_t fModuleSize; //! + /** Z-position of HCAL from the target [cm] **/ + Float_t fZHcal; //! + /** Semiaxises of keeping volume for ecal **/ + Float_t fSemiX; + Float_t fSemiY; + /** Name of absorber material/media **/ + TString fAbsorber; //! + /** thickness of one lead layer [cm] **/ + Float_t fThicknessAbsorber; //! + /** thickness of one scintillator layer [cm] **/ + Float_t fThicknessScin; //! + /** thickness of one tyvek layer [cm] **/ + Float_t fThicknessTyvk; //! + /** total thickness of one layer [cm] **/ + Float_t fThicknessLayer; //! + /** total thickness of steel layer [cm] **/ + Float_t fThicknessSteel; //! + /** Thickness of tile edging [cm] **/ + Float_t fEdging; //! + /** Radius of holes in the calorimeter [cm] **/ + Float_t fHoleRad; //! + /** Radius of fibers in calorimeter [cm] **/ + Float_t fFiberRad; //! + /** XY Size of cell **/ + Float_t fXCell; //! + Float_t fYCell; //! + /** Number of holes in modules **/ + Int_t fNH; //! + Int_t fCF; //! + /** Names of light maps **/ + TString fLightMapName; //! + /** Light maps **/ + hcalLightMap* fLightMap; //! + /** number of layers per module **/ + Int_t fNLayers; //! + /** number of layers in first section **/ + Int_t fNLayers1; //! + /** Lenght of calorimeter module **/ + Float_t fModuleLength; //! + /** Max number of HCAL cells **/ + Int_t fVolIdMax; //! + /** Number of first hit for current primary **/ + Int_t fFirstNumber; //! + /** Map of volumes in HCAL + ** fVolArr[0]==code of sensivite wall + ** fVolArr[4]==code of Lead + ** fVolArr[3]==code of Tyveec + ** fVolArr[5]==code of scintillator + **/ + Int_t fVolArr[kNumberOfHCALSensitiveVolumes]; //! + + /** Construct a raw of modules **/ + TGeoVolume* ConstructRaw(Int_t number); + /** Construct a module **/ + void ConstructModule(); + /** Construct a tile **/ + void ConstructTile(Int_t material); + /** Next method for simplified geometry **/ + /** Construct a module **/ + void ConstructModuleSimple(); + /** Construct a tile **/ + void ConstructTileSimple(Int_t material); + TGeoVolume* fModule; //! Calorimeter Modules + TGeoVolume* fScTile; //! Pb tiles + TGeoVolume* fTileEdging; //! Edging of scintillator tiles + TGeoVolume* fPbTile; //! Scintillator tiles + TGeoVolume* fTvTile; //! Tyvek sheets + TGeoVolume* fHoleVol[3]; //! Hole volume + TGeoVolume* fFiberVol[3]; //! Fiber volume + TGeoVolume* fSteelTapes[2]; //! Steel tapes + TGeoTranslation** fHolePos; //! Positions of holes + Int_t fModules; //! Number of mudules + std::list> fRawNumber; //! List of constructed raws + + /** Volume ID of calorimeter structure **/ + Int_t fStructureId; //! + /** Initialize medium with given name **/ + Int_t InitMedium(const char* name); + /** Initialize all calorimter media **/ + void InitMedia(); + + hcal(const hcal&); + hcal& operator=(const hcal&); + + ClassDef(hcal, 1) }; inline void hcal::ResetParameters() { - fTrackID = fVolumeID = 0; - fPos.SetXYZM(0.0, 0.0, 0.0, 0.0); - fMom.SetXYZM(0.0, 0.0, 0.0, 0.0); - fTime = fLength = fELoss = 0; - fPosIndex = 0; + fTrackID = fVolumeID = 0; + fPos.SetXYZM(0.0, 0.0, 0.0, 0.0); + fMom.SetXYZM(0.0, 0.0, 0.0, 0.0); + fTime = fLength = fELoss = 0; + fPosIndex = 0; }; - #endif diff --git a/hcal/hcalAnalysisSimple.cxx b/hcal/hcalAnalysisSimple.cxx index 69a2a0a143..de7d664da7 100644 --- a/hcal/hcalAnalysisSimple.cxx +++ b/hcal/hcalAnalysisSimple.cxx @@ -1,17 +1,15 @@ #include "hcalAnalysisSimple.h" #include "FairRootManager.h" - -#include "hcalStructure.h" -#include "hcalModule.h" -#include "hcalPoint.h" - -#include "TTree.h" #include "TClonesArray.h" #include "TRandom.h" +#include "TTree.h" +#include "hcalModule.h" +#include "hcalPoint.h" +#include "hcalStructure.h" -#include #include +#include #include using namespace std; @@ -19,148 +17,145 @@ using namespace std; /** Loop procedure **/ void hcalAnalysisSimple::Exec(Option_t* option) { - Int_t n=fTracks->GetEntries(); - Int_t i; - hcalPoint* t; - hcalModule* module; - hcalModule* mmodule; - TVector3 m; - list modules; - list::const_iterator p; -// TVector3 m1; - - fEv++; - InitTree(); - - for(i=0;iAt(i); - fX=t->GetX(); - fY=t->GetY(); - t->Momentum(m); - fP=m.Mag(); - fPX=m.Px(); - fPY=m.Py(); - fPZ=m.Pz(); - -// m1=m.Unit(); - module=fStr->GetModule(fX, fY); - if (!module) continue; - mmodule=module; - module->GetNeighborsList(modules); - for(p=modules.begin();p!=modules.end();++p) - if ((*p)->GetEnergy()>mmodule->GetEnergy()) - mmodule=(*p); - - mmodule->GetNeighborsList(modules); - for(p=modules.begin();p!=modules.end();++p) - if ((*p)->GetEnergy()>mmodule->GetEnergy()) - break; - - if (p!=modules.end()) continue; - - fCX=mmodule->GetCenterX(); - fCY=mmodule->GetCenterY(); - fCE=mmodule->GetEnergy(); - fCE2=mmodule->GetEnergy2(); - fModuleNum=mmodule->GetNumber(); - fADC=mmodule->ADC(); - fOE=fCE; - for(p=modules.begin();p!=modules.end();++p) - fOE+=(*p)->GetEnergy(); - - fTree->Fill(); - } - + Int_t n = fTracks->GetEntries(); + Int_t i; + hcalPoint* t; + hcalModule* module; + hcalModule* mmodule; + TVector3 m; + list modules; + list::const_iterator p; + // TVector3 m1; + + fEv++; + InitTree(); + + for (i = 0; i < n; i++) { + t = (hcalPoint*)fTracks->At(i); + fX = t->GetX(); + fY = t->GetY(); + t->Momentum(m); + fP = m.Mag(); + fPX = m.Px(); + fPY = m.Py(); + fPZ = m.Pz(); + + // m1=m.Unit(); + module = fStr->GetModule(fX, fY); + if (!module) + continue; + mmodule = module; + module->GetNeighborsList(modules); + for (p = modules.begin(); p != modules.end(); ++p) + if ((*p)->GetEnergy() > mmodule->GetEnergy()) + mmodule = (*p); + + mmodule->GetNeighborsList(modules); + for (p = modules.begin(); p != modules.end(); ++p) + if ((*p)->GetEnergy() > mmodule->GetEnergy()) + break; + + if (p != modules.end()) + continue; + + fCX = mmodule->GetCenterX(); + fCY = mmodule->GetCenterY(); + fCE = mmodule->GetEnergy(); + fCE2 = mmodule->GetEnergy2(); + fModuleNum = mmodule->GetNumber(); + fADC = mmodule->ADC(); + fOE = fCE; + for (p = modules.begin(); p != modules.end(); ++p) + fOE += (*p)->GetEnergy(); + + fTree->Fill(); + } } void hcalAnalysisSimple::InitTree() { - if (fTree) return; - fTree=new TTree("calib", "calib"); - fTree->Branch("px", &fPX, "px/D"); - fTree->Branch("py", &fPY, "py/D"); - fTree->Branch("pz", &fPZ, "pz/D"); - fTree->Branch("p" , &fP , "p/D"); - fTree->Branch("x" , &fX , "x/D"); - fTree->Branch("y" , &fY , "y/D"); - fTree->Branch("cx", &fCX, "cx/D"); - fTree->Branch("cy", &fCY, "cy/D"); - fTree->Branch("ce", &fCE, "ce/D"); - fTree->Branch("ce2",&fCE2,"ce2/D"); - fTree->Branch("oe", &fOE, "oe/D"); - fTree->Branch("ev", &fEv, "ev/I"); - fTree->Branch("mn", &fModuleNum, "mn/I"); - fTree->Branch("adc", &fADC, "adc/I"); + if (fTree) + return; + fTree = new TTree("calib", "calib"); + fTree->Branch("px", &fPX, "px/D"); + fTree->Branch("py", &fPY, "py/D"); + fTree->Branch("pz", &fPZ, "pz/D"); + fTree->Branch("p", &fP, "p/D"); + fTree->Branch("x", &fX, "x/D"); + fTree->Branch("y", &fY, "y/D"); + fTree->Branch("cx", &fCX, "cx/D"); + fTree->Branch("cy", &fCY, "cy/D"); + fTree->Branch("ce", &fCE, "ce/D"); + fTree->Branch("ce2", &fCE2, "ce2/D"); + fTree->Branch("oe", &fOE, "oe/D"); + fTree->Branch("ev", &fEv, "ev/I"); + fTree->Branch("mn", &fModuleNum, "mn/I"); + fTree->Branch("adc", &fADC, "adc/I"); } hcalAnalysisSimple::hcalAnalysisSimple(const char* name, const Int_t iVerbose) - : FairTask(name, iVerbose), - fTree(NULL), - fX(0.), - fY(0.), - fCX(0.), - fCY(0.), - fP(0.), - fCE(0.), - fCE2(0.), - fOE(0.), - fPX(0.), - fPY(0.), - fPZ(0.), - fEv(0), - fModuleNum(0), - fADC(0), - fStr(NULL), - fTracks(NULL) -{ -} + : FairTask(name, iVerbose) + , fTree(NULL) + , fX(0.) + , fY(0.) + , fCX(0.) + , fCY(0.) + , fP(0.) + , fCE(0.) + , fCE2(0.) + , fOE(0.) + , fPX(0.) + , fPY(0.) + , fPZ(0.) + , fEv(0) + , fModuleNum(0) + , fADC(0) + , fStr(NULL) + , fTracks(NULL) +{} hcalAnalysisSimple::hcalAnalysisSimple() - : FairTask(), - fTree(NULL), - fX(0.), - fY(0.), - fCX(0.), - fCY(0.), - fP(0.), - fCE(0.), - fCE2(0.), - fOE(0.), - fPX(0.), - fPY(0.), - fPZ(0.), - fEv(0), - fModuleNum(0), - fADC(0), - fStr(NULL), - fTracks(NULL) -{ -} + : FairTask() + , fTree(NULL) + , fX(0.) + , fY(0.) + , fCX(0.) + , fCY(0.) + , fP(0.) + , fCE(0.) + , fCE2(0.) + , fOE(0.) + , fPX(0.) + , fPY(0.) + , fPZ(0.) + , fEv(0) + , fModuleNum(0) + , fADC(0) + , fStr(NULL) + , fTracks(NULL) +{} /** Initing routine **/ InitStatus hcalAnalysisSimple::Init() { - FairRootManager* fManager=FairRootManager::Instance(); - fStr=(hcalStructure*)fManager->GetObject("HcalStructure"); - if (!fStr) - { - Fatal("Init()", "Can't find calorimeter structure. "); - return kFATAL; - } - fTracks=(TClonesArray*)fManager->GetObject("HcalPoint"); - if (!fTracks) - { - Fatal("Init()", "Can't find array of reconstructed tracks. "); - return kFATAL; - } - - return kSUCCESS; + FairRootManager* fManager = FairRootManager::Instance(); + fStr = (hcalStructure*)fManager->GetObject("HcalStructure"); + if (!fStr) { + Fatal("Init()", "Can't find calorimeter structure. "); + return kFATAL; + } + fTracks = (TClonesArray*)fManager->GetObject("HcalPoint"); + if (!fTracks) { + Fatal("Init()", "Can't find array of reconstructed tracks. "); + return kFATAL; + } + + return kSUCCESS; } /** Finishing routine **/ void hcalAnalysisSimple::Finish() { - if (fTree) - fTree->Write(); + if (fTree) + fTree->Write(); } diff --git a/hcal/hcalAnalysisSimple.h b/hcal/hcalAnalysisSimple.h index 34ded37ef8..7027e98e41 100644 --- a/hcal/hcalAnalysisSimple.h +++ b/hcal/hcalAnalysisSimple.h @@ -2,7 +2,6 @@ #define HCALANALYSISCALIB_H #include "FairTask.h" - #include "TString.h" #include @@ -13,48 +12,48 @@ class TClonesArray; class hcalAnalysisSimple : public FairTask { -public: - hcalAnalysisSimple(const char* name, const Int_t iVerbose); - - /** Default constructor **/ - hcalAnalysisSimple(); - - /** Initing routine **/ - virtual InitStatus Init(); - - /** Loop procedure **/ - virtual void Exec(Option_t* option); - - /** Finishing routine **/ - virtual void Finish(); - - /** Destructor **/ - virtual ~hcalAnalysisSimple() {}; - -private: - TTree* fTree; - Double_t fX; - Double_t fY; - Double_t fCX; - Double_t fCY; - Double_t fP; - Double_t fCE; - Double_t fCE2; - Double_t fOE; - Double_t fPX; - Double_t fPY; - Double_t fPZ; - Int_t fEv; - Int_t fModuleNum; - Int_t fADC; - void InitTree(); - hcalStructure* fStr; - TClonesArray* fTracks; - - hcalAnalysisSimple(const hcalAnalysisSimple&); - hcalAnalysisSimple operator=(const hcalAnalysisSimple&); - - ClassDef(hcalAnalysisSimple,1) + public: + hcalAnalysisSimple(const char* name, const Int_t iVerbose); + + /** Default constructor **/ + hcalAnalysisSimple(); + + /** Initing routine **/ + virtual InitStatus Init(); + + /** Loop procedure **/ + virtual void Exec(Option_t* option); + + /** Finishing routine **/ + virtual void Finish(); + + /** Destructor **/ + virtual ~hcalAnalysisSimple() {}; + + private: + TTree* fTree; + Double_t fX; + Double_t fY; + Double_t fCX; + Double_t fCY; + Double_t fP; + Double_t fCE; + Double_t fCE2; + Double_t fOE; + Double_t fPX; + Double_t fPY; + Double_t fPZ; + Int_t fEv; + Int_t fModuleNum; + Int_t fADC; + void InitTree(); + hcalStructure* fStr; + TClonesArray* fTracks; + + hcalAnalysisSimple(const hcalAnalysisSimple&); + hcalAnalysisSimple operator=(const hcalAnalysisSimple&); + + ClassDef(hcalAnalysisSimple, 1) }; #endif diff --git a/hcal/hcalContFact.cxx b/hcal/hcalContFact.cxx index 053c7ebf79..c79d340ec7 100644 --- a/hcal/hcalContFact.cxx +++ b/hcal/hcalContFact.cxx @@ -1,46 +1,44 @@ #include "hcalContFact.h" - #include "FairRuntimeDb.h" #include - -//static hcalContFact ghcalContFact; +// static hcalContFact ghcalContFact; hcalContFact::hcalContFact() - : FairContFact() + : FairContFact() { - /** Constructor (called when the library is loaded) */ - fName="hcalContFact"; - fTitle="Factory for parameter containers in libhcal"; - setAllContainers(); - FairRuntimeDb::instance()->addContFactory(this); + /** Constructor (called when the library is loaded) */ + fName = "hcalContFact"; + fTitle = "Factory for parameter containers in libhcal"; + setAllContainers(); + FairRuntimeDb::instance()->addContFactory(this); } void hcalContFact::setAllContainers() { - /** Creates the Container objects with all accepted - contexts and adds them to - the list of containers for the hcal library. - */ - - /* FairContainer* p= new FairContainer("hcalGeoPar", - "hcal Geometry Parameters", - "TestDefaultContext"); - p->addContext("TestNonDefaultContext"); - - containers->Add(p); -*/ + /** Creates the Container objects with all accepted + contexts and adds them to + the list of containers for the hcal library. + */ + + /* FairContainer* p= new FairContainer("hcalGeoPar", + "hcal Geometry Parameters", + "TestDefaultContext"); + p->addContext("TestNonDefaultContext"); + + containers->Add(p); + */ } FairParSet* hcalContFact::createContainer(FairContainer* c) { - /** Calls the constructor of the corresponding parameter container. - For an actual context, which is not an empty string and not - the default context - of this container, the name is concatinated with the context. - */ + /** Calls the constructor of the corresponding parameter container. + For an actual context, which is not an empty string and not + the default context + of this container, the name is concatinated with the context. + */ /* const char* name=c->GetName(); FairParSet* p=NULL; @@ -50,5 +48,5 @@ FairParSet* hcalContFact::createContainer(FairContainer* c) } return p; */ - return 0; + return 0; } diff --git a/hcal/hcalContFact.h b/hcal/hcalContFact.h index 48c0ade94f..8f191dafa4 100644 --- a/hcal/hcalContFact.h +++ b/hcal/hcalContFact.h @@ -9,11 +9,12 @@ class hcalContFact : public FairContFact { private: void setAllContainers(); + public: hcalContFact(); ~hcalContFact() {} FairParSet* createContainer(FairContainer*); - ClassDef( hcalContFact,0) // Factory for all hcal parameter containers + ClassDef(hcalContFact, 0) // Factory for all hcal parameter containers }; #endif diff --git a/hcal/hcalInf.cxx b/hcal/hcalInf.cxx index 5019992598..3db1270fdd 100644 --- a/hcal/hcalInf.cxx +++ b/hcal/hcalInf.cxx @@ -8,260 +8,254 @@ #include "FairRunAna.h" #include "FairRuntimeDb.h" - -#include "TSystem.h" #include "TMap.h" +#include "TSystem.h" -#include #include +#include #include -using std::cout; using std::cerr; +using std::cout; using std::endl; using std::string; -hcalInf* hcalInf::fInf=NULL; -Int_t hcalInf::fRefCount=0; - +hcalInf* hcalInf::fInf = NULL; +Int_t hcalInf::fRefCount = 0; hcalInf::~hcalInf() { - for(Int_t i=0;iGetenv("VMCWORKDIR"); - newname+="/geometry/"; - newname+=filename; - if (fInf!=NULL) { - if (fInf->fFileName==newname) { - fRefCount++; - return fInf; - } else { - cerr << "hcalInf: Trying create "; - cerr << "instance of hcalInf with"; - cerr << " name " << filename; - cerr << ", which is different from "; - cerr << fInf->fFileName << "." << endl; - return NULL; - } + if (filename == NULL) { + if (fInf != NULL) + fRefCount++; + return fInf; } - fInf=new hcalInf(newname); - //Is something wrong? - if (fInf->fSuccess==0) - { - delete fInf; - return NULL; - } - fRefCount++; - return fInf; + TString newname = gSystem->Getenv("VMCWORKDIR"); + newname += "/geometry/"; + newname += filename; + if (fInf != NULL) { + if (fInf->fFileName == newname) { + fRefCount++; + return fInf; + } else { + cerr << "hcalInf: Trying create "; + cerr << "instance of hcalInf with"; + cerr << " name " << filename; + cerr << ", which is different from "; + cerr << fInf->fFileName << "." << endl; + return NULL; + } + } + fInf = new hcalInf(newname); + // Is something wrong? + if (fInf->fSuccess == 0) { + delete fInf; + return NULL; + } + fRefCount++; + return fInf; } -int cmp_nocase(const string &s, const string &s2 ) +int cmp_nocase(const string& s, const string& s2) { - string::const_iterator p=s.begin(); - string::const_iterator p2=s2.begin(); - while(p!=s.end()&&p2!=s2.end()) { - if (toupper(*p)!=toupper(*p2)) return (toupper(*p)GetValue(key); - if (value==NULL) - { - cerr << "Can't find variable named \"" << key << "\""; - Fatal("GetVariableStrict","Exiting..."); - } - Double_t val; - char* err=NULL; - val=strtod(value->GetString(),&err); - if (err[0]!='\0') - { - cerr << "Can't convert variable named \"" << key ; - cerr << "\" to floating point. Value is \""; - cerr << value->GetString() << "\"." << endl; - Fatal("GetVariableStrict","Exiting..."); - } - return val; + TObjString* value = (TObjString*)fVariables->GetValue(key); + if (value == NULL) { + cerr << "Can't find variable named \"" << key << "\""; + Fatal("GetVariableStrict", "Exiting..."); + } + Double_t val; + char* err = NULL; + val = strtod(value->GetString(), &err); + if (err[0] != '\0') { + cerr << "Can't convert variable named \"" << key; + cerr << "\" to floating point. Value is \""; + cerr << value->GetString() << "\"." << endl; + Fatal("GetVariableStrict", "Exiting..."); + } + return val; } TString hcalInf::GetStringVariable(const char* key) { - TObjString* value=(TObjString*)fVariables->GetValue(key); - if (value==NULL) - { - Fatal("GetStringVariable","Can't find variable named %s.", key); - } - return value->GetString(); + TObjString* value = (TObjString*)fVariables->GetValue(key); + if (value == NULL) { + Fatal("GetStringVariable", "Can't find variable named %s.", key); + } + return value->GetString(); } - - Double_t hcalInf::GetVariable(const char* key) { - TObjString* value=(TObjString*)fVariables->GetValue(key); - if (value==NULL) - return -1111; - Double_t val; - char* err=NULL; - val=strtod(value->GetString(),&err); - if (err[0]!='\0') - return -1111; - return val; + TObjString* value = (TObjString*)fVariables->GetValue(key); + if (value == NULL) + return -1111; + Double_t val; + char* err = NULL; + val = strtod(value->GetString(), &err); + if (err[0] != '\0') + return -1111; + return val; } void hcalInf::AddVariable(const char* key, const char* value) { - TObjString* skey=(TObjString*)fVariables->FindObject(key); - //Value for this key already exists!!! - if (skey!=NULL) return; - skey=new TObjString(key); - skey->String().ToLower(); - TObjString* svalue=new TObjString(value); - fVariables->Add(skey, svalue); + TObjString* skey = (TObjString*)fVariables->FindObject(key); + // Value for this key already exists!!! + if (skey != NULL) + return; + skey = new TObjString(key); + skey->String().ToLower(); + TObjString* svalue = new TObjString(value); + fVariables->Add(skey, svalue); } //============================================================================= hcalInf::hcalInf(const char* filename) - : TObject(), - fVariables(new TMap(200)), - fHcalStr(), - fXPos(0.), - fYPos(0.), - fZPos(0.), - fNLayers(0), - fN1Layers(0), - fXSize(0), - fYSize(0), - fModuleSize(0.), - fAbsorber(0.), - fScin(0.), - fTyveec(0.), - fThicknessLayer(0.), - fCellSize(0.), - fHcalSize(), - fECut(0.), - fHCut(0.), - fSemiX(0.), - fSemiY(0.), - fFastMC(-1), - fSuccess(1), - fFileName(filename) + : TObject() + , fVariables(new TMap(200)) + , fHcalStr() + , fXPos(0.) + , fYPos(0.) + , fZPos(0.) + , fNLayers(0) + , fN1Layers(0) + , fXSize(0) + , fYSize(0) + , fModuleSize(0.) + , fAbsorber(0.) + , fScin(0.) + , fTyveec(0.) + , fThicknessLayer(0.) + , fCellSize(0.) + , fHcalSize() + , fECut(0.) + , fHCut(0.) + , fSemiX(0.) + , fSemiY(0.) + , fFastMC(-1) + , fSuccess(1) + , fFileName(filename) { - /** - ** Constructor reads and parses the ascii file, and fill - ** the HCAL geometry container - ** - FairRunAna* ana = FairRunAna::Instance(); - if (ana!=NULL) - { - FairRuntimeDb* rtdb=ana->GetRuntimeDb(); - rtdb->getContainer("CbmGeoHcalPar"); - } - */ - std::ifstream file(filename); - Int_t linenum; - Double_t val; - string buffer; - string message; - string variable; - string value; - TObjString* str=NULL; - char** err=NULL; - char winend[2]={13, 0}; - int ssize=-1; - - if (!file) { - cerr << "hcalInf: Can't open information file " << filename << "!" << endl; - cerr << "hcalInf: Hcal will not be constructed correctly." << endl; - fSuccess=0; - return; - } - - linenum=0; - while(getline(file,buffer)) { - linenum++; - message=buffer.substr(buffer.find_first_not_of(" ")); //Skiping initial spaces - message=message.substr(0,message.find("#")); //Removing comments - // Threat windows end of strings correctly - message=message.substr(0,message.find(winend)); - if (message.empty()) continue; //This was just a comment - variable=message.substr(0,message.find("=")); - if (variable=="structure") { - while(getline(file,buffer)) { - linenum++; - if (buffer.empty()) break; - message=buffer.substr(buffer.find_first_not_of(" ")); //Skiping initial spaces - message=message.substr(0,message.find("#")); //Removing comments - message=message.substr(0,message.find_last_not_of(" ")+1); //Skiping ending spaces + /** + ** Constructor reads and parses the ascii file, and fill + ** the HCAL geometry container + ** + FairRunAna* ana = FairRunAna::Instance(); + if (ana!=NULL) + { + FairRuntimeDb* rtdb=ana->GetRuntimeDb(); + rtdb->getContainer("CbmGeoHcalPar"); + } + */ + std::ifstream file(filename); + Int_t linenum; + Double_t val; + string buffer; + string message; + string variable; + string value; + TObjString* str = NULL; + char** err = NULL; + char winend[2] = {13, 0}; + int ssize = -1; + + if (!file) { + cerr << "hcalInf: Can't open information file " << filename << "!" << endl; + cerr << "hcalInf: Hcal will not be constructed correctly." << endl; + fSuccess = 0; + return; + } + linenum = 0; + while (getline(file, buffer)) { + linenum++; + message = buffer.substr(buffer.find_first_not_of(" ")); // Skiping initial spaces + message = message.substr(0, message.find("#")); // Removing comments // Threat windows end of strings correctly - message=message.substr(0,message.find(winend)); - - if (!message.empty()) { - if (-1==ssize) - ssize=message.size(); - else - if (ssize!=(Int_t)message.size()) { - cerr << "Error in HCAL structure at line " << linenum; - cerr << "." << endl; - cerr << "Line length differs from previous one" << endl; + message = message.substr(0, message.find(winend)); + if (message.empty()) + continue; // This was just a comment + variable = message.substr(0, message.find("=")); + if (variable == "structure") { + while (getline(file, buffer)) { + linenum++; + if (buffer.empty()) + break; + message = buffer.substr(buffer.find_first_not_of(" ")); // Skiping initial spaces + message = message.substr(0, message.find("#")); // Removing comments + message = message.substr(0, message.find_last_not_of(" ") + 1); // Skiping ending spaces + + // Threat windows end of strings correctly + message = message.substr(0, message.find(winend)); + + if (!message.empty()) { + if (-1 == ssize) + ssize = message.size(); + else if (ssize != (Int_t)message.size()) { + cerr << "Error in HCAL structure at line " << linenum; + cerr << "." << endl; + cerr << "Line length differs from previous one" << endl; + fSuccess = 0; + file.close(); + return; + } + + str = new TObjString(message.c_str()); + fHcalStr.Add(str); + } + } + break; + } + if (variable == message) { + cerr << "Syntax error: File " << filename << ".Line " << linenum << "." << endl; + fSuccess = 0; + file.close(); + return; + } + variable = variable.substr(0, variable.find_first_of(" ")); + value = message.substr(message.find("=") + 1); + value = value.substr(value.find_first_not_of(" ")); // Skiping initial spaces + value = value.substr(0, value.find_first_of(" ")); + /* + value=value.substr(0,value.find_first_not_of("1234567890-+e.")); + val=strtod(value.c_str(),err); + if (err) { + cerr << "Syntax error after =: File " << filename << ".Line " << linenum << "." << endl; fSuccess=0; - file.close(); - return; - - } - - str=new TObjString(message.c_str()); - fHcalStr.Add(str); - } - } - break; - } - if (variable==message) { - cerr << "Syntax error: File " << filename << ".Line " << linenum << "." << endl; - fSuccess=0; - file.close(); - return; + file.close(); + return; + } + */ + AddVariable(variable.c_str(), value.c_str()); } - variable=variable.substr(0,variable.find_first_of(" ")); - value=message.substr(message.find("=")+1); - value=value.substr(value.find_first_not_of(" ")); //Skiping initial spaces - value=value.substr(0,value.find_first_of(" ")); -/* - value=value.substr(0,value.find_first_not_of("1234567890-+e.")); - val=strtod(value.c_str(),err); - if (err) { - cerr << "Syntax error after =: File " << filename << ".Line " << linenum << "." << endl; - fSuccess=0; - file.close(); - return; - } -*/ - AddVariable(variable.c_str(), value.c_str()); - } - file.close(); - InitVariables(); + file.close(); + InitVariables(); } Bool_t hcalInf::ExcludeParameter(TString parname) { - if (parname.CompareTo("hcalversion")==0) return kTRUE; - return kFALSE; + if (parname.CompareTo("hcalversion") == 0) + return kTRUE; + return kFALSE; } /* @@ -291,16 +285,15 @@ void hcalInf::CheckVariables() if (ExcludeParameter(key->String())==kFALSE) if (second==NULL) { - Info("CheckVariables", "Parameter %s not found in .geo file, but found in parameter file.", key->String().Data()); - } else - if (first->String()!=second->String()) + Info("CheckVariables", "Parameter %s not found in .geo file, but found in parameter file.", +key->String().Data()); } else if (first->String()!=second->String()) { - Info("CheckVariables", "Parameter %s differs in .geo file and parameter file!", key->String().Data()); - Info("CheckVariables", "%s=%s in parameter file.", key->String().Data(), first->String().Data()); - Info("CheckVariables", "%s=%s in .geo file.", key->String().Data(), second->String().Data()); + Info("CheckVariables", "Parameter %s differs in .geo file and parameter file!", key->String().Data()); + Info("CheckVariables", "%s=%s in parameter file.", key->String().Data(), first->String().Data()); + Info("CheckVariables", "%s=%s in .geo file.", key->String().Data(), second->String().Data()); } if (ExcludeParameter(key->String())==kTRUE) - AddVariable(key->String().Data(), first->String().Data()); + AddVariable(key->String().Data(), first->String().Data()); } } @@ -314,9 +307,9 @@ void hcalInf::CheckVariables() TObjString* second=(TObjString*)fHcalStr.At(i); if (second&&first->String()!=second->String()) { - Info("CheckVariables", "String %d in calorimeter structure differs in .geo file and in parameter file.", i); - Info("CheckVariables", "%s=%s in parameter file", key->String().Data(), first->String().Data()); - Info("CheckVariables", "%s=%s in .geo file", key->String().Data(), second->String().Data()); + Info("CheckVariables", "String %d in calorimeter structure differs in .geo file and in parameter file.", i); + Info("CheckVariables", "%s=%s in parameter file", key->String().Data(), first->String().Data()); + Info("CheckVariables", "%s=%s in .geo file", key->String().Data(), second->String().Data()); } } } @@ -324,87 +317,88 @@ void hcalInf::CheckVariables() */ void hcalInf::InitVariables() { - TString stri; - TObjString* str=(TObjString*)fHcalStr.At(0); - - fXPos=GetVariableStrict("xpos"); - fYPos=GetVariableStrict("ypos"); - fZPos=GetVariableStrict("zpos"); - fNLayers=(Int_t)GetVariableStrict("nlayers"); - fN1Layers=(Int_t)GetVariableStrict("n1layers"); - fModuleSize=GetVariableStrict("modulesize"); - fAbsorber=GetVariableStrict("absorber"); - fScin=GetVariableStrict("scin"); - fTyveec=GetVariableStrict("tyveec"); - fHcalSize[2]=GetVariableStrict("hcalzsize"); - fECut=GetVariableStrict("ecut"); - fHCut=GetVariableStrict("hcut"); - fFastMC=(Int_t)GetVariableStrict("fastmc"); - fSemiX=GetVariableStrict("xsemiaxis"); - fSemiY=GetVariableStrict("ysemiaxis"); - - stri=""; stri+=str->GetString().Length(); - AddVariable("xsize", stri); - stri=""; stri+=fHcalStr.GetLast()+1; - AddVariable("ysize", stri); - - fXSize=(Int_t)GetVariableStrict("xsize"); - fYSize=(Int_t)GetVariableStrict("ysize"); - fThicknessLayer = 2.0*GetTyveec()+GetScin()+GetAbsorber(); - fHcalSize[0] = GetXSize()*GetModuleSize(); - fHcalSize[1] = GetYSize()*GetModuleSize(); - stri=""; stri+=fHcalSize[0]; - AddVariable("xhcalsize",stri); - stri=""; stri+=fHcalSize[1]; - AddVariable("yhcalsize",stri); + TString stri; + TObjString* str = (TObjString*)fHcalStr.At(0); + + fXPos = GetVariableStrict("xpos"); + fYPos = GetVariableStrict("ypos"); + fZPos = GetVariableStrict("zpos"); + fNLayers = (Int_t)GetVariableStrict("nlayers"); + fN1Layers = (Int_t)GetVariableStrict("n1layers"); + fModuleSize = GetVariableStrict("modulesize"); + fAbsorber = GetVariableStrict("absorber"); + fScin = GetVariableStrict("scin"); + fTyveec = GetVariableStrict("tyveec"); + fHcalSize[2] = GetVariableStrict("hcalzsize"); + fECut = GetVariableStrict("ecut"); + fHCut = GetVariableStrict("hcut"); + fFastMC = (Int_t)GetVariableStrict("fastmc"); + fSemiX = GetVariableStrict("xsemiaxis"); + fSemiY = GetVariableStrict("ysemiaxis"); + + stri = ""; + stri += str->GetString().Length(); + AddVariable("xsize", stri); + stri = ""; + stri += fHcalStr.GetLast() + 1; + AddVariable("ysize", stri); + + fXSize = (Int_t)GetVariableStrict("xsize"); + fYSize = (Int_t)GetVariableStrict("ysize"); + fThicknessLayer = 2.0 * GetTyveec() + GetScin() + GetAbsorber(); + fHcalSize[0] = GetXSize() * GetModuleSize(); + fHcalSize[1] = GetYSize() * GetModuleSize(); + stri = ""; + stri += fHcalSize[0]; + AddVariable("xhcalsize", stri); + stri = ""; + stri += fHcalSize[1]; + AddVariable("yhcalsize", stri); } //----------------------------------------------------------------------------- void hcalInf::DumpContainer() const { - // Print out the HCAL geometry container - - if (fVariables) - { + // Print out the HCAL geometry container + + if (fVariables) { + TObjString* key; + TIterator* iter = fVariables->MakeIterator(); + while ((key = (TObjString*)iter->Next()) != NULL) { + TObjString* str = (TObjString*)fVariables->GetValue(key); + cout << key->String() << "=" << str->String() << endl; + } + } TObjString* key; - TIterator* iter=fVariables->MakeIterator(); - while((key=(TObjString*)iter->Next())!=NULL) - { - TObjString* str=(TObjString*)fVariables->GetValue(key); - cout << key->String() << "=" << str->String() << endl; + TIterator* iter = fHcalStr.MakeIterator(); + + Int_t modules = 0; + Int_t channels = 0; + Int_t i; + Int_t j; + Int_t m[10]; + char stri[2] = {0, 0}; + TString st; + for (i = 0; i < 10; i++) + m[i] = 0; + + while ((key = (TObjString*)iter->Next()) != NULL) { + st = key->String(); + cout << key->String() << endl; + for (i = 0; i < st.Length(); i++) { + stri[0] = st[i]; + j = atoi(stri); + m[j]++; + if (j) + modules++; + channels += j * j; + } } - } - TObjString* key; - TIterator* iter=fHcalStr.MakeIterator(); - - Int_t modules=0; - Int_t channels=0; - Int_t i; - Int_t j; - Int_t m[10]; - char stri[2]={0, 0}; - TString st; - for(i=0;i<10;i++) m[i]=0; - - while((key=(TObjString*)iter->Next())!=NULL) - { - st=key->String(); - cout << key->String() << endl; - for(i=0;i #include class TMap; -class hcalInf:public TObject +class hcalInf : public TObject { -public: - /** This is ROOT requirement **/ - hcalInf() : TObject(), fVariables(NULL), fHcalStr(), fXPos(0.), fYPos(0.), - fZPos(0.), fNLayers(0), fXSize(0), fYSize(0), fModuleSize(0.), fAbsorber(0.), - fScin(0.), fTyveec(0.), fThicknessLayer(0.), fCellSize(0.), fHcalSize(), - fECut(0.), fHCut(0.), fSemiX(0.0), fSemiY(0.0), fFastMC(-1), - fSuccess(-1), fFileName("") - {}; - - static hcalInf* GetInstance(const char* filename); - /** Getters **/ - inline Double_t GetXPos() const {return fXPos;} - inline Double_t GetYPos() const {return fYPos;} - inline Double_t GetZPos() const {return fZPos;} - - inline Double_t GetModuleSize() const {return fModuleSize;} - - inline Int_t GetNLayers() const {return fNLayers;} - inline Int_t GetN1Layers()const {return fN1Layers;} - inline Double_t GetAbsorber()const {return fAbsorber;} - inline Double_t GetScin() const {return fScin;} - inline Double_t GetTyveec() const {return fTyveec;} - inline Double_t GetThicknessLayer() const {return fThicknessLayer;} - - /** Size of HCAL in super modules **/ - inline Int_t GetXSize() const {return fXSize;} - inline Int_t GetYSize() const {return fYSize;} - inline Double_t GetContainerXSemiAxiss() const {return fSemiX;} - inline Double_t GetContainerYSemiAxiss() const {return fSemiY;} - - /** Geant cuts information **/ - inline Double_t GetElectronCut() const {return fECut;} - inline Double_t GetHadronCut() const {return fHCut;} - - inline Double_t GetHcalSize(Int_t num) const { - if (num>-1&&num<3) return fHcalSize[num]; - return -1; - } - char GetType(Int_t x, Int_t y) const; //returns type of (X,Y) supercell - inline Int_t GetFastMC() const {return fFastMC;} - void DumpContainer() const; - - void FreeInstance(); - - /** key must be lower case. For example, if have in - ** geo file AaaA=90, then you should call - ** GetVariableStrict("aaaa"). - ** If variable not found, will return -1111 **/ - Double_t GetVariable(const char* key); - /** key must be lower case. For example, if have in - ** geo file AaaA=90, then you should call - ** GetVariableStrict("aaaa"). - ** If variable not found, will generate Fatal **/ - Double_t GetVariableStrict(const char* key); - TString GetStringVariable(const char* key); - - void AddVariable(const char* key, const char* value); - /** If data from Parameter file differs from ours - ** TODO: should understand a way of storring parameters in SHIP**/ - // void CheckVariables(); -protected: - - /** Text file constructor **/ - hcalInf(const char* filename); - void CalculateHoleSize(); - virtual ~hcalInf(); - - static hcalInf* fInf; - static Int_t fRefCount; - - -private: - /** Init all other variables from fVariables - ** and fHcalStr**/ - void InitVariables(); - /** Ignore a parameter during comparision **/ - Bool_t ExcludeParameter(TString parname); - /** A map containing all variables - ** This variable should be saved in parameter file **/ - TMap* fVariables; - /** Structure of HCAL as array of strings - ** This variable should be saved in parameter file **/ - TObjArray fHcalStr; - /** x-position of HCAL center [cm] **/ - Double_t fXPos; - /** y-position of HCAL center [cm] **/ - Double_t fYPos; - /** z-position of HCAL front [cm] **/ - Double_t fZPos; - - /** Number of HCAL layers **/ - Int_t fNLayers; - /** Number of layers in first hcal section **/ - Int_t fN1Layers; - - /** x-size of hcal in supermodules **/ - Int_t fXSize; - /** y-size of hcal in supermodules **/ - Int_t fYSize; - - /** transverse supermodule size in cm **/ - Double_t fModuleSize; - - /**Thickness of absorber in one layer [cm] **/ - Double_t fAbsorber; - /**Thickness of scintillator in one layer [cm] **/ - Double_t fScin; - /**Thickness of tyvec in one layer [cm] **/ - Double_t fTyveec; - /**Total thickness of layer [cm] **/ - Double_t fThicknessLayer; - /**transverse size of HCAL cell for simulation [cm] **/ - Double_t fCellSize; - /**Size of HCAL container [cm] **/ - Double_t fHcalSize[3]; - /**Electron cut for HCAL **/ - Double_t fECut; - /**Hadron cut for HCAL **/ - Double_t fHCut; - /**Semiaxises of keeping volume **/ - Double_t fSemiX; - Double_t fSemiY; - - /**Flag to run Fast (1) or Full (0) MC code **/ - Int_t fFastMC; - - /** 1 if evething Ok **/ - Int_t fSuccess; - - TString fFileName; - - hcalInf(const hcalInf&); - hcalInf& operator=(const hcalInf&); - - ClassDef(hcalInf,2); + public: + /** This is ROOT requirement **/ + hcalInf() + : TObject() + , fVariables(NULL) + , fHcalStr() + , fXPos(0.) + , fYPos(0.) + , fZPos(0.) + , fNLayers(0) + , fXSize(0) + , fYSize(0) + , fModuleSize(0.) + , fAbsorber(0.) + , fScin(0.) + , fTyveec(0.) + , fThicknessLayer(0.) + , fCellSize(0.) + , fHcalSize() + , fECut(0.) + , fHCut(0.) + , fSemiX(0.0) + , fSemiY(0.0) + , fFastMC(-1) + , fSuccess(-1) + , fFileName("") {}; + + static hcalInf* GetInstance(const char* filename); + /** Getters **/ + inline Double_t GetXPos() const { return fXPos; } + inline Double_t GetYPos() const { return fYPos; } + inline Double_t GetZPos() const { return fZPos; } + + inline Double_t GetModuleSize() const { return fModuleSize; } + + inline Int_t GetNLayers() const { return fNLayers; } + inline Int_t GetN1Layers() const { return fN1Layers; } + inline Double_t GetAbsorber() const { return fAbsorber; } + inline Double_t GetScin() const { return fScin; } + inline Double_t GetTyveec() const { return fTyveec; } + inline Double_t GetThicknessLayer() const { return fThicknessLayer; } + + /** Size of HCAL in super modules **/ + inline Int_t GetXSize() const { return fXSize; } + inline Int_t GetYSize() const { return fYSize; } + inline Double_t GetContainerXSemiAxiss() const { return fSemiX; } + inline Double_t GetContainerYSemiAxiss() const { return fSemiY; } + + /** Geant cuts information **/ + inline Double_t GetElectronCut() const { return fECut; } + inline Double_t GetHadronCut() const { return fHCut; } + + inline Double_t GetHcalSize(Int_t num) const + { + if (num > -1 && num < 3) + return fHcalSize[num]; + return -1; + } + char GetType(Int_t x, Int_t y) const; // returns type of (X,Y) supercell + inline Int_t GetFastMC() const { return fFastMC; } + void DumpContainer() const; + + void FreeInstance(); + + /** key must be lower case. For example, if have in + ** geo file AaaA=90, then you should call + ** GetVariableStrict("aaaa"). + ** If variable not found, will return -1111 **/ + Double_t GetVariable(const char* key); + /** key must be lower case. For example, if have in + ** geo file AaaA=90, then you should call + ** GetVariableStrict("aaaa"). + ** If variable not found, will generate Fatal **/ + Double_t GetVariableStrict(const char* key); + TString GetStringVariable(const char* key); + + void AddVariable(const char* key, const char* value); + /** If data from Parameter file differs from ours + ** TODO: should understand a way of storring parameters in SHIP**/ + // void CheckVariables(); + protected: + /** Text file constructor **/ + hcalInf(const char* filename); + void CalculateHoleSize(); + virtual ~hcalInf(); + + static hcalInf* fInf; + static Int_t fRefCount; + + private: + /** Init all other variables from fVariables + ** and fHcalStr**/ + void InitVariables(); + /** Ignore a parameter during comparision **/ + Bool_t ExcludeParameter(TString parname); + /** A map containing all variables + ** This variable should be saved in parameter file **/ + TMap* fVariables; + /** Structure of HCAL as array of strings + ** This variable should be saved in parameter file **/ + TObjArray fHcalStr; + /** x-position of HCAL center [cm] **/ + Double_t fXPos; + /** y-position of HCAL center [cm] **/ + Double_t fYPos; + /** z-position of HCAL front [cm] **/ + Double_t fZPos; + + /** Number of HCAL layers **/ + Int_t fNLayers; + /** Number of layers in first hcal section **/ + Int_t fN1Layers; + + /** x-size of hcal in supermodules **/ + Int_t fXSize; + /** y-size of hcal in supermodules **/ + Int_t fYSize; + + /** transverse supermodule size in cm **/ + Double_t fModuleSize; + + /**Thickness of absorber in one layer [cm] **/ + Double_t fAbsorber; + /**Thickness of scintillator in one layer [cm] **/ + Double_t fScin; + /**Thickness of tyvec in one layer [cm] **/ + Double_t fTyveec; + /**Total thickness of layer [cm] **/ + Double_t fThicknessLayer; + /**transverse size of HCAL cell for simulation [cm] **/ + Double_t fCellSize; + /**Size of HCAL container [cm] **/ + Double_t fHcalSize[3]; + /**Electron cut for HCAL **/ + Double_t fECut; + /**Hadron cut for HCAL **/ + Double_t fHCut; + /**Semiaxises of keeping volume **/ + Double_t fSemiX; + Double_t fSemiY; + + /**Flag to run Fast (1) or Full (0) MC code **/ + Int_t fFastMC; + + /** 1 if evething Ok **/ + Int_t fSuccess; + + TString fFileName; + + hcalInf(const hcalInf&); + hcalInf& operator=(const hcalInf&); + + ClassDef(hcalInf, 2); }; inline char hcalInf::GetType(Int_t x, Int_t y) const { - /** Returns the type of the module with position (x,y) **/ - if (x<0||y<0||y>fHcalStr.GetLast()) return 0; - TObjString* str=(TObjString*)fHcalStr.At(y); - if (str->GetString().Length()GetString()[x],0}; - return atoi(stri); + /** Returns the type of the module with position (x,y) **/ + if (x < 0 || y < 0 || y > fHcalStr.GetLast()) + return 0; + TObjString* str = (TObjString*)fHcalStr.At(y); + if (str->GetString().Length() < x) + return 0; + char stri[2] = {str->GetString()[x], 0}; + return atoi(stri); } inline void hcalInf::FreeInstance() { - fRefCount--; - if (fRefCount==0) - { - delete this; - fInf=NULL; - } + fRefCount--; + if (fRefCount == 0) { + delete this; + fInf = NULL; + } } #endif diff --git a/hcal/hcalLightMap.cxx b/hcal/hcalLightMap.cxx index f695abf8ac..5d0eb163e9 100644 --- a/hcal/hcalLightMap.cxx +++ b/hcal/hcalLightMap.cxx @@ -2,145 +2,179 @@ #include "TSystem.h" -#include #include -#include +#include #include #include +#include using namespace std; hcalLightMap::hcalLightMap(const char* fname, const char* title) - : TNamed(fname, title), - fSSide(-1111.), fS(-1111), fSize(0), fData(NULL) + : TNamed(fname, title) + , fSSide(-1111.) + , fS(-1111) + , fSize(0) + , fData(NULL) { - Init(fname); + Init(fname); } /** Read information from file **/ void hcalLightMap::Init(const char* filename) { - TString fn=filename; - gSystem->ExpandPathName(fn); - ifstream f(fn); - list lst; - string buf; - string token; - string message; - if (!f) - { - Fatal("Init","Can't open file %s.", filename); - return; - } + TString fn = filename; + gSystem->ExpandPathName(fn); + ifstream f(fn); + list lst; + string buf; + string token; + string message; + if (!f) { + Fatal("Init", "Can't open file %s.", filename); + return; + } - while(getline(f, buf)) - { - if (buf.empty()) continue; - if (buf.find_first_not_of(" ")==string::npos) continue; - //Skipping initial spaces - message=buf.substr(buf.find_first_not_of(" ")); - if (message.empty()) continue; - //Removing comments - message=message.substr(0,message.find("#")); - if (message.empty()) continue; - while(!message.empty()) - { - token=message.substr(0,message.find_first_of(" ")); - if (token.empty()) break; - lst.push_back(atof(token.c_str())); - if (token==message) break; - token=message.substr(message.find_first_of(" ")); - if (token.empty()) break; - if (token.find_first_not_of(" ")==string::npos) break; - message=token.substr(token.find_first_not_of(" ")); + while (getline(f, buf)) { + if (buf.empty()) + continue; + if (buf.find_first_not_of(" ") == string::npos) + continue; + // Skipping initial spaces + message = buf.substr(buf.find_first_not_of(" ")); + if (message.empty()) + continue; + // Removing comments + message = message.substr(0, message.find("#")); + if (message.empty()) + continue; + while (!message.empty()) { + token = message.substr(0, message.find_first_of(" ")); + if (token.empty()) + break; + lst.push_back(atof(token.c_str())); + if (token == message) + break; + token = message.substr(message.find_first_of(" ")); + if (token.empty()) + break; + if (token.find_first_not_of(" ") == string::npos) + break; + message = token.substr(token.find_first_not_of(" ")); + } } - } - f.close(); + f.close(); - list::const_iterator p=lst.begin(); - Double_t xsize; - Double_t ysize; - Double_t sqside; - Double_t l; - Double_t x; - Double_t y; - Double_t z; - Double_t v; - Int_t n; - Int_t i; + list::const_iterator p = lst.begin(); + Double_t xsize; + Double_t ysize; + Double_t sqside; + Double_t l; + Double_t x; + Double_t y; + Double_t z; + Double_t v; + Int_t n; + Int_t i; - xsize=(*p); ++p; ysize=(*p); ++p; sqside=(*p); ++p; - fS=(Int_t)((xsize+0.00001)/sqside); - fSize=fS*fS; fSSide=sqside/xsize; - fData=new Double_t[fSize]; - for(i=0;i=fSize) - { - Info("Init","Data is not selfconsistent (%f, %f), %d", x, y, fSize); + xsize = (*p); + ++p; + ysize = (*p); + ++p; + sqside = (*p); + ++p; + fS = (Int_t)((xsize + 0.00001) / sqside); + fSize = fS * fS; + fSSide = sqside / xsize; + fData = new Double_t[fSize]; + for (i = 0; i < fSize; i++) + fData[i] = -1111; + for (;;) { + if (p == lst.end()) + break; + l = (*p); + ++p; + if (p == lst.end()) + break; + x = (*p); + ++p; + if (p == lst.end()) + break; + y = (*p); + ++p; + if (p == lst.end()) + break; + z = (*p); + ++p; + if (p == lst.end()) + break; + v = (*p); + ++p; + x /= xsize; + y /= ysize; + n = GetNum(x, y); + if (n >= fSize) { + Info("Init", "Data is not selfconsistent (%f, %f), %d", x, y, fSize); + } + fData[n] = v; } - fData[n]=v; - } - lst.clear(); - FillGaps(); - Normalize(); + lst.clear(); + FillGaps(); + Normalize(); } /** Fix a light collection map **/ void hcalLightMap::FillGaps() { - Int_t i; - Int_t j; - Double_t x; - Double_t y; - Int_t n[3]; - Double_t v; - Int_t d; + Int_t i; + Int_t j; + Double_t x; + Double_t y; + Int_t n[3]; + Double_t v; + Int_t d; - for(i=0;i=0&&fData[n[j]]>=0) - { d++; v+=fData[n[j]]; } - if (d>0) - { - v/=d; fData[i]=v; - if (fData[n[0]]<=0) fData[n[0]]=v; - if (fData[n[1]]<=0) fData[n[1]]=v; - if (fData[n[2]]<=0) fData[n[2]]=v; - } - else - Info("FillGaps","No data for (%f,%f)", x, y); - } + for (i = 0; i < fSize; i++) + if (fData[i] < 0) { + x = (i % fS) * fSSide - 0.5 + fSSide / 2.0; + y = (i / fS) * fSSide - 0.5 + fSSide / 2.0; + n[0] = GetNum(x, -y); + n[1] = GetNum(-x, y); + n[2] = GetNum(-x, -y); + v = 0; + d = 0; + for (j = 0; j < 3; j++) + if (n[j] >= 0 && fData[n[j]] >= 0) { + d++; + v += fData[n[j]]; + } + if (d > 0) { + v /= d; + fData[i] = v; + if (fData[n[0]] <= 0) + fData[n[0]] = v; + if (fData[n[1]] <= 0) + fData[n[1]] = v; + if (fData[n[2]] <= 0) + fData[n[2]] = v; + } else + Info("FillGaps", "No data for (%f,%f)", x, y); + } } /** Set average efficiency of light collection to 1.0 **/ void hcalLightMap::Normalize() { - Int_t i; - Int_t n=0; - Double_t v=0; - for(i=0;i0) - { v+=fData[i]; n++; } - v/=n; - for(i=0;i0) - fData[i]/=v; + Int_t i; + Int_t n = 0; + Double_t v = 0; + for (i = 0; i < fSize; i++) + if (fData[i] > 0) { + v += fData[i]; + n++; + } + v /= n; + for (i = 0; i < fSize; i++) + if (fData[i] > 0) + fData[i] /= v; } diff --git a/hcal/hcalLightMap.h b/hcal/hcalLightMap.h index 4215ca0ee0..1a4d5bfa1f 100644 --- a/hcal/hcalLightMap.h +++ b/hcal/hcalLightMap.h @@ -5,41 +5,59 @@ class hcalLightMap : public TNamed { -public: - hcalLightMap() : TNamed(), fSSide(0.), fS(0), fSize(0), fData(NULL) {}; - hcalLightMap(const char* fname, const char* title="Light collection efficiency map"); - Double_t Data(Double_t x, Double_t y) - {Int_t n=GetNum(x,y); if (n<0) return n; return fData[n];} - Int_t GetNum(Double_t x, Double_t y) - { - Double_t lx=x+0.5; Double_t ly=y+0.5; - if (lx<0) lx=0; if (ly<0) ly=0; - if (lx>1) lx=1; if (ly>1) ly=1; - Int_t ix=(Int_t)(lx/fSSide); - Int_t iy=(Int_t)(ly/fSSide); - return iy*fS+ix; - } - virtual ~hcalLightMap() {delete fData;} -private: - /** Read information from file **/ - void Init(const char* filename); - /** Fix a light collection map **/ - void FillGaps(); - /** Set average efficiency of light collection to 1.0 **/ - void Normalize(); - /** Step of the light map **/ - Double_t fSSide; //! - /** Size of side of the light map in steps**/ - Int_t fS; //! - /** Size of the light map **/ - Int_t fSize; //! - /** Light collection efficiency map **/ - Double_t* fData; //! + public: + hcalLightMap() + : TNamed() + , fSSide(0.) + , fS(0) + , fSize(0) + , fData(NULL) {}; + hcalLightMap(const char* fname, const char* title = "Light collection efficiency map"); + Double_t Data(Double_t x, Double_t y) + { + Int_t n = GetNum(x, y); + if (n < 0) + return n; + return fData[n]; + } + Int_t GetNum(Double_t x, Double_t y) + { + Double_t lx = x + 0.5; + Double_t ly = y + 0.5; + if (lx < 0) + lx = 0; + if (ly < 0) + ly = 0; + if (lx > 1) + lx = 1; + if (ly > 1) + ly = 1; + Int_t ix = (Int_t)(lx / fSSide); + Int_t iy = (Int_t)(ly / fSSide); + return iy * fS + ix; + } + virtual ~hcalLightMap() { delete fData; } - hcalLightMap(const hcalLightMap&); - hcalLightMap& operator=(const hcalLightMap&); + private: + /** Read information from file **/ + void Init(const char* filename); + /** Fix a light collection map **/ + void FillGaps(); + /** Set average efficiency of light collection to 1.0 **/ + void Normalize(); + /** Step of the light map **/ + Double_t fSSide; //! + /** Size of side of the light map in steps**/ + Int_t fS; //! + /** Size of the light map **/ + Int_t fSize; //! + /** Light collection efficiency map **/ + Double_t* fData; //! - ClassDef(hcalLightMap, 1) + hcalLightMap(const hcalLightMap&); + hcalLightMap& operator=(const hcalLightMap&); + + ClassDef(hcalLightMap, 1) }; #endif diff --git a/hcal/hcalModule.cxx b/hcal/hcalModule.cxx index 1a19bed15f..e460b968be 100644 --- a/hcal/hcalModule.cxx +++ b/hcal/hcalModule.cxx @@ -11,29 +11,28 @@ using std::cout; using std::endl; -using std::map; using std::list; +using std::map; //----------------------------------------------------------------------------- Int_t hcalModule::CountNeighbors(const std::list& lst) const { - Int_t c=0; - list::const_iterator p=lst.begin(); - for(;p!=lst.end();++p) - if (find(fNeighbors.begin(), fNeighbors.end(), *p)!=fNeighbors.end()) - ++c; + Int_t c = 0; + list::const_iterator p = lst.begin(); + for (; p != lst.end(); ++p) + if (find(fNeighbors.begin(), fNeighbors.end(), *p) != fNeighbors.end()) + ++c; - return c; + return c; } //----------------------------------------------------------------------------- void hcalModule::GetClusterEnergy(Float_t& EcalEnergy) { - EcalEnergy=-1; - EcalEnergy=GetEnergy(); - list::const_iterator p; - for(p=fNeighbors.begin();p!=fNeighbors.end();++p) - { - EcalEnergy+=(*p)->GetEnergy(); - } + EcalEnergy = -1; + EcalEnergy = GetEnergy(); + list::const_iterator p; + for (p = fNeighbors.begin(); p != fNeighbors.end(); ++p) { + EcalEnergy += (*p)->GetEnergy(); + } } diff --git a/hcal/hcalModule.h b/hcal/hcalModule.h index 5f7e0c323b..c446efb61d 100644 --- a/hcal/hcalModule.h +++ b/hcal/hcalModule.h @@ -9,91 +9,97 @@ #include "TObject.h" +#include #include #include -#include class hcalModule : public TObject { -public: - hcalModule(Int_t modulenumber, Float_t x1=0, Float_t y1=0, Float_t x2=0, Float_t y2=0) - : TObject(), fNumber(modulenumber), fX1(x1), fY1(y1), fX2(x2), - fY2(y2), fEnergy(0), fEnergy2(0), fADC(-1111), fNeighbors() - {}; + public: + hcalModule(Int_t modulenumber, Float_t x1 = 0, Float_t y1 = 0, Float_t x2 = 0, Float_t y2 = 0) + : TObject() + , fNumber(modulenumber) + , fX1(x1) + , fY1(y1) + , fX2(x2) + , fY2(y2) + , fEnergy(0) + , fEnergy2(0) + , fADC(-1111) + , fNeighbors() {}; - inline Bool_t IsInside(Float_t x, Float_t y) {return x>GetX1()&&xGetY1()&&y GetX1() && x < GetX2() && y > GetY1() && y < GetY2(); } + // getters + inline Float_t X1() const { return fX1; } + inline Float_t Y1() const { return fY1; } + inline Float_t X2() const { return fX2; } + inline Float_t Y2() const { return fY2; } + inline Float_t GetX1() const { return fX1; } + inline Float_t GetY1() const { return fY1; } + inline Float_t GetX2() const { return fX2; } + inline Float_t GetY2() const { return fY2; } + inline Float_t GetCenterX() const { return (fX1 + fX2) / 2.0; } + inline Float_t GetCenterY() const { return (fY1 + fY2) / 2.0; } + inline Short_t ADC() const { return fADC; } + inline Short_t GetADC() const { return fADC; } - inline Int_t GetNumber() const {return fNumber;} + inline Int_t GetNumber() const { return fNumber; } - inline Float_t GetEnergy() const {return fEnergy;} - inline Float_t GetEnergy2() const {return fEnergy2;} + inline Float_t GetEnergy() const { return fEnergy; } + inline Float_t GetEnergy2() const { return fEnergy2; } - inline void GetNeighborsList(std::list &neib) const - { - neib=fNeighbors; - } - inline void SetNeighborsList(std::list &neib) - { - fNeighbors=neib; - } - inline void SetEnergy(Float_t energy) {fEnergy=energy;} - inline void SetEnergy2(Float_t energy) {fEnergy2=energy;} - inline void SetADC(Short_t adc) {fADC=adc;} - /** Reset all energies in module **/ - void ResetEnergyFast(); - inline void AddEnergy(Float_t energy) {fEnergy+=energy;} - inline void AddEnergy2(Float_t energy) {fEnergy2+=energy;} + inline void GetNeighborsList(std::list& neib) const { neib = fNeighbors; } + inline void SetNeighborsList(std::list& neib) { fNeighbors = neib; } + inline void SetEnergy(Float_t energy) { fEnergy = energy; } + inline void SetEnergy2(Float_t energy) { fEnergy2 = energy; } + inline void SetADC(Short_t adc) { fADC = adc; } + /** Reset all energies in module **/ + void ResetEnergyFast(); + inline void AddEnergy(Float_t energy) { fEnergy += energy; } + inline void AddEnergy2(Float_t energy) { fEnergy2 += energy; } - /** 3x3 cluster, first section **/ - void GetClusterEnergy(Float_t& EcalEnergy); + /** 3x3 cluster, first section **/ + void GetClusterEnergy(Float_t& EcalEnergy); - inline void SetCoord(Float_t x1, Float_t y1, Float_t x2, Float_t y2) - { fX1=x1; fY1=y1; fX2=x2; fY2=y2; } - /** returns number of neighbors in list with module **/ - Int_t CountNeighbors(const std::list& lst) const; -private: - /** module number **/ - Int_t fNumber; - /** left edge of the module **/ - Float_t fX1; - /** bottom edge of the module **/ - Float_t fY1; - /** right edge of the module **/ - Float_t fX2; - /** upper edge of the module **/ - Float_t fY2; - /** energy in first section of hcal module **/ - Float_t fEnergy; - /** energy in second section of hcal module **/ - Float_t fEnergy2; - /** ADC counts read **/ - Short_t fADC; + inline void SetCoord(Float_t x1, Float_t y1, Float_t x2, Float_t y2) + { + fX1 = x1; + fY1 = y1; + fX2 = x2; + fY2 = y2; + } + /** returns number of neighbors in list with module **/ + Int_t CountNeighbors(const std::list& lst) const; + private: + /** module number **/ + Int_t fNumber; + /** left edge of the module **/ + Float_t fX1; + /** bottom edge of the module **/ + Float_t fY1; + /** right edge of the module **/ + Float_t fX2; + /** upper edge of the module **/ + Float_t fY2; + /** energy in first section of hcal module **/ + Float_t fEnergy; + /** energy in second section of hcal module **/ + Float_t fEnergy2; + /** ADC counts read **/ + Short_t fADC; - /** list of neighbor modules **/ - std::list fNeighbors; + /** list of neighbor modules **/ + std::list fNeighbors; - ClassDef(hcalModule,1); + ClassDef(hcalModule, 1); }; inline void hcalModule::ResetEnergyFast() { - fEnergy=0.0; - fEnergy2=0.0; - fADC=-1111; + fEnergy = 0.0; + fEnergy2 = 0.0; + fADC = -1111; } #endif diff --git a/hcal/hcalModuleMC.cxx b/hcal/hcalModuleMC.cxx index b72ac9d4fa..1346d7eaff 100644 --- a/hcal/hcalModuleMC.cxx +++ b/hcal/hcalModuleMC.cxx @@ -11,46 +11,52 @@ using std::cout; using std::endl; -using std::map; using std::list; +using std::map; //----------------------------------------------------------------------------- hcalModuleMC::hcalModuleMC(Int_t number, Float_t x1, Float_t y1, Float_t x2, Float_t y2) - : hcalModule(number, x1, y1, x2, y2), - fTrackEnergy(), - fTrackEnergy2() -{ -} + : hcalModule(number, x1, y1, x2, y2) + , fTrackEnergy() + , fTrackEnergy2() +{} //----------------------------------------------------------------------------- Float_t hcalModuleMC::GetTrackEnergy(Int_t num) const { - map::const_iterator p=fTrackEnergy.find(num); - if (p==fTrackEnergy.end()) return 0; else return p->second; + map::const_iterator p = fTrackEnergy.find(num); + if (p == fTrackEnergy.end()) + return 0; + else + return p->second; } //----------------------------------------------------------------------------- Float_t hcalModuleMC::GetTrackEnergy2(Int_t num) const { - map::const_iterator p=fTrackEnergy2.find(num); - if (p==fTrackEnergy2.end()) return 0; else return p->second; + map::const_iterator p = fTrackEnergy2.find(num); + if (p == fTrackEnergy2.end()) + return 0; + else + return p->second; } //----------------------------------------------------------------------------- void hcalModuleMC::ResetEnergy() { - ResetEnergyFast(); - fTrackEnergy.clear(); - fTrackEnergy2.clear(); + ResetEnergyFast(); + fTrackEnergy.clear(); + fTrackEnergy2.clear(); } //----------------------------------------------------------------------------- Float_t hcalModuleMC::GetTrackClusterEnergy(Int_t num) { - Float_t energy=GetTrackEnergy(num); - list mdls; GetNeighborsList(mdls); - list::const_iterator p=mdls.begin(); - for(;p!=mdls.end();++p) - energy+=((hcalModuleMC*)(*p))->GetTrackEnergy(num); - return energy; + Float_t energy = GetTrackEnergy(num); + list mdls; + GetNeighborsList(mdls); + list::const_iterator p = mdls.begin(); + for (; p != mdls.end(); ++p) + energy += ((hcalModuleMC*)(*p))->GetTrackEnergy(num); + return energy; } diff --git a/hcal/hcalModuleMC.h b/hcal/hcalModuleMC.h index c15bbee42f..779fa70504 100644 --- a/hcal/hcalModuleMC.h +++ b/hcal/hcalModuleMC.h @@ -11,53 +11,44 @@ #include "hcalModule.h" +#include #include #include -#include class hcalModuleMC : public hcalModule { -public: - hcalModuleMC(Int_t number, Float_t x1=0, Float_t y1=0, Float_t x2=0, Float_t y2=0); + public: + hcalModuleMC(Int_t number, Float_t x1 = 0, Float_t y1 = 0, Float_t x2 = 0, Float_t y2 = 0); - Float_t GetTrackEnergy(Int_t num) const; - Float_t GetTrackEnergy2(Int_t num) const; + Float_t GetTrackEnergy(Int_t num) const; + Float_t GetTrackEnergy2(Int_t num) const; - /** Reset all energies in module **/ - void ResetEnergy(); + /** Reset all energies in module **/ + void ResetEnergy(); - inline void SetTrackEnergy(Int_t num, Float_t energy) - { fTrackEnergy[num]=energy; } - inline void AddTrackEnergy(Int_t num, Float_t energy) - { fTrackEnergy[num]+=energy;} + inline void SetTrackEnergy(Int_t num, Float_t energy) { fTrackEnergy[num] = energy; } + inline void AddTrackEnergy(Int_t num, Float_t energy) { fTrackEnergy[num] += energy; } - inline void SetTrackEnergy2(Int_t num, Float_t energy) - { fTrackEnergy2[num]=energy; } - inline void AddTrackEnergy2(Int_t num, Float_t energy) - { fTrackEnergy2[num]+=energy;} + inline void SetTrackEnergy2(Int_t num, Float_t energy) { fTrackEnergy2[num] = energy; } + inline void AddTrackEnergy2(Int_t num, Float_t energy) { fTrackEnergy2[num] += energy; } - // same for tracks - Float_t GetTrackClusterEnergy(Int_t num); + // same for tracks + Float_t GetTrackClusterEnergy(Int_t num); - inline std::map::const_iterator GetTrackEnergyBegin() const - {return fTrackEnergy.begin();} - inline std::map::const_iterator GetTrackEnergyEnd() const - {return fTrackEnergy.end();} + inline std::map::const_iterator GetTrackEnergyBegin() const { return fTrackEnergy.begin(); } + inline std::map::const_iterator GetTrackEnergyEnd() const { return fTrackEnergy.end(); } - inline std::map::const_iterator GetTrackEnergy2Begin() const - {return fTrackEnergy2.begin();} - inline std::map::const_iterator GetTrackEnergy2End() const - {return fTrackEnergy2.end();} + inline std::map::const_iterator GetTrackEnergy2Begin() const { return fTrackEnergy2.begin(); } + inline std::map::const_iterator GetTrackEnergy2End() const { return fTrackEnergy2.end(); } -private: - /** map **/ - std::map fTrackEnergy; + private: + /** map **/ + std::map fTrackEnergy; - /** map **/ - std::map fTrackEnergy2; + /** map **/ + std::map fTrackEnergy2; - ClassDef(hcalModuleMC,1); + ClassDef(hcalModuleMC, 1); }; - #endif diff --git a/hcal/hcalPoint.cxx b/hcal/hcalPoint.cxx index ec3ff95677..79d9e6fe35 100644 --- a/hcal/hcalPoint.cxx +++ b/hcal/hcalPoint.cxx @@ -4,38 +4,38 @@ using std::cout; using std::endl; - // ----- Default constructor ------------------------------------------- hcalPoint::hcalPoint() - : FairMCPoint() -{ -} + : FairMCPoint() +{} // ------------------------------------------------------------------------- // ----- Standard constructor ------------------------------------------ -hcalPoint::hcalPoint(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t tof, Double_t length, - Double_t eLoss, Int_t pdgcode) - : FairMCPoint(trackID, detID, pos, mom, tof, length, eLoss), fPdgCode(pdgcode) -{ -} +hcalPoint::hcalPoint(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t tof, + Double_t length, + Double_t eLoss, + Int_t pdgcode) + : FairMCPoint(trackID, detID, pos, mom, tof, length, eLoss) + , fPdgCode(pdgcode) +{} // ------------------------------------------------------------------------- // ----- Destructor ---------------------------------------------------- -hcalPoint::~hcalPoint() { } +hcalPoint::~hcalPoint() {} // ------------------------------------------------------------------------- // ----- Public method Print ------------------------------------------- void hcalPoint::Print(const Option_t* opt) const { - cout << "-I- hcalPoint: hcal point for track " << fTrackID - << "(PDG=" << fPdgCode << ") in detector " << fDetectorID << endl; - cout << " Position (" << fX << ", " << fY << ", " << fZ - << ") cm" << endl; - cout << " Momentum (" << fPx << ", " << fPy << ", " << fPz - << ") GeV" << endl; - cout << " Time " << fTime << " ns, Length " << fLength - << " cm, Energy loss " << fELoss*1.0e06 << " keV" << endl; + cout << "-I- hcalPoint: hcal point for track " << fTrackID << "(PDG=" << fPdgCode << ") in detector " << fDetectorID + << endl; + cout << " Position (" << fX << ", " << fY << ", " << fZ << ") cm" << endl; + cout << " Momentum (" << fPx << ", " << fPy << ", " << fPz << ") GeV" << endl; + cout << " Time " << fTime << " ns, Length " << fLength << " cm, Energy loss " << fELoss * 1.0e06 << " keV" + << endl; } // ------------------------------------------------------------------------- diff --git a/hcal/hcalPoint.h b/hcal/hcalPoint.h index 679b6db2d7..469236f843 100644 --- a/hcal/hcalPoint.h +++ b/hcal/hcalPoint.h @@ -1,24 +1,19 @@ #ifndef HCALPOINT_H #define HCALPOINT_H 1 - #include "FairMCPoint.h" - +#include "TClonesArray.h" #include "TObject.h" #include "TVector3.h" -#include "TClonesArray.h" - class hcalPoint : public FairMCPoint { - friend class hcal; + friend class hcal; public: - /** Default constructor **/ hcalPoint(); - /** Constructor with arguments *@param trackID Index of MCTrack *@param detID Detector ID @@ -28,8 +23,14 @@ class hcalPoint : public FairMCPoint *@param length Track length since creation [cm] *@param eLoss Energy deposit [GeV] **/ - hcalPoint(Int_t trackID, Int_t detID, TVector3 pos, TVector3 mom, - Double_t tof, Double_t length, Double_t eLoss, Int_t pdgcode=0); + hcalPoint(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t tof, + Double_t length, + Double_t eLoss, + Int_t pdgcode = 0); /** Constructor with arguments for lite points *@param trackID Index of MCTrack @@ -37,12 +38,19 @@ class hcalPoint : public FairMCPoint *@param tof Time since event start [ns] *@param eLoss Energy deposit [GeV] **/ - hcalPoint(Int_t trackID, Int_t detID, Double32_t tof, Double32_t eloss, UInt_t EventId=0) - : FairMCPoint(trackID, detID, TVector3(-1111, -1111, -1111), TVector3(-1111, -1111, -1111), tof, -1111, eloss, EventId), fPdgCode(0) - {}; - - Int_t GetPdgCode() const {return fPdgCode;} - Int_t PdgCode() const {return fPdgCode;} + hcalPoint(Int_t trackID, Int_t detID, Double32_t tof, Double32_t eloss, UInt_t EventId = 0) + : FairMCPoint(trackID, + detID, + TVector3(-1111, -1111, -1111), + TVector3(-1111, -1111, -1111), + tof, + -1111, + eloss, + EventId) + , fPdgCode(0) {}; + + Int_t GetPdgCode() const { return fPdgCode; } + Int_t PdgCode() const { return fPdgCode; } /** Destructor **/ virtual ~hcalPoint(); @@ -57,8 +65,7 @@ class hcalPoint : public FairMCPoint Int_t fPdgCode; - ClassDef(hcalPoint,1) - + ClassDef(hcalPoint, 1) }; #endif diff --git a/hcal/hcalStructure.cxx b/hcal/hcalStructure.cxx index e4a331c9ef..744cf5083a 100644 --- a/hcal/hcalStructure.cxx +++ b/hcal/hcalStructure.cxx @@ -9,221 +9,214 @@ #include "hcal.h" #include "hcalModuleMC.h" - -#include #include #include +#include using namespace std; - hcalModule* hcalStructure::GetModule(Int_t volId, Int_t& section) { - UInt_t i; - static Int_t volidmax = 0; - volidmax=10000000; - - if ((Int_t)fHash.size()volidmax) - return NULL; - if (fHash[volId]==NULL) - { - Float_t x; - Float_t y; - hcal::GetCellCoordInf(volId, x, y, section); - fHash[volId]=GetModule(x+0.025,y+0.025); - } - section=volId%10; - return fHash[volId]; + UInt_t i; + static Int_t volidmax = 0; + volidmax = 10000000; + + if ((Int_t)fHash.size() < volidmax) { + fHash.resize(volidmax); + for (i = 0; i < fHash.size(); i++) + fHash[i] = NULL; + } + if (volId > volidmax) + return NULL; + if (fHash[volId] == NULL) { + Float_t x; + Float_t y; + hcal::GetCellCoordInf(volId, x, y, section); + fHash[volId] = GetModule(x + 0.025, y + 0.025); + } + section = volId % 10; + return fHash[volId]; } //----------------------------------------------------------------------------- void hcalStructure::Serialize() { - fModules.clear(); - for(UInt_t i=0;iGetXPos()-fHcalInf->GetModuleSize()*fHcalInf->GetXSize()/2.0; - fY1=fHcalInf->GetYPos()-fHcalInf->GetModuleSize()*fHcalInf->GetYSize()/2.0; + fX1 = fHcalInf->GetXPos() - fHcalInf->GetModuleSize() * fHcalInf->GetXSize() / 2.0; + fY1 = fHcalInf->GetYPos() - fHcalInf->GetModuleSize() * fHcalInf->GetYSize() / 2.0; } //----------------------------------------------------------------------------- void hcalStructure::Construct() { - if (!fHcalInf) return; - - Float_t x1=GetX1(); - Float_t y1=GetY1(); - Float_t x; - Float_t y; - Float_t dx; - Float_t dy; - Int_t i; - Int_t j; - Int_t k; - Int_t number; - char type; - - fStructure.resize(fHcalInf->GetXSize()*fHcalInf->GetYSize(), NULL); - - dx=fHcalInf->GetModuleSize(); - dy=fHcalInf->GetModuleSize(); - //Creating ECAL Matrix - for(i=0;iGetXSize();i++) - for(j=0;jGetYSize();j++) { - type=fHcalInf->GetType(i,j); - if (type) { - x=x1+i*dx; - y=y1+j*dy; - number=(i*100+j)*100; - fStructure[GetNum(i,j)]=CreateModule(type,number,x,y,x+dx,y+dy); - } - else - fStructure[GetNum(i,j)]=NULL; - } + if (!fHcalInf) + return; + + Float_t x1 = GetX1(); + Float_t y1 = GetY1(); + Float_t x; + Float_t y; + Float_t dx; + Float_t dy; + Int_t i; + Int_t j; + Int_t k; + Int_t number; + char type; + + fStructure.resize(fHcalInf->GetXSize() * fHcalInf->GetYSize(), NULL); + + dx = fHcalInf->GetModuleSize(); + dy = fHcalInf->GetModuleSize(); + // Creating ECAL Matrix + for (i = 0; i < fHcalInf->GetXSize(); i++) + for (j = 0; j < fHcalInf->GetYSize(); j++) { + type = fHcalInf->GetType(i, j); + if (type) { + x = x1 + i * dx; + y = y1 + j * dy; + number = (i * 100 + j) * 100; + fStructure[GetNum(i, j)] = CreateModule(type, number, x, y, x + dx, y + dy); + } else + fStructure[GetNum(i, j)] = NULL; + } #ifdef _DECALSTRUCT - Info("Construct()", "Calorimeter matrix created."); + Info("Construct()", "Calorimeter matrix created."); #endif - //Now HCAL matrix created - list neib; - vector cl; - vector::const_iterator pcl; - - Int_t num; - //We want neighbors for ecalModules be ecalModules - for(i=0;iGetXSize();i++) - for(j=0;jGetYSize();j++) - if (fStructure[GetNum(i,j)]) { - neib.clear(); - - num=GetNumber(i-1,j); - if (-1!=num) { - neib.push_back(fStructure[num]); - } - - num=GetNumber(i-1,j+1); - if (-1!=num) { - neib.push_back(fStructure[num]); - } - - num=GetNumber(i,j+1); - if (-1!=num) { - neib.push_back(fStructure[num]); - } - - num=GetNumber(i+1,j+1); - if (-1!=num) { - neib.push_back(fStructure[num]); - } - - num=GetNumber(i+1,j); - if (-1!=num) { - neib.push_back(fStructure[num]); - } - - num=GetNumber(i+1,j-1); - if (-1!=num) { - neib.push_back(fStructure[num]); - } - - num=GetNumber(i,j-1); - if (-1!=num) { - neib.push_back(fStructure[num]); - } - - num=GetNumber(i-1,j-1); - if (-1!=num) { - neib.push_back(fStructure[num]); - } - - num=GetNumber(i,j); - fStructure[num]->SetNeighborsList(neib); - } - Serialize(); + // Now HCAL matrix created + list neib; + vector cl; + vector::const_iterator pcl; + + Int_t num; + // We want neighbors for ecalModules be ecalModules + for (i = 0; i < fHcalInf->GetXSize(); i++) + for (j = 0; j < fHcalInf->GetYSize(); j++) + if (fStructure[GetNum(i, j)]) { + neib.clear(); + + num = GetNumber(i - 1, j); + if (-1 != num) { + neib.push_back(fStructure[num]); + } + + num = GetNumber(i - 1, j + 1); + if (-1 != num) { + neib.push_back(fStructure[num]); + } + + num = GetNumber(i, j + 1); + if (-1 != num) { + neib.push_back(fStructure[num]); + } + + num = GetNumber(i + 1, j + 1); + if (-1 != num) { + neib.push_back(fStructure[num]); + } + + num = GetNumber(i + 1, j); + if (-1 != num) { + neib.push_back(fStructure[num]); + } + + num = GetNumber(i + 1, j - 1); + if (-1 != num) { + neib.push_back(fStructure[num]); + } + + num = GetNumber(i, j - 1); + if (-1 != num) { + neib.push_back(fStructure[num]); + } + + num = GetNumber(i - 1, j - 1); + if (-1 != num) { + neib.push_back(fStructure[num]); + } + + num = GetNumber(i, j); + fStructure[num]->SetNeighborsList(neib); + } + Serialize(); } //----------------------------------------------------------------------------- void hcalStructure::ResetModules() { - list::const_iterator p=fModules.begin(); - if (fUseMC==0) - { - for(;p!=fModules.end();++p) - (*p)->ResetEnergyFast(); - } - else - { - for(;p!=fModules.end();++p) - ((hcalModuleMC*)(*p))->ResetEnergy(); - } + list::const_iterator p = fModules.begin(); + if (fUseMC == 0) { + for (; p != fModules.end(); ++p) + (*p)->ResetEnergyFast(); + } else { + for (; p != fModules.end(); ++p) + ((hcalModuleMC*)(*p))->ResetEnergy(); + } } //----------------------------------------------------------------------------- void hcalStructure::GetHitXY(const Int_t hitId, Float_t& x, Float_t& y) const { - /** Hit Id -> (x,y) **/ + /** Hit Id -> (x,y) **/ - // Some translation from x*100+y to y*sizex+x coding... + // Some translation from x*100+y to y*sizex+x coding... - Int_t mnum=hitId/10; - Int_t cellx = mnum/100; - Int_t celly = mnum%100; - mnum = GetNum(cellx, celly); + Int_t mnum = hitId / 10; + Int_t cellx = mnum / 100; + Int_t celly = mnum % 100; + mnum = GetNum(cellx, celly); - // end translation + // end translation - hcalModule* module=fStructure[mnum]; - if (module==NULL) return; - x=module->GetCenterX(); - y=module->GetCenterY(); + hcalModule* module = fStructure[mnum]; + if (module == NULL) + return; + x = module->GetCenterX(); + y = module->GetCenterY(); } //----------------------------------------------------------------------------- hcalModule* hcalStructure::GetHitModule(const Int_t hitId) const { - /** Hit Id -> Cell **/ + /** Hit Id -> Cell **/ - // Some translation from x*100+y to y*sizex+x coding... + // Some translation from x*100+y to y*sizex+x coding... - Int_t mnum=hitId/10; - Int_t cellx = mnum/100; - Int_t celly = mnum%100; - mnum = GetNum(cellx, celly); + Int_t mnum = hitId / 10; + Int_t cellx = mnum / 100; + Int_t celly = mnum % 100; + mnum = GetNum(cellx, celly); - // end translation + // end translation - return fStructure[mnum]; + return fStructure[mnum]; } diff --git a/hcal/hcalStructure.h b/hcal/hcalStructure.h index 8d4055a855..0097241382 100644 --- a/hcal/hcalStructure.h +++ b/hcal/hcalStructure.h @@ -7,11 +7,10 @@ #ifndef HCALSTRUCTURE_H #define HCALSTRUCTURE_H -#include "hcalInf.h" -#include "hcalModule.h" - #include "TMath.h" #include "TNamed.h" +#include "hcalInf.h" +#include "hcalModule.h" #include @@ -19,144 +18,144 @@ class hcalStructure : public TNamed { -public: - hcalStructure(hcalInf* hcalinf); - void SetUseMC(Int_t mc=0) {fUseMC=mc;} - Int_t GetUseMC() const {return fUseMC;} - void Construct(); - Int_t GetNumber(Int_t x, Int_t y) const; - - Bool_t AddEnergy(Float_t x, Float_t y, Float_t energy, Float_t energy2); - Float_t GetEnergy(Float_t x, Float_t y, Int_t section=0) const; - hcalModule* GetModule(Float_t x, Float_t y) const; - Int_t GetModuleNumber(Float_t x, Float_t y) const; - - Float_t GetX1() const {return fX1;}; - Float_t GetY1() const {return fY1;}; - Float_t GetX2() const; - Float_t GetY2() const; - inline hcalInf* GetHcalInf() const {return fHcalInf;} - inline void GetStructure(std::vector& stru) const {stru=fStructure;} - inline void GetModules(std::list& mdls) const {mdls=fModules;} - void ResetModules(); - - hcalModule* CreateModule(char type, Int_t number, Float_t x1, Float_t y1, Float_t x2, Float_t y2); - //Some usefull procedures for hit processing - - //Converts (x,y) to hit Id - Int_t GetHitId(Float_t x, Float_t y) const; - //Hit Id -> (x,y) - void GetHitXY(const Int_t hitId, Float_t& x, Float_t& y) const; - - hcalModule* GetModule(Int_t fVolId, Int_t& section); - //Hit It -> Cell - hcalModule* GetHitModule(const Int_t hitId) const; - -private: - Int_t GetNum(Int_t x, Int_t y) const; - -private: - /** Creates modules lists **/ - void Serialize(); - /** Use store MC information in modules **/ - Int_t fUseMC; - /** X coordibate of left bottom angle of ECAL **/ - Float_t fX1; - /** Y coordibate of left bottom angle of ECAL **/ - Float_t fY1; - /** HCAL geometry container **/ - hcalInf* fHcalInf; - /** vector of HCAL modules **/ - std::vector fStructure; - /** All ECAL modules **/ - std::list fModules; - /** MCPoint id -> HCAL mdoule**/ - std::vector fHash; - - hcalStructure(const hcalStructure&); - hcalStructure& operator=(const hcalStructure&); - - ClassDef(hcalStructure,1); + public: + hcalStructure(hcalInf* hcalinf); + void SetUseMC(Int_t mc = 0) { fUseMC = mc; } + Int_t GetUseMC() const { return fUseMC; } + void Construct(); + Int_t GetNumber(Int_t x, Int_t y) const; + + Bool_t AddEnergy(Float_t x, Float_t y, Float_t energy, Float_t energy2); + Float_t GetEnergy(Float_t x, Float_t y, Int_t section = 0) const; + hcalModule* GetModule(Float_t x, Float_t y) const; + Int_t GetModuleNumber(Float_t x, Float_t y) const; + + Float_t GetX1() const { return fX1; }; + Float_t GetY1() const { return fY1; }; + Float_t GetX2() const; + Float_t GetY2() const; + inline hcalInf* GetHcalInf() const { return fHcalInf; } + inline void GetStructure(std::vector& stru) const { stru = fStructure; } + inline void GetModules(std::list& mdls) const { mdls = fModules; } + void ResetModules(); + + hcalModule* CreateModule(char type, Int_t number, Float_t x1, Float_t y1, Float_t x2, Float_t y2); + // Some usefull procedures for hit processing + + // Converts (x,y) to hit Id + Int_t GetHitId(Float_t x, Float_t y) const; + // Hit Id -> (x,y) + void GetHitXY(const Int_t hitId, Float_t& x, Float_t& y) const; + + hcalModule* GetModule(Int_t fVolId, Int_t& section); + // Hit It -> Cell + hcalModule* GetHitModule(const Int_t hitId) const; + + private: + Int_t GetNum(Int_t x, Int_t y) const; + + private: + /** Creates modules lists **/ + void Serialize(); + /** Use store MC information in modules **/ + Int_t fUseMC; + /** X coordibate of left bottom angle of ECAL **/ + Float_t fX1; + /** Y coordibate of left bottom angle of ECAL **/ + Float_t fY1; + /** HCAL geometry container **/ + hcalInf* fHcalInf; + /** vector of HCAL modules **/ + std::vector fStructure; + /** All ECAL modules **/ + std::list fModules; + /** MCPoint id -> HCAL mdoule**/ + std::vector fHash; + + hcalStructure(const hcalStructure&); + hcalStructure& operator=(const hcalStructure&); + + ClassDef(hcalStructure, 1); }; inline hcalModule* hcalStructure::GetModule(Float_t x, Float_t y) const { - /** get ECAL module by known module center coordinate (x,y) **/ - Int_t num=GetModuleNumber(x,y); - if (-1==num) return NULL; else return fStructure[num]; + /** get ECAL module by known module center coordinate (x,y) **/ + Int_t num = GetModuleNumber(x, y); + if (-1 == num) + return NULL; + else + return fStructure[num]; } -inline Int_t hcalStructure::GetModuleNumber(Float_t x, Float_t y) const +inline Int_t hcalStructure::GetModuleNumber(Float_t x, Float_t y) const { - /** get ECAL module by known module center coordinate (x,y) **/ - Int_t ix=(Int_t)TMath::Floor((x-GetX1())/fHcalInf->GetModuleSize()); - Int_t iy=(Int_t)TMath::Floor((y-GetY1())/fHcalInf->GetModuleSize()); - return GetNumber(ix,iy); + /** get ECAL module by known module center coordinate (x,y) **/ + Int_t ix = (Int_t)TMath::Floor((x - GetX1()) / fHcalInf->GetModuleSize()); + Int_t iy = (Int_t)TMath::Floor((y - GetY1()) / fHcalInf->GetModuleSize()); + return GetNumber(ix, iy); } inline Int_t hcalStructure::GetNumber(Int_t x, Int_t y) const { - /** get ECAL absolute module number by known module relative number (x,y) - ** with check for the ECAL boundaries **/ - if (x>-1&&y>-1) - if (xGetXSize()&&yGetYSize()) - return GetNum(x,y); - return -1; + /** get ECAL absolute module number by known module relative number (x,y) + ** with check for the ECAL boundaries **/ + if (x > -1 && y > -1) + if (x < fHcalInf->GetXSize() && y < fHcalInf->GetYSize()) + return GetNum(x, y); + return -1; } inline Int_t hcalStructure::GetNum(Int_t x, Int_t y) const { - /** get ECAL absolute module number by known module relative number (x,y) **/ - return y*fHcalInf->GetXSize()+x; + /** get ECAL absolute module number by known module relative number (x,y) **/ + return y * fHcalInf->GetXSize() + x; } inline Float_t hcalStructure::GetX2() const { - /** get ECAL right edge coordinate in cm **/ - return fHcalInf->GetXPos()+fHcalInf->GetModuleSize()*fHcalInf->GetXSize()/2.0; + /** get ECAL right edge coordinate in cm **/ + return fHcalInf->GetXPos() + fHcalInf->GetModuleSize() * fHcalInf->GetXSize() / 2.0; } inline Float_t hcalStructure::GetY2() const { - /** get ECAL upper edge coordinate in cm **/ - return fHcalInf->GetYPos()+fHcalInf->GetModuleSize()*fHcalInf->GetYSize()/2.0; + /** get ECAL upper edge coordinate in cm **/ + return fHcalInf->GetYPos() + fHcalInf->GetModuleSize() * fHcalInf->GetYSize() / 2.0; } inline Bool_t hcalStructure::AddEnergy(Float_t x, Float_t y, Float_t energy, Float_t energy2) { - /** Add calorimeter energy to a module with coordinate (x,y) **/ - hcalModule* mdl=GetModule(x,y); - if (mdl) - { - mdl->AddEnergy(energy); - mdl->AddEnergy2(energy2); - } - else - return kFALSE; - return kTRUE; + /** Add calorimeter energy to a module with coordinate (x,y) **/ + hcalModule* mdl = GetModule(x, y); + if (mdl) { + mdl->AddEnergy(energy); + mdl->AddEnergy2(energy2); + } else + return kFALSE; + return kTRUE; } inline Float_t hcalStructure::GetEnergy(Float_t x, Float_t y, Int_t section) const { - hcalModule* mdl=GetModule(x,y); - if (mdl) - { - if (section==1) - return mdl->GetEnergy2(); - else - return mdl->GetEnergy(); - } - return -1111; + hcalModule* mdl = GetModule(x, y); + if (mdl) { + if (section == 1) + return mdl->GetEnergy2(); + else + return mdl->GetEnergy(); + } + return -1111; } -//Converts (x,y) to hit Id +// Converts (x,y) to hit Id inline Int_t hcalStructure::GetHitId(Float_t x, Float_t y) const { - hcalModule* mdl=GetModule(x,y); - if (mdl) - return mdl->GetNumber(); - else - return -1111; + hcalModule* mdl = GetModule(x, y); + if (mdl) + return mdl->GetNumber(); + else + return -1111; } #endif diff --git a/hcal/hcalStructureFiller.cxx b/hcal/hcalStructureFiller.cxx index f0b09366a9..88604e0e32 100644 --- a/hcal/hcalStructureFiller.cxx +++ b/hcal/hcalStructureFiller.cxx @@ -1,144 +1,137 @@ #include "hcalStructureFiller.h" -#include "hcalPoint.h" -#include "hcalModuleMC.h" -#include "hcalInf.h" -#include "hcalStructure.h" #include "FairRootManager.h" - +#include "TClonesArray.h" #include "TRandom.h" #include "TVector3.h" -#include "TClonesArray.h" +#include "hcalInf.h" +#include "hcalModuleMC.h" +#include "hcalPoint.h" +#include "hcalStructure.h" -#include #include +#include using namespace std; // ----- Default constructor ------------------------------------------- hcalStructureFiller::hcalStructureFiller() - : FairTask(), - fStr(NULL), - fInf(NULL), - fListHCALpts(NULL), - fEvent(0), - fInited(kFALSE), - fUseMCPoints(kFALSE), - fStoreTrackInfo(kTRUE), - fFileGeo("") -{ -} + : FairTask() + , fStr(NULL) + , fInf(NULL) + , fListHCALpts(NULL) + , fEvent(0) + , fInited(kFALSE) + , fUseMCPoints(kFALSE) + , fStoreTrackInfo(kTRUE) + , fFileGeo("") +{} // ------------------------------------------------------------------------- // ----- Standard constructor ------------------------------------------- -hcalStructureFiller::hcalStructureFiller(const char *name, const Int_t iVerbose, const char* fileGeo) - : FairTask(name,iVerbose), - fStr(NULL), - fInf(hcalInf::GetInstance(fileGeo)), - fListHCALpts(NULL), - fEvent(0), - fInited(kFALSE), - fUseMCPoints(kFALSE), - fStoreTrackInfo(kTRUE), - fFileGeo(fileGeo) -{ -} +hcalStructureFiller::hcalStructureFiller(const char* name, const Int_t iVerbose, const char* fileGeo) + : FairTask(name, iVerbose) + , fStr(NULL) + , fInf(hcalInf::GetInstance(fileGeo)) + , fListHCALpts(NULL) + , fEvent(0) + , fInited(kFALSE) + , fUseMCPoints(kFALSE) + , fStoreTrackInfo(kTRUE) + , fFileGeo(fileGeo) +{} // ------------------------------------------------------------------------- - // ----- Destructor ---------------------------------------------------- hcalStructureFiller::~hcalStructureFiller() { - ; + ; } // ------------------------------------------------------------------------- void hcalStructureFiller::SetParContainers() { - ; + ; } // ----- Initialization ------------------------------------------------ InitStatus hcalStructureFiller::Init() { - fInited=kTRUE; - FairRootManager* fManager = FairRootManager::Instance(); - - if (fUseMCPoints==kFALSE) - { - Warning("Init()", "No data source for structure filler! Calorimeter structure will be empty."); -// return kFATAL; - } - //HCAL MC points - if (fUseMCPoints) - fListHCALpts = (TClonesArray*)fManager->GetObject("HcalPointLite"); - - //fInf->CheckVariables(); - fStr=new hcalStructure(fInf); - if (fStoreTrackInfo) fStr->SetUseMC(1); - fStr->Construct(); - - fManager->Register("HcalStructure", "HCAL", fStr, kFALSE); - return kSUCCESS; + fInited = kTRUE; + FairRootManager* fManager = FairRootManager::Instance(); + + if (fUseMCPoints == kFALSE) { + Warning("Init()", "No data source for structure filler! Calorimeter structure will be empty."); + // return kFATAL; + } + // HCAL MC points + if (fUseMCPoints) + fListHCALpts = (TClonesArray*)fManager->GetObject("HcalPointLite"); + + // fInf->CheckVariables(); + fStr = new hcalStructure(fInf); + if (fStoreTrackInfo) + fStr->SetUseMC(1); + fStr->Construct(); + + fManager->Register("HcalStructure", "HCAL", fStr, kFALSE); + return kSUCCESS; } // ------------------------------------------------------------------------- /** Loop over MCPoints hits and add them to modules **/ void hcalStructureFiller::LoopForMCPoints() { - hcalPoint* pt=NULL; - hcalModule* module; - UInt_t n; - Int_t section; - - n=fListHCALpts->GetEntriesFast(); - if (fVerbose>0) - { - cout << ". Number of input MC points: "; - cout << n << flush; - } - - for(UInt_t j=0; jAt(j); - module=fStr->GetModule(pt->GetDetectorID(), section); - cout << section << " " << pt->GetEnergyLoss() << endl; - if (section==0) - module->AddEnergy(pt->GetEnergyLoss()); - else - module->AddEnergy2(pt->GetEnergyLoss()); - } - if (fStoreTrackInfo) - for(UInt_t j=0; jAt(j); - hcalModuleMC* modulemc=(hcalModuleMC*)fStr->GetModule(pt->GetDetectorID(), section); - if (section==0) - modulemc->AddTrackEnergy(pt->GetTrackID(),pt->GetEnergyLoss()); - else - modulemc->AddTrackEnergy2(pt->GetTrackID(),pt->GetEnergyLoss()); - } + hcalPoint* pt = NULL; + hcalModule* module; + UInt_t n; + Int_t section; + + n = fListHCALpts->GetEntriesFast(); + if (fVerbose > 0) { + cout << ". Number of input MC points: "; + cout << n << flush; + } + + for (UInt_t j = 0; j < n; j++) { + pt = (hcalPoint*)fListHCALpts->At(j); + module = fStr->GetModule(pt->GetDetectorID(), section); + cout << section << " " << pt->GetEnergyLoss() << endl; + if (section == 0) + module->AddEnergy(pt->GetEnergyLoss()); + else + module->AddEnergy2(pt->GetEnergyLoss()); + } + if (fStoreTrackInfo) + for (UInt_t j = 0; j < n; j++) { + pt = (hcalPoint*)fListHCALpts->At(j); + hcalModuleMC* modulemc = (hcalModuleMC*)fStr->GetModule(pt->GetDetectorID(), section); + if (section == 0) + modulemc->AddTrackEnergy(pt->GetTrackID(), pt->GetEnergyLoss()); + else + modulemc->AddTrackEnergy2(pt->GetTrackID(), pt->GetEnergyLoss()); + } } // ----- Execution of Task --------------------------------------------- void hcalStructureFiller::Exec(Option_t* option) { - fEvent++; - if (fVerbose>0) - cout << "--> Event no. " << fEvent; + fEvent++; + if (fVerbose > 0) + cout << "--> Event no. " << fEvent; - fStr->ResetModules(); - if (fUseMCPoints) LoopForMCPoints(); + fStr->ResetModules(); + if (fUseMCPoints) + LoopForMCPoints(); - if (fVerbose>0) - cout << endl << flush; + if (fVerbose > 0) + cout << endl << flush; } // ------------------------------------------------------------------------- - // ----- Finish Task --------------------------------------------------- void hcalStructureFiller::Finish() { - ; + ; } // ------------------------------------------------------------------------- diff --git a/hcal/hcalStructureFiller.h b/hcal/hcalStructureFiller.h index fcaa89943b..89a36d5d5c 100644 --- a/hcal/hcalStructureFiller.h +++ b/hcal/hcalStructureFiller.h @@ -21,94 +21,96 @@ class hcalInf; class hcalStructure; class TClonesArray; -class hcalStructureFiller : public FairTask { - -public: - /** Default constructor **/ - hcalStructureFiller(); +class hcalStructureFiller : public FairTask +{ - /** Standard constructor **/ - hcalStructureFiller(const char *name, const Int_t iVerbose=1, const char* fileGeo="hcal.geo"); + public: + /** Default constructor **/ + hcalStructureFiller(); - /** Destructor **/ - virtual ~hcalStructureFiller(); + /** Standard constructor **/ + hcalStructureFiller(const char* name, const Int_t iVerbose = 1, const char* fileGeo = "hcal.geo"); - /** Initialization of the task **/ - virtual InitStatus Init(); + /** Destructor **/ + virtual ~hcalStructureFiller(); - /** Executed task **/ - virtual void Exec(Option_t* option); + /** Initialization of the task **/ + virtual InitStatus Init(); - /** Finish task **/ - virtual void Finish(); + /** Executed task **/ + virtual void Exec(Option_t* option); - /** Set data source for hit producer. - ** This must be called before Init() - ** (No effect other case)! **/ - void SetUseMCPoints(Bool_t UseMCPoints); + /** Finish task **/ + virtual void Finish(); - hcalStructure* GetStructure() const; - void StoreTrackInformation(Bool_t storetrackinfo=kTRUE); - Bool_t GetStoreTrackInformation() const; + /** Set data source for hit producer. + ** This must be called before Init() + ** (No effect other case)! **/ + void SetUseMCPoints(Bool_t UseMCPoints); - Bool_t GetUseMCPoints() const; - Bool_t GetUseSummableHits() const; - Bool_t GetUseHits() const; -protected: + hcalStructure* GetStructure() const; + void StoreTrackInformation(Bool_t storetrackinfo = kTRUE); + Bool_t GetStoreTrackInformation() const; -private: - /** Init parameter containers **/ - void SetParContainers(); - /** Loop over MCPoints **/ - void LoopForMCPoints(); - hcalStructure* fStr; - hcalInf* fInf; //HCAL geometry container + Bool_t GetUseMCPoints() const; + Bool_t GetUseSummableHits() const; + Bool_t GetUseHits() const; - TClonesArray* fListHCALpts; //HCAL MC points - Int_t fEvent; //! Internal event counter + protected: + private: + /** Init parameter containers **/ + void SetParContainers(); + /** Loop over MCPoints **/ + void LoopForMCPoints(); + hcalStructure* fStr; + hcalInf* fInf; // HCAL geometry container - /** Is Init() already done? **/ - Bool_t fInited; - /** Should we take data from MCPoints? **/ - Bool_t fUseMCPoints; + TClonesArray* fListHCALpts; // HCAL MC points + Int_t fEvent; //! Internal event counter - /** Should we store information about tracks/energy depostion **/ - Bool_t fStoreTrackInfo; - /** Geo file to use **/ - TString fFileGeo; + /** Is Init() already done? **/ + Bool_t fInited; + /** Should we take data from MCPoints? **/ + Bool_t fUseMCPoints; - hcalStructureFiller(const hcalStructureFiller&); - hcalStructureFiller& operator=(const hcalStructureFiller&); + /** Should we store information about tracks/energy depostion **/ + Bool_t fStoreTrackInfo; + /** Geo file to use **/ + TString fFileGeo; - ClassDef(hcalStructureFiller,1) + hcalStructureFiller(const hcalStructureFiller&); + hcalStructureFiller& operator=(const hcalStructureFiller&); + ClassDef(hcalStructureFiller, 1) }; inline void hcalStructureFiller::SetUseMCPoints(Bool_t UseMCPoints) { - if (fInited) return; - fUseMCPoints=UseMCPoints; + if (fInited) + return; + fUseMCPoints = UseMCPoints; } inline Bool_t hcalStructureFiller::GetUseMCPoints() const { - return fUseMCPoints; + return fUseMCPoints; } inline void hcalStructureFiller::StoreTrackInformation(Bool_t storetrackinfo) { - if (fInited) return; - fStoreTrackInfo=storetrackinfo; + if (fInited) + return; + fStoreTrackInfo = storetrackinfo; } inline Bool_t hcalStructureFiller::GetStoreTrackInformation() const { - return fStoreTrackInfo; + return fStoreTrackInfo; } inline hcalStructure* hcalStructureFiller::GetStructure() const { - return fStr; + return fStr; } #endif diff --git a/macro/ShipAna.py b/macro/ShipAna.py index 9b8e093f72..de25e65f14 100644 --- a/macro/ShipAna.py +++ b/macro/ShipAna.py @@ -1,81 +1,109 @@ # example for accessing smeared hits and fitted tracks +import ctypes import os import sys +from argparse import ArgumentParser + import ROOT -import ctypes import rootUtils as ut +import shipRoot_conf import shipunit as u -from ShipGeoConfig import ConfigRegistry -from rootpyPickler import Unpickler from decorators import * -import shipRoot_conf -from argparse import ArgumentParser +from rootpyPickler import Unpickler +from ShipGeoConfig import ConfigRegistry shipRoot_conf.configure() PDG = ROOT.TDatabasePDG.Instance() -chi2CutOff = 4. +chi2CutOff = 4.0 fiducialCut = False measCutFK = 25 measCutPR = 22 -docaCut = 2. +docaCut = 2.0 parser = ArgumentParser() -parser.add_argument("-f", "--inputFile", dest="inputFile", help="Input file", required=True) -parser.add_argument("-n", "--nEvents", dest="nEvents", help="Number of events to analyze", required=False, default=999999,type=int) -parser.add_argument("-g", "--geoFile", dest="geoFile", help="ROOT geofile", required=True) -parser.add_argument("--Debug", dest="Debug", help="Switch on debugging", required=False, action="store_true") +parser.add_argument( + "-f", "--inputFile", dest="inputFile", help="Input file", required=True +) +parser.add_argument( + "-n", + "--nEvents", + dest="nEvents", + help="Number of events to analyze", + required=False, + default=999999, + type=int, +) +parser.add_argument( + "-g", "--geoFile", dest="geoFile", help="ROOT geofile", required=True +) +parser.add_argument( + "--Debug", + dest="Debug", + help="Switch on debugging", + required=False, + action="store_true", +) options = parser.parse_args() eosship = ROOT.gSystem.Getenv("EOSSHIP") -if not options.inputFile.find(',')<0 : - sTree = ROOT.TChain("cbmsim") - for x in options.inputFile.split(','): - if x[0:4] == "/eos": - sTree.AddFile(eosship+x) - else: sTree.AddFile(x) +if not options.inputFile.find(",") < 0: + sTree = ROOT.TChain("cbmsim") + for x in options.inputFile.split(","): + if x[0:4] == "/eos": + sTree.AddFile(eosship + x) + else: + sTree.AddFile(x) elif options.inputFile[0:4] == "/eos": - eospath = eosship+options.inputFile - f = ROOT.TFile.Open(eospath) - sTree = f.cbmsim + eospath = eosship + options.inputFile + f = ROOT.TFile.Open(eospath) + sTree = f.cbmsim else: - f = ROOT.TFile(options.inputFile) - sTree = f.cbmsim + f = ROOT.TFile(options.inputFile) + sTree = f.cbmsim # try to figure out which ecal geo to load if not options.geoFile: - options.geoFile = options.inputFile.replace('ship.','geofile_full.').replace('_rec.','.') + options.geoFile = options.inputFile.replace("ship.", "geofile_full.").replace( + "_rec.", "." + ) if options.geoFile[0:4] == "/eos": - eospath = eosship+options.geoFile - fgeo = ROOT.TFile.Open(eospath) + eospath = eosship + options.geoFile + fgeo = ROOT.TFile.Open(eospath) else: - fgeo = ROOT.TFile(options.geoFile) + fgeo = ROOT.TFile(options.geoFile) # new geofile, load Shipgeo dictionary written by run_simScript.py -upkl = Unpickler(fgeo) -ShipGeo = upkl.load('ShipGeo') +upkl = Unpickler(fgeo) +ShipGeo = upkl.load("ShipGeo") ecalGeoFile = ShipGeo.ecal.File -dy = ShipGeo.Yheight/u.m +dy = ShipGeo.Yheight / u.m # -----Create geometry---------------------------------------------- import shipDet_conf + run = ROOT.FairRunSim() run.SetName("TGeant4") # Transport engine -run.SetSink(ROOT.FairRootFileSink(ROOT.TMemFile('output', 'recreate'))) # Dummy output file -run.SetUserConfig("g4Config_basic.C") # geant4 transport not used, only needed for the mag field +run.SetSink( + ROOT.FairRootFileSink(ROOT.TMemFile("output", "recreate")) +) # Dummy output file +run.SetUserConfig( + "g4Config_basic.C" +) # geant4 transport not used, only needed for the mag field rtdb = run.GetRuntimeDb() # -----Create geometry---------------------------------------------- -modules = shipDet_conf.configure(run,ShipGeo) +modules = shipDet_conf.configure(run, ShipGeo) import geomGeant4 -if hasattr(ShipGeo.Bfield,"fieldMap"): - fieldMaker = geomGeant4.addVMCFields(ShipGeo, '', True, withVirtualMC = False) + +if hasattr(ShipGeo.Bfield, "fieldMap"): + fieldMaker = geomGeant4.addVMCFields(ShipGeo, "", True, withVirtualMC=False) else: - print("no fieldmap given, geofile too old, not anymore support") - exit(-1) -sGeo = fgeo.FAIRGeom -geoMat = ROOT.genfit.TGeoMaterialInterface() + print("no fieldmap given, geofile too old, not anymore support") + exit(-1) +sGeo = fgeo.FAIRGeom +geoMat = ROOT.genfit.TGeoMaterialInterface() ROOT.genfit.MaterialEffects.getInstance().init(geoMat) bfield = ROOT.genfit.FairShipFields() bfield.setField(fieldMaker.getGlobalField()) @@ -83,804 +111,1125 @@ fM.init(bfield) volDict = {} -i=0 +i = 0 for x in ROOT.gGeoManager.GetListOfVolumes(): - volDict[i]=x.GetName() - i+=1 + volDict[i] = x.GetName() + i += 1 # prepare veto decisions import shipVeto + veto = shipVeto.Task(sTree) -vetoDets={} -log={} +vetoDets = {} +log = {} h = {} -ut.bookHist(h,'delPOverP','delP / P',400,0.,200.,100,-0.5,0.5) -ut.bookHist(h,'pullPOverPx','delPx / sigma',400,0.,200.,100,-3.,3.) -ut.bookHist(h,'pullPOverPy','delPy / sigma',400,0.,200.,100,-3.,3.) -ut.bookHist(h,'pullPOverPz','delPz / sigma',400,0.,200.,100,-3.,3.) -ut.bookHist(h,'delPOverP2','delP / P chi2/nmeas<'+str(chi2CutOff),400,0.,200.,100,-0.5,0.5) -ut.bookHist(h,'delPOverPz','delPz / Pz',400,0.,200.,100,-0.5,0.5) -ut.bookHist(h,'delPOverP2z','delPz / Pz chi2/nmeas<'+str(chi2CutOff),400,0.,200.,100,-0.5,0.5) -ut.bookHist(h,'chi2','chi2/nmeas after trackfit',100,0.,10.) -ut.bookHist(h,'prob','prob(chi2)',100,0.,1.) -ut.bookHist(h,'IP','Impact Parameter',100,0.,10.) -ut.bookHist(h,'Vzresol','Vz reco - true [cm]',100,-50.,50.) -ut.bookHist(h,'Vxresol','Vx reco - true [cm]',100,-10.,10.) -ut.bookHist(h,'Vyresol','Vy reco - true [cm]',100,-10.,10.) -ut.bookHist(h,'Vzpull','Vz pull',100,-5.,5.) -ut.bookHist(h,'Vxpull','Vx pull',100,-5.,5.) -ut.bookHist(h,'Vypull','Vy pull',100,-5.,5.) -ut.bookHist(h,'Doca','Doca between two tracks',100,0.,10.) -for x in ['','_pi0']: - ut.bookHist(h,'IP0'+x,'Impact Parameter to target',100,0.,100.) - ut.bookHist(h,'IP0/mass'+x,'Impact Parameter to target vs mass',100,0.,2.,100,0.,100.) - ut.bookHist(h,'HNL'+x,'reconstructed Mass',500,0.,2.) -ut.bookHist(h,'HNLw','reconstructed Mass with weights',500,0.,2.) -ut.bookHist(h,'meas','number of measurements',40,-0.5,39.5) -ut.bookHist(h,'meas2','number of measurements, fitted track',40,-0.5,39.5) -ut.bookHist(h,'measVSchi2','number of measurements vs chi2/meas',40,-0.5,39.5,100,0.,10.) -ut.bookHist(h,'distu','distance to wire',100,0.,1.) -ut.bookHist(h,'distv','distance to wire',100,0.,1.) -ut.bookHist(h,'disty','distance to wire',100,0.,1.) -ut.bookHist(h,'meanhits','mean number of hits / track',50,-0.5,49.5) -ut.bookHist(h,'ecalClusters','x/y and energy',50,-3.,3.,50,-6.,6.) - -ut.bookHist(h,'extrapTimeDetX','extrapolation to TimeDet X',100,-10.,10.) -ut.bookHist(h,'extrapTimeDetY','extrapolation to TimeDet Y',100,-10.,10.) - -ut.bookHist(h,'oa','cos opening angle',100,0.999,1.) +ut.bookHist(h, "delPOverP", "delP / P", 400, 0.0, 200.0, 100, -0.5, 0.5) +ut.bookHist(h, "pullPOverPx", "delPx / sigma", 400, 0.0, 200.0, 100, -3.0, 3.0) +ut.bookHist(h, "pullPOverPy", "delPy / sigma", 400, 0.0, 200.0, 100, -3.0, 3.0) +ut.bookHist(h, "pullPOverPz", "delPz / sigma", 400, 0.0, 200.0, 100, -3.0, 3.0) +ut.bookHist( + h, + "delPOverP2", + "delP / P chi2/nmeas<" + str(chi2CutOff), + 400, + 0.0, + 200.0, + 100, + -0.5, + 0.5, +) +ut.bookHist(h, "delPOverPz", "delPz / Pz", 400, 0.0, 200.0, 100, -0.5, 0.5) +ut.bookHist( + h, + "delPOverP2z", + "delPz / Pz chi2/nmeas<" + str(chi2CutOff), + 400, + 0.0, + 200.0, + 100, + -0.5, + 0.5, +) +ut.bookHist(h, "chi2", "chi2/nmeas after trackfit", 100, 0.0, 10.0) +ut.bookHist(h, "prob", "prob(chi2)", 100, 0.0, 1.0) +ut.bookHist(h, "IP", "Impact Parameter", 100, 0.0, 10.0) +ut.bookHist(h, "Vzresol", "Vz reco - true [cm]", 100, -50.0, 50.0) +ut.bookHist(h, "Vxresol", "Vx reco - true [cm]", 100, -10.0, 10.0) +ut.bookHist(h, "Vyresol", "Vy reco - true [cm]", 100, -10.0, 10.0) +ut.bookHist(h, "Vzpull", "Vz pull", 100, -5.0, 5.0) +ut.bookHist(h, "Vxpull", "Vx pull", 100, -5.0, 5.0) +ut.bookHist(h, "Vypull", "Vy pull", 100, -5.0, 5.0) +ut.bookHist(h, "Doca", "Doca between two tracks", 100, 0.0, 10.0) +for x in ["", "_pi0"]: + ut.bookHist(h, "IP0" + x, "Impact Parameter to target", 100, 0.0, 100.0) + ut.bookHist( + h, + "IP0/mass" + x, + "Impact Parameter to target vs mass", + 100, + 0.0, + 2.0, + 100, + 0.0, + 100.0, + ) + ut.bookHist(h, "HNL" + x, "reconstructed Mass", 500, 0.0, 2.0) +ut.bookHist(h, "HNLw", "reconstructed Mass with weights", 500, 0.0, 2.0) +ut.bookHist(h, "meas", "number of measurements", 40, -0.5, 39.5) +ut.bookHist(h, "meas2", "number of measurements, fitted track", 40, -0.5, 39.5) +ut.bookHist( + h, + "measVSchi2", + "number of measurements vs chi2/meas", + 40, + -0.5, + 39.5, + 100, + 0.0, + 10.0, +) +ut.bookHist(h, "distu", "distance to wire", 100, 0.0, 1.0) +ut.bookHist(h, "distv", "distance to wire", 100, 0.0, 1.0) +ut.bookHist(h, "disty", "distance to wire", 100, 0.0, 1.0) +ut.bookHist(h, "meanhits", "mean number of hits / track", 50, -0.5, 49.5) +ut.bookHist(h, "ecalClusters", "x/y and energy", 50, -3.0, 3.0, 50, -6.0, 6.0) + +ut.bookHist(h, "extrapTimeDetX", "extrapolation to TimeDet X", 100, -10.0, 10.0) +ut.bookHist(h, "extrapTimeDetY", "extrapolation to TimeDet Y", 100, -10.0, 10.0) + +ut.bookHist(h, "oa", "cos opening angle", 100, 0.999, 1.0) # potential Veto detectors -ut.bookHist(h,'nrtracks','nr of tracks in signal selected',10,-0.5,9.5) -ut.bookHist(h,'nrSVT','nr of hits in SVT',10,-0.5,9.5) -ut.bookHist(h,'nrSBT','nr of hits in SBT',100,-0.5,99.5) -ut.bookHist(h,'nrRPC','nr of hits in RPC',100,-0.5,99.5) +ut.bookHist(h, "nrtracks", "nr of tracks in signal selected", 10, -0.5, 9.5) +ut.bookHist(h, "nrSVT", "nr of hits in SVT", 10, -0.5, 9.5) +ut.bookHist(h, "nrSBT", "nr of hits in SBT", 100, -0.5, 99.5) +ut.bookHist(h, "nrRPC", "nr of hits in RPC", 100, -0.5, 99.5) import TrackExtrapolateTool -def VertexError(t1,t2,PosDir,CovMat,scalFac): -# with improved Vx x,y resolution - a,u = PosDir[t1]['position'],PosDir[t1]['direction'] - c,v = PosDir[t2]['position'],PosDir[t2]['direction'] - Vsq = v.Dot(v) - Usq = u.Dot(u) - UV = u.Dot(v) - ca = c-a - denom = Usq*Vsq-UV**2 - tmp2 = Vsq*u-UV*v - Va = ca.Dot(tmp2)/denom - tmp2 = UV*u-Usq*v - Vb = ca.Dot(tmp2)/denom - X = (a+c+Va*u+Vb*v) * 0.5 - l1 = a - X + u*Va # l2 = c - X + v*Vb - dist = 2. * ROOT.TMath.Sqrt( l1.Dot(l1) ) - T = ROOT.TMatrixD(3,12) - for i in range(3): - for k in range(4): - for j in range(3): - KD = 0 - if i==j: KD = 1 - if k==0 or k==2: - # cova and covc - temp = ( u[j]*Vsq - v[j]*UV )*u[i] + (u[j]*UV-v[j]*Usq)*v[i] - sign = -1 - if k==2 : sign = +1 - T[i][3*k+j] = 0.5*( KD + sign*temp/denom ) - elif k==1: - # covu - aNAZ = denom*( ca[j]*Vsq-v.Dot(ca)*v[j] ) - aZAN = ( ca.Dot(u)*Vsq-ca.Dot(v)*UV )*2*( u[j]*Vsq-v[j]*UV ) - bNAZ = denom*( ca[j]*UV+(u.Dot(ca)*v[j]) - 2*ca.Dot(v)*u[j] ) - bZAN = ( ca.Dot(u)*UV-ca.Dot(v)*Usq )*2*( u[j]*Vsq-v[j]*UV ) - T[i][3*k+j] = 0.5*( Va*KD + u[i]/denom**2*(aNAZ-aZAN) + v[i]/denom**2*(bNAZ-bZAN) ) - elif k==3: - # covv - aNAZ = denom*( 2*ca.Dot(u)*v[j] - ca.Dot(v)*u[j] - ca[j]*UV ) - aZAN = ( ca.Dot(u)*Vsq-ca.Dot(v)*UV )*2*( v[j]*Usq-u[j]*UV ) - bNAZ = denom*( ca.Dot(u)*u[j]-ca[j]*Usq ) - bZAN = ( ca.Dot(u)*UV-ca.Dot(v)*Usq )*2*( v[j]*Usq-u[j]*UV ) - T[i][3*k+j] = 0.5*(Vb*KD + u[i]/denom**2*(aNAZ-aZAN) + v[i]/denom**2*(bNAZ-bZAN) ) - transT = ROOT.TMatrixD(12,3) - transT.Transpose(T) - CovTracks = ROOT.TMatrixD(12,12) - tlist = [t1,t2] - for k in range(2): - for i in range(6): - for j in range(6): - xfac = 1. - if i>2: xfac = scalFac[tlist[k]] - if j>2: xfac = xfac * scalFac[tlist[k]] - CovTracks[i+k*6][j+k*6] = CovMat[tlist[k]][i][j] * xfac - # if i==5 or j==5 : CovMat[tlist[k]][i][j] = 0 # ignore error on z-direction - tmp = ROOT.TMatrixD(3,12) - tmp.Mult(T,CovTracks) - covX = ROOT.TMatrixD(3,3) - covX.Mult(tmp,transT) - return X,covX,dist + +def VertexError(t1, t2, PosDir, CovMat, scalFac): + # with improved Vx x,y resolution + a, u = PosDir[t1]["position"], PosDir[t1]["direction"] + c, v = PosDir[t2]["position"], PosDir[t2]["direction"] + Vsq = v.Dot(v) + Usq = u.Dot(u) + UV = u.Dot(v) + ca = c - a + denom = Usq * Vsq - UV**2 + tmp2 = Vsq * u - UV * v + Va = ca.Dot(tmp2) / denom + tmp2 = UV * u - Usq * v + Vb = ca.Dot(tmp2) / denom + X = (a + c + Va * u + Vb * v) * 0.5 + l1 = a - X + u * Va # l2 = c - X + v*Vb + dist = 2.0 * ROOT.TMath.Sqrt(l1.Dot(l1)) + T = ROOT.TMatrixD(3, 12) + for i in range(3): + for k in range(4): + for j in range(3): + KD = 0 + if i == j: + KD = 1 + if k == 0 or k == 2: + # cova and covc + temp = (u[j] * Vsq - v[j] * UV) * u[i] + ( + u[j] * UV - v[j] * Usq + ) * v[i] + sign = -1 + if k == 2: + sign = +1 + T[i][3 * k + j] = 0.5 * (KD + sign * temp / denom) + elif k == 1: + # covu + aNAZ = denom * (ca[j] * Vsq - v.Dot(ca) * v[j]) + aZAN = ( + (ca.Dot(u) * Vsq - ca.Dot(v) * UV) + * 2 + * (u[j] * Vsq - v[j] * UV) + ) + bNAZ = denom * ( + ca[j] * UV + (u.Dot(ca) * v[j]) - 2 * ca.Dot(v) * u[j] + ) + bZAN = ( + (ca.Dot(u) * UV - ca.Dot(v) * Usq) + * 2 + * (u[j] * Vsq - v[j] * UV) + ) + T[i][3 * k + j] = 0.5 * ( + Va * KD + + u[i] / denom**2 * (aNAZ - aZAN) + + v[i] / denom**2 * (bNAZ - bZAN) + ) + elif k == 3: + # covv + aNAZ = denom * ( + 2 * ca.Dot(u) * v[j] - ca.Dot(v) * u[j] - ca[j] * UV + ) + aZAN = ( + (ca.Dot(u) * Vsq - ca.Dot(v) * UV) + * 2 + * (v[j] * Usq - u[j] * UV) + ) + bNAZ = denom * (ca.Dot(u) * u[j] - ca[j] * Usq) + bZAN = ( + (ca.Dot(u) * UV - ca.Dot(v) * Usq) + * 2 + * (v[j] * Usq - u[j] * UV) + ) + T[i][3 * k + j] = 0.5 * ( + Vb * KD + + u[i] / denom**2 * (aNAZ - aZAN) + + v[i] / denom**2 * (bNAZ - bZAN) + ) + transT = ROOT.TMatrixD(12, 3) + transT.Transpose(T) + CovTracks = ROOT.TMatrixD(12, 12) + tlist = [t1, t2] + for k in range(2): + for i in range(6): + for j in range(6): + xfac = 1.0 + if i > 2: + xfac = scalFac[tlist[k]] + if j > 2: + xfac = xfac * scalFac[tlist[k]] + CovTracks[i + k * 6][j + k * 6] = CovMat[tlist[k]][i][j] * xfac + # if i==5 or j==5 : CovMat[tlist[k]][i][j] = 0 # ignore error on z-direction + tmp = ROOT.TMatrixD(3, 12) + tmp.Mult(T, CovTracks) + covX = ROOT.TMatrixD(3, 3) + covX.Mult(tmp, transT) + return X, covX, dist + from array import array -def dist2InnerWall(X,Y,Z): - dist = 0 - # return distance to inner wall perpendicular to z-axis, if outside decayVolume return 0. - node = sGeo.FindNode(X,Y,Z) - if ShipGeo.tankDesign < 5: - if not 'cave' in node.GetName(): return dist # TP - else: - if not 'DecayVacuum' in node.GetName(): return dist - start = array('d',[X,Y,Z]) - nsteps = 8 - dalpha = 2*ROOT.TMath.Pi()/nsteps - rsq = X**2+Y**2 - minDistance = 100 *u.m - for n in range(nsteps): - alpha = n * dalpha - sdir = array('d',[ROOT.TMath.Sin(alpha),ROOT.TMath.Cos(alpha),0.]) - node = sGeo.InitTrack(start, sdir) - nxt = sGeo.FindNextBoundary() - if ShipGeo.tankDesign < 5 and nxt.GetName().find('I')<0: return 0 - distance = sGeo.GetStep() - if distance < minDistance : minDistance = distance - return minDistance - -def isInFiducial(X,Y,Z): - if not fiducialCut: return True - if Z > ShipGeo.TrackStation1.z : return False - if Z < ShipGeo.vetoStation.z+100.*u.cm : return False - # typical x,y Vx resolution for exclusive HNL decays 0.3cm,0.15cm (gaussian width) - if dist2InnerWall(X,Y,Z)<5*u.cm: return False - return True + + +def dist2InnerWall(X, Y, Z): + dist = 0 + # return distance to inner wall perpendicular to z-axis, if outside decayVolume return 0. + node = sGeo.FindNode(X, Y, Z) + if ShipGeo.tankDesign < 5: + if not "cave" in node.GetName(): + return dist # TP + else: + if not "DecayVacuum" in node.GetName(): + return dist + start = array("d", [X, Y, Z]) + nsteps = 8 + dalpha = 2 * ROOT.TMath.Pi() / nsteps + rsq = X**2 + Y**2 + minDistance = 100 * u.m + for n in range(nsteps): + alpha = n * dalpha + sdir = array("d", [ROOT.TMath.Sin(alpha), ROOT.TMath.Cos(alpha), 0.0]) + node = sGeo.InitTrack(start, sdir) + nxt = sGeo.FindNextBoundary() + if ShipGeo.tankDesign < 5 and nxt.GetName().find("I") < 0: + return 0 + distance = sGeo.GetStep() + if distance < minDistance: + minDistance = distance + return minDistance + + +def isInFiducial(X, Y, Z): + if not fiducialCut: + return True + if Z > ShipGeo.TrackStation1.z: + return False + if Z < ShipGeo.vetoStation.z + 100.0 * u.cm: + return False + # typical x,y Vx resolution for exclusive HNL decays 0.3cm,0.15cm (gaussian width) + if dist2InnerWall(X, Y, Z) < 5 * u.cm: + return False + return True + + # -def ImpactParameter(point,tPos,tMom): - t = 0 - if hasattr(tMom,'P'): P = tMom.P() - else: P = tMom.Mag() - for i in range(3): t += tMom(i)/P*(point(i)-tPos(i)) - dist = 0 - for i in range(3): dist += (point(i)-tPos(i)-t*tMom(i)/P)**2 - dist = ROOT.TMath.Sqrt(dist) - return dist +def ImpactParameter(point, tPos, tMom): + t = 0 + if hasattr(tMom, "P"): + P = tMom.P() + else: + P = tMom.Mag() + for i in range(3): + t += tMom(i) / P * (point(i) - tPos(i)) + dist = 0 + for i in range(3): + dist += (point(i) - tPos(i) - t * tMom(i) / P) ** 2 + dist = ROOT.TMath.Sqrt(dist) + return dist + + # def checkHNLorigin(sTree): - flag = True - if not fiducialCut: return flag - flag = False -# only makes sense for signal == HNL - hnlkey = -1 - for n in range(sTree.MCTrack.GetEntries()): - mo = sTree.MCTrack[n].GetMotherId() - if mo <0: continue - if abs(sTree.MCTrack[mo].GetPdgCode()) == 9900015: - hnlkey = n - break - if hnlkey<0 : - ut.reportError("ShipAna: checkHNLorigin, no HNL found") - else: - # MCTrack after HNL should be first daughter - theHNLVx = sTree.MCTrack[hnlkey] - X,Y,Z = theHNLVx.GetStartX(),theHNLVx.GetStartY(),theHNLVx.GetStartZ() - if isInFiducial(X,Y,Z): flag = True - return flag - -def checkFiducialVolume(sTree,tkey,dy): -# extrapolate track to middle of magnet and check if in decay volume - inside = True - if not fiducialCut: return True - fT = sTree.FitTracks[tkey] - rc,pos,mom = TrackExtrapolateTool.extrapolateToPlane(fT,ShipGeo.Bfield.z) - if not rc: return False - if not dist2InnerWall(pos.X(),pos.Y(),pos.Z())>0: return False - return inside -def getPtruthFirst(sTree,mcPartKey): - Ptruth,Ptruthx,Ptruthy,Ptruthz = -1.,-1.,-1.,-1. - for ahit in sTree.strawtubesPoint: - if ahit.GetTrackID() == mcPartKey: - Ptruthx,Ptruthy,Ptruthz = ahit.GetPx(),ahit.GetPy(),ahit.GetPz() - Ptruth = ROOT.TMath.Sqrt(Ptruthx**2+Ptruthy**2+Ptruthz**2) - break - return Ptruth,Ptruthx,Ptruthy,Ptruthz + flag = True + if not fiducialCut: + return flag + flag = False + # only makes sense for signal == HNL + hnlkey = -1 + for n in range(sTree.MCTrack.GetEntries()): + mo = sTree.MCTrack[n].GetMotherId() + if mo < 0: + continue + if abs(sTree.MCTrack[mo].GetPdgCode()) == 9900015: + hnlkey = n + break + if hnlkey < 0: + ut.reportError("ShipAna: checkHNLorigin, no HNL found") + else: + # MCTrack after HNL should be first daughter + theHNLVx = sTree.MCTrack[hnlkey] + X, Y, Z = theHNLVx.GetStartX(), theHNLVx.GetStartY(), theHNLVx.GetStartZ() + if isInFiducial(X, Y, Z): + flag = True + return flag + + +def checkFiducialVolume(sTree, tkey, dy): + # extrapolate track to middle of magnet and check if in decay volume + inside = True + if not fiducialCut: + return True + fT = sTree.FitTracks[tkey] + rc, pos, mom = TrackExtrapolateTool.extrapolateToPlane(fT, ShipGeo.Bfield.z) + if not rc: + return False + if not dist2InnerWall(pos.X(), pos.Y(), pos.Z()) > 0: + return False + return inside + + +def getPtruthFirst(sTree, mcPartKey): + Ptruth, Ptruthx, Ptruthy, Ptruthz = -1.0, -1.0, -1.0, -1.0 + for ahit in sTree.strawtubesPoint: + if ahit.GetTrackID() == mcPartKey: + Ptruthx, Ptruthy, Ptruthz = ahit.GetPx(), ahit.GetPy(), ahit.GetPz() + Ptruth = ROOT.TMath.Sqrt(Ptruthx**2 + Ptruthy**2 + Ptruthz**2) + break + return Ptruth, Ptruthx, Ptruthy, Ptruthz + def access2SmearedHits(): - key = 0 - for ahit in ev.SmearedHits.GetObject(): - print(ahit[0],ahit[1],ahit[2],ahit[3],ahit[4],ahit[5],ahit[6]) - # follow link to true MCHit - mchit = TrackingHits[key] - mctrack = MCTracks[mchit.GetTrackID()] - print(mchit.GetZ(),mctrack.GetP(),mctrack.GetPdgCode()) - key+=1 - -def myVertex(t1,t2,PosDir): - # closest distance between two tracks + key = 0 + for ahit in ev.SmearedHits.GetObject(): + print(ahit[0], ahit[1], ahit[2], ahit[3], ahit[4], ahit[5], ahit[6]) + # follow link to true MCHit + mchit = TrackingHits[key] + mctrack = MCTracks[mchit.GetTrackID()] + print(mchit.GetZ(), mctrack.GetP(), mctrack.GetPdgCode()) + key += 1 + + +def myVertex(t1, t2, PosDir): + # closest distance between two tracks # d = |pq . u x v|/|u x v| - a = ROOT.TVector3(PosDir[t1][0](0) ,PosDir[t1][0](1), PosDir[t1][0](2)) - u = ROOT.TVector3(PosDir[t1][1](0),PosDir[t1][1](1),PosDir[t1][1](2)) - c = ROOT.TVector3(PosDir[t2][0](0) ,PosDir[t2][0](1), PosDir[t2][0](2)) - v = ROOT.TVector3(PosDir[t2][1](0),PosDir[t2][1](1),PosDir[t2][1](2)) - pq = a-c - uCrossv = u.Cross(v) - dist = pq.Dot(uCrossv)/(uCrossv.Mag()+1E-8) - # u.a - u.c + s*|u|**2 - u.v*t = 0 - # v.a - v.c + s*v.u - t*|v|**2 = 0 - E = u.Dot(a) - u.Dot(c) - F = v.Dot(a) - v.Dot(c) - A,B = u.Mag2(), -u.Dot(v) - C,D = u.Dot(v), -v.Mag2() - t = -(C*E-A*F)/(B*C-A*D) - X = c.x()+v.x()*t - Y = c.y()+v.y()*t - Z = c.z()+v.z()*t - return X,Y,Z,abs(dist) -def RedoVertexing(t1,t2): - PosDir = {} - for tr in [t1,t2]: - xx = sTree.FitTracks[tr].getFittedState() - PosDir[tr] = [xx.getPos(),xx.getDir()] - xv,yv,zv,doca = myVertex(t1,t2,PosDir) -# as we have learned, need iterative procedure - dz = 99999. - reps,states,newPosDir = {},{},{} - parallelToZ = ROOT.TVector3(0., 0., 1.) - rc = True - step = 0 - while dz > 0.1: - zBefore = zv - newPos = ROOT.TVector3(xv,yv,zv) - # make a new rep for track 1,2 - for tr in [t1,t2]: - xx = sTree.FitTracks[tr].getFittedState() - reps[tr] = ROOT.genfit.RKTrackRep(xx.getPDG()) - states[tr] = ROOT.genfit.StateOnPlane(reps[tr]) - reps[tr].setPosMom(states[tr],xx.getPos(),xx.getMom()) - try: - reps[tr].extrapolateToPoint(states[tr], newPos, False) - except: - print('SHiPAna: extrapolation did not worked') - rc = False - break - newPosDir[tr] = [reps[tr].getPos(states[tr]),reps[tr].getDir(states[tr])] - if not rc: break - xv,yv,zv,doca = myVertex(t1,t2,newPosDir) - dz = abs(zBefore-zv) - step+=1 - if step > 10: - print('abort iteration, too many steps, pos=',xv,yv,zv,' doca=',doca,'z before and dz',zBefore,dz) - rc = False - break - if not rc: return xv,yv,zv,doca,-1 # extrapolation failed, makes no sense to continue - LV={} - for tr in [t1,t2]: - mom = reps[tr].getMom(states[tr]) - pid = abs(states[tr].getPDG()) - if pid == 2212: pid = 211 - mass = PDG.GetParticle(pid).Mass() - E = ROOT.TMath.Sqrt( mass*mass + mom.Mag2() ) - LV[tr] = ROOT.TLorentzVector() - LV[tr].SetPxPyPzE(mom.x(),mom.y(),mom.z(),E) - HNLMom = LV[t1]+LV[t2] - return xv,yv,zv,doca,HNLMom -def fitSingleGauss(x,ba=None,be=None): - name = 'myGauss_'+x + a = ROOT.TVector3(PosDir[t1][0](0), PosDir[t1][0](1), PosDir[t1][0](2)) + u = ROOT.TVector3(PosDir[t1][1](0), PosDir[t1][1](1), PosDir[t1][1](2)) + c = ROOT.TVector3(PosDir[t2][0](0), PosDir[t2][0](1), PosDir[t2][0](2)) + v = ROOT.TVector3(PosDir[t2][1](0), PosDir[t2][1](1), PosDir[t2][1](2)) + pq = a - c + uCrossv = u.Cross(v) + dist = pq.Dot(uCrossv) / (uCrossv.Mag() + 1e-8) + # u.a - u.c + s*|u|**2 - u.v*t = 0 + # v.a - v.c + s*v.u - t*|v|**2 = 0 + E = u.Dot(a) - u.Dot(c) + F = v.Dot(a) - v.Dot(c) + A, B = u.Mag2(), -u.Dot(v) + C, D = u.Dot(v), -v.Mag2() + t = -(C * E - A * F) / (B * C - A * D) + X = c.x() + v.x() * t + Y = c.y() + v.y() * t + Z = c.z() + v.z() * t + return X, Y, Z, abs(dist) + + +def RedoVertexing(t1, t2): + PosDir = {} + for tr in [t1, t2]: + xx = sTree.FitTracks[tr].getFittedState() + PosDir[tr] = [xx.getPos(), xx.getDir()] + xv, yv, zv, doca = myVertex(t1, t2, PosDir) + # as we have learned, need iterative procedure + dz = 99999.0 + reps, states, newPosDir = {}, {}, {} + parallelToZ = ROOT.TVector3(0.0, 0.0, 1.0) + rc = True + step = 0 + while dz > 0.1: + zBefore = zv + newPos = ROOT.TVector3(xv, yv, zv) + # make a new rep for track 1,2 + for tr in [t1, t2]: + xx = sTree.FitTracks[tr].getFittedState() + reps[tr] = ROOT.genfit.RKTrackRep(xx.getPDG()) + states[tr] = ROOT.genfit.StateOnPlane(reps[tr]) + reps[tr].setPosMom(states[tr], xx.getPos(), xx.getMom()) + try: + reps[tr].extrapolateToPoint(states[tr], newPos, False) + except: + print("SHiPAna: extrapolation did not worked") + rc = False + break + newPosDir[tr] = [reps[tr].getPos(states[tr]), reps[tr].getDir(states[tr])] + if not rc: + break + xv, yv, zv, doca = myVertex(t1, t2, newPosDir) + dz = abs(zBefore - zv) + step += 1 + if step > 10: + print( + "abort iteration, too many steps, pos=", + xv, + yv, + zv, + " doca=", + doca, + "z before and dz", + zBefore, + dz, + ) + rc = False + break + if not rc: + return xv, yv, zv, doca, -1 # extrapolation failed, makes no sense to continue + LV = {} + for tr in [t1, t2]: + mom = reps[tr].getMom(states[tr]) + pid = abs(states[tr].getPDG()) + if pid == 2212: + pid = 211 + mass = PDG.GetParticle(pid).Mass() + E = ROOT.TMath.Sqrt(mass * mass + mom.Mag2()) + LV[tr] = ROOT.TLorentzVector() + LV[tr].SetPxPyPzE(mom.x(), mom.y(), mom.z(), E) + HNLMom = LV[t1] + LV[t2] + return xv, yv, zv, doca, HNLMom + + +def fitSingleGauss(x, ba=None, be=None): + name = "myGauss_" + x myGauss = h[x].GetListOfFunctions().FindObject(name) if not myGauss: - if not ba : ba = h[x].GetBinCenter(1) - if not be : be = h[x].GetBinCenter(h[x].GetNbinsX()) - bw = h[x].GetBinWidth(1) - mean = h[x].GetMean() - sigma = h[x].GetRMS() - norm = h[x].GetEntries()*0.3 - myGauss = ROOT.TF1(name,'[0]*'+str(bw)+'/([2]*sqrt(2*pi))*exp(-0.5*((x-[1])/[2])**2)+[3]',4) - myGauss.SetParameter(0,norm) - myGauss.SetParameter(1,mean) - myGauss.SetParameter(2,sigma) - myGauss.SetParameter(3,1.) - myGauss.SetParName(0,'Signal') - myGauss.SetParName(1,'Mean') - myGauss.SetParName(2,'Sigma') - myGauss.SetParName(3,'bckgr') - h[x].Fit(myGauss,'','',ba,be) + if not ba: + ba = h[x].GetBinCenter(1) + if not be: + be = h[x].GetBinCenter(h[x].GetNbinsX()) + bw = h[x].GetBinWidth(1) + mean = h[x].GetMean() + sigma = h[x].GetRMS() + norm = h[x].GetEntries() * 0.3 + myGauss = ROOT.TF1( + name, + "[0]*" + str(bw) + "/([2]*sqrt(2*pi))*exp(-0.5*((x-[1])/[2])**2)+[3]", + 4, + ) + myGauss.SetParameter(0, norm) + myGauss.SetParameter(1, mean) + myGauss.SetParameter(2, sigma) + myGauss.SetParameter(3, 1.0) + myGauss.SetParName(0, "Signal") + myGauss.SetParName(1, "Mean") + myGauss.SetParName(2, "Sigma") + myGauss.SetParName(3, "bckgr") + h[x].Fit(myGauss, "", "", ba, be) + def match2HNL(p): matched = False - hnlKey = [] - for t in [p.GetDaughter(0),p.GetDaughter(1)]: - mcp = sTree.fitTrack2MC[t] - while mcp > -0.5: - mo = sTree.MCTrack[mcp] - if abs(mo.GetPdgCode()) == 9900015: - hnlKey.append(mcp) - break - mcp = mo.GetMotherId() + hnlKey = [] + for t in [p.GetDaughter(0), p.GetDaughter(1)]: + mcp = sTree.fitTrack2MC[t] + while mcp > -0.5: + mo = sTree.MCTrack[mcp] + if abs(mo.GetPdgCode()) == 9900015: + hnlKey.append(mcp) + break + mcp = mo.GetMotherId() if len(hnlKey) == 2: - if hnlKey[0]==hnlKey[1]: matched = True + if hnlKey[0] == hnlKey[1]: + matched = True return matched + + def ecalCluster2MC(aClus): - # return MC track most contributing, and its fraction of energy - trackid = ctypes.c_int() - energy_dep = ctypes.c_double() - mcLink = {} - for i in range( aClus.Size() ): - mccell = ecalStructure.GetHitCell(aClus.CellNum(i)) # Get i'th cell of the cluster. - for n in range( mccell.TrackEnergySize()): - mccell.GetTrackEnergySlow(n, trackid, energy_dep) - if not abs(trackid.value)eMax: - eMax = mcLink[m] - mMax = m - return mMax,eMax/aClus.Energy() + # return MC track most contributing, and its fraction of energy + trackid = ctypes.c_int() + energy_dep = ctypes.c_double() + mcLink = {} + for i in range(aClus.Size()): + mccell = ecalStructure.GetHitCell( + aClus.CellNum(i) + ) # Get i'th cell of the cluster. + for n in range(mccell.TrackEnergySize()): + mccell.GetTrackEnergySlow(n, trackid, energy_dep) + if not abs(trackid.value) < sTree.MCTrack.GetEntries(): + tid = -1 + else: + tid = trackid.value + if tid not in mcLink: + mcLink[tid] = 0 + mcLink[tid] += energy_dep.value + # find trackid most contributing + eMax, mMax = 0, -1 + for m in mcLink: + if mcLink[m] > eMax: + eMax = mcLink[m] + mMax = m + return mMax, eMax / aClus.Energy() + def makePlots(): - ut.bookCanvas(h,key='ecalanalysis',title='cluster map',nx=800,ny=600,cx=1,cy=1) - cv = h['ecalanalysis'].cd(1) - h['ecalClusters'].Draw('colz') - ut.bookCanvas(h,key='ecalCluster2Track',title='Ecal cluster distances to track impact',nx=1600,ny=800,cx=4,cy=2) - if "ecalReconstructed_dist_mu+" in h: - cv = h['ecalCluster2Track'].cd(1) - h['ecalReconstructed_distx_mu+'].Draw() - cv = h['ecalCluster2Track'].cd(2) - h['ecalReconstructed_disty_mu+'].Draw() - if "ecalReconstructed_dist_pi+" in h: - cv = h['ecalCluster2Track'].cd(3) - h['ecalReconstructed_distx_pi+'].Draw() - cv = h['ecalCluster2Track'].cd(4) - h['ecalReconstructed_disty_pi+'].Draw() - if "ecalReconstructed_dist_mu-" in h: - cv = h['ecalCluster2Track'].cd(5) - h['ecalReconstructed_distx_mu-'].Draw() - cv = h['ecalCluster2Track'].cd(6) - h['ecalReconstructed_disty_mu-'].Draw() - if "ecalReconstructed_dist_pi-" in h: - cv = h['ecalCluster2Track'].cd(7) - h['ecalReconstructed_distx_pi-'].Draw() - cv = h['ecalCluster2Track'].cd(8) - h['ecalReconstructed_disty_pi-'].Draw() - - ut.bookCanvas(h,key='strawanalysis',title='Distance to wire and mean nr of hits',nx=1200,ny=600,cx=3,cy=1) - cv = h['strawanalysis'].cd(1) - h['disty'].Draw() - h['distu'].Draw('same') - h['distv'].Draw('same') - cv = h['strawanalysis'].cd(2) - h['meanhits'].Draw() - cv = h['strawanalysis'].cd(3) - h['meas2'].Draw() - ut.bookCanvas(h,key='fitresults',title='Fit Results',nx=1600,ny=1200,cx=2,cy=2) - cv = h['fitresults'].cd(1) - h['delPOverPz'].Draw('box') - cv = h['fitresults'].cd(2) - cv.SetLogy(1) - h['prob'].Draw() - cv = h['fitresults'].cd(3) - h['delPOverPz_proj'] = h['delPOverPz'].ProjectionY() - ROOT.gStyle.SetOptFit(11111) - h['delPOverPz_proj'].Draw() - h['delPOverPz_proj'].Fit('gaus') - cv = h['fitresults'].cd(4) - h['delPOverP2z_proj'] = h['delPOverP2z'].ProjectionY() - h['delPOverP2z_proj'].Draw() - fitSingleGauss('delPOverP2z_proj') - h['fitresults'].Print('fitresults.gif') - for x in ['','_pi0']: - ut.bookCanvas(h,key='fitresults2'+x,title='Fit Results '+x,nx=1600,ny=1200,cx=2,cy=2) - cv = h['fitresults2'+x].cd(1) - if x=='': - h['Doca'].SetXTitle('closest distance between 2 tracks [cm]') - h['Doca'].SetYTitle('N/1mm') - h['Doca'].Draw() - else: - h['pi0Mass'].SetXTitle('#gamma #gamma invariant mass [GeV/c^{2}]') - h['pi0Mass'].SetYTitle('N/'+str(int(h['pi0Mass'].GetBinWidth(1)*1000))+'MeV') - h['pi0Mass'].Draw() - fitResult = h['pi0Mass'].Fit('gaus','S','',0.08,0.19) - cv = h['fitresults2'+x].cd(2) - h['IP0'+x].SetXTitle('impact parameter to p-target [cm]') - h['IP0'+x].SetYTitle('N/1cm') - h['IP0'+x].Draw() - cv = h['fitresults2'+x].cd(3) - h['HNL'+x].SetXTitle('inv. mass [GeV/c^{2}]') - h['HNL'+x].SetYTitle('N/4MeV/c2') - h['HNL'+x].Draw() - fitSingleGauss('HNL'+x,0.9,1.1) - cv = h['fitresults2'+x].cd(4) - h['IP0/mass'+x].SetXTitle('inv. mass [GeV/c^{2}]') - h['IP0/mass'+x].SetYTitle('IP [cm]') - h['IP0/mass'+x].Draw('colz') - h['fitresults2'+x].Print('fitresults2'+x+'.gif') - ut.bookCanvas(h,key='vxpulls',title='Vertex resol and pulls',nx=1600,ny=1200,cx=3,cy=2) - cv = h['vxpulls'].cd(4) - h['Vxpull'].Draw() - cv = h['vxpulls'].cd(5) - h['Vypull'].Draw() - cv = h['vxpulls'].cd(6) - h['Vzpull'].Draw() - cv = h['vxpulls'].cd(1) - h['Vxresol'].Draw() - cv = h['vxpulls'].cd(2) - h['Vyresol'].Draw() - cv = h['vxpulls'].cd(3) - h['Vzresol'].Draw() - ut.bookCanvas(h,key='trpulls',title='momentum pulls',nx=1600,ny=600,cx=3,cy=1) - cv = h['trpulls'].cd(1) - h['pullPOverPx_proj']=h['pullPOverPx'].ProjectionY() - h['pullPOverPx_proj'].Draw() - cv = h['trpulls'].cd(2) - h['pullPOverPy_proj']=h['pullPOverPy'].ProjectionY() - h['pullPOverPy_proj'].Draw() - cv = h['trpulls'].cd(3) - h['pullPOverPz_proj']=h['pullPOverPz'].ProjectionY() - h['pullPOverPz_proj'].Draw() - ut.bookCanvas(h,key='vetodecisions',title='Veto Detectors',nx=1600,ny=600,cx=4,cy=1) - cv = h['vetodecisions'].cd(1) - cv.SetLogy(1) - h['nrtracks'].Draw() - cv = h['vetodecisions'].cd(2) - cv.SetLogy(1) - h['nrSVT'].Draw() - cv = h['vetodecisions'].cd(3) - cv.SetLogy(1) - h['nrSBT'].Draw() - cv = h['vetodecisions'].cd(4) - cv.SetLogy(1) - h['nrRPC'].Draw() -# - print('finished making plots') + ut.bookCanvas( + h, key="ecalanalysis", title="cluster map", nx=800, ny=600, cx=1, cy=1 + ) + cv = h["ecalanalysis"].cd(1) + h["ecalClusters"].Draw("colz") + ut.bookCanvas( + h, + key="ecalCluster2Track", + title="Ecal cluster distances to track impact", + nx=1600, + ny=800, + cx=4, + cy=2, + ) + if "ecalReconstructed_dist_mu+" in h: + cv = h["ecalCluster2Track"].cd(1) + h["ecalReconstructed_distx_mu+"].Draw() + cv = h["ecalCluster2Track"].cd(2) + h["ecalReconstructed_disty_mu+"].Draw() + if "ecalReconstructed_dist_pi+" in h: + cv = h["ecalCluster2Track"].cd(3) + h["ecalReconstructed_distx_pi+"].Draw() + cv = h["ecalCluster2Track"].cd(4) + h["ecalReconstructed_disty_pi+"].Draw() + if "ecalReconstructed_dist_mu-" in h: + cv = h["ecalCluster2Track"].cd(5) + h["ecalReconstructed_distx_mu-"].Draw() + cv = h["ecalCluster2Track"].cd(6) + h["ecalReconstructed_disty_mu-"].Draw() + if "ecalReconstructed_dist_pi-" in h: + cv = h["ecalCluster2Track"].cd(7) + h["ecalReconstructed_distx_pi-"].Draw() + cv = h["ecalCluster2Track"].cd(8) + h["ecalReconstructed_disty_pi-"].Draw() + + ut.bookCanvas( + h, + key="strawanalysis", + title="Distance to wire and mean nr of hits", + nx=1200, + ny=600, + cx=3, + cy=1, + ) + cv = h["strawanalysis"].cd(1) + h["disty"].Draw() + h["distu"].Draw("same") + h["distv"].Draw("same") + cv = h["strawanalysis"].cd(2) + h["meanhits"].Draw() + cv = h["strawanalysis"].cd(3) + h["meas2"].Draw() + ut.bookCanvas( + h, key="fitresults", title="Fit Results", nx=1600, ny=1200, cx=2, cy=2 + ) + cv = h["fitresults"].cd(1) + h["delPOverPz"].Draw("box") + cv = h["fitresults"].cd(2) + cv.SetLogy(1) + h["prob"].Draw() + cv = h["fitresults"].cd(3) + h["delPOverPz_proj"] = h["delPOverPz"].ProjectionY() + ROOT.gStyle.SetOptFit(11111) + h["delPOverPz_proj"].Draw() + h["delPOverPz_proj"].Fit("gaus") + cv = h["fitresults"].cd(4) + h["delPOverP2z_proj"] = h["delPOverP2z"].ProjectionY() + h["delPOverP2z_proj"].Draw() + fitSingleGauss("delPOverP2z_proj") + h["fitresults"].Print("fitresults.gif") + for x in ["", "_pi0"]: + ut.bookCanvas( + h, + key="fitresults2" + x, + title="Fit Results " + x, + nx=1600, + ny=1200, + cx=2, + cy=2, + ) + cv = h["fitresults2" + x].cd(1) + if x == "": + h["Doca"].SetXTitle("closest distance between 2 tracks [cm]") + h["Doca"].SetYTitle("N/1mm") + h["Doca"].Draw() + else: + h["pi0Mass"].SetXTitle("#gamma #gamma invariant mass [GeV/c^{2}]") + h["pi0Mass"].SetYTitle( + "N/" + str(int(h["pi0Mass"].GetBinWidth(1) * 1000)) + "MeV" + ) + h["pi0Mass"].Draw() + fitResult = h["pi0Mass"].Fit("gaus", "S", "", 0.08, 0.19) + cv = h["fitresults2" + x].cd(2) + h["IP0" + x].SetXTitle("impact parameter to p-target [cm]") + h["IP0" + x].SetYTitle("N/1cm") + h["IP0" + x].Draw() + cv = h["fitresults2" + x].cd(3) + h["HNL" + x].SetXTitle("inv. mass [GeV/c^{2}]") + h["HNL" + x].SetYTitle("N/4MeV/c2") + h["HNL" + x].Draw() + fitSingleGauss("HNL" + x, 0.9, 1.1) + cv = h["fitresults2" + x].cd(4) + h["IP0/mass" + x].SetXTitle("inv. mass [GeV/c^{2}]") + h["IP0/mass" + x].SetYTitle("IP [cm]") + h["IP0/mass" + x].Draw("colz") + h["fitresults2" + x].Print("fitresults2" + x + ".gif") + ut.bookCanvas( + h, key="vxpulls", title="Vertex resol and pulls", nx=1600, ny=1200, cx=3, cy=2 + ) + cv = h["vxpulls"].cd(4) + h["Vxpull"].Draw() + cv = h["vxpulls"].cd(5) + h["Vypull"].Draw() + cv = h["vxpulls"].cd(6) + h["Vzpull"].Draw() + cv = h["vxpulls"].cd(1) + h["Vxresol"].Draw() + cv = h["vxpulls"].cd(2) + h["Vyresol"].Draw() + cv = h["vxpulls"].cd(3) + h["Vzresol"].Draw() + ut.bookCanvas(h, key="trpulls", title="momentum pulls", nx=1600, ny=600, cx=3, cy=1) + cv = h["trpulls"].cd(1) + h["pullPOverPx_proj"] = h["pullPOverPx"].ProjectionY() + h["pullPOverPx_proj"].Draw() + cv = h["trpulls"].cd(2) + h["pullPOverPy_proj"] = h["pullPOverPy"].ProjectionY() + h["pullPOverPy_proj"].Draw() + cv = h["trpulls"].cd(3) + h["pullPOverPz_proj"] = h["pullPOverPz"].ProjectionY() + h["pullPOverPz_proj"].Draw() + ut.bookCanvas( + h, key="vetodecisions", title="Veto Detectors", nx=1600, ny=600, cx=4, cy=1 + ) + cv = h["vetodecisions"].cd(1) + cv.SetLogy(1) + h["nrtracks"].Draw() + cv = h["vetodecisions"].cd(2) + cv.SetLogy(1) + h["nrSVT"].Draw() + cv = h["vetodecisions"].cd(3) + cv.SetLogy(1) + h["nrSBT"].Draw() + cv = h["vetodecisions"].cd(4) + cv.SetLogy(1) + h["nrRPC"].Draw() + # + print("finished making plots") + + # calculate z front face of ecal, needed later top = ROOT.gGeoManager.GetTopVolume() ecal = None -if top.GetNode('Ecal_1'): - ecal = top.GetNode('Ecal_1') - z_ecal = ecal.GetMatrix().GetTranslation()[2] -elif top.GetNode('SplitCalDetector_1'): - ecal = top.GetNode('SplitCalDetector_1') - z_ecal = ecal.GetMatrix().GetTranslation()[2] +if top.GetNode("Ecal_1"): + ecal = top.GetNode("Ecal_1") + z_ecal = ecal.GetMatrix().GetTranslation()[2] +elif top.GetNode("SplitCalDetector_1"): + ecal = top.GetNode("SplitCalDetector_1") + z_ecal = ecal.GetMatrix().GetTranslation()[2] + # start event loop def myEventLoop(n): - global ecalReconstructed - rc = sTree.GetEntry(n) -# check if tracks are made from real pattern recognition - measCut = measCutFK - if sTree.GetBranch("FitTracks_PR"): - sTree.FitTracks = sTree.FitTracks_PR - measCut = measCutPR - if sTree.GetBranch("fitTrack2MC_PR"): sTree.fitTrack2MC = sTree.fitTrack2MC_PR - if sTree.GetBranch("Particles_PR"): sTree.Particles = sTree.Particles_PR - if not checkHNLorigin(sTree): return - if not sTree.MCTrack.GetEntries()>1: wg = 1. - else: wg = sTree.MCTrack[1].GetWeight() - if not wg>0.: wg=1. - -# make some ecal cluster analysis if exist - if hasattr(sTree,"EcalClusters"): - if calReco: ecalReconstructed.Delete() - else: ecalReconstructed = sTree.EcalReconstructed - for x in caloTasks: - if x.GetName() == 'ecalFiller': x.Exec('start',sTree.EcalPointLite) - elif x.GetName() == 'ecalMatch': x.Exec('start',ecalReconstructed,sTree.MCTrack) - else : x.Exec('start') - for aClus in ecalReconstructed: - mMax = aClus.MCTrack() - if mMax <0 or mMax > sTree.MCTrack.GetEntries(): - aP = None # this should never happen, otherwise the ECAL MC matching has a bug - else: aP = sTree.MCTrack[mMax] - if aP: - tmp = PDG.GetParticle(aP.GetPdgCode()) - if tmp: pName = 'ecalReconstructed_'+tmp.GetName() - else: pName = 'ecalReconstructed_'+str(aP.GetPdgCode()) + global ecalReconstructed + rc = sTree.GetEntry(n) + # check if tracks are made from real pattern recognition + measCut = measCutFK + if sTree.GetBranch("FitTracks_PR"): + sTree.FitTracks = sTree.FitTracks_PR + measCut = measCutPR + if sTree.GetBranch("fitTrack2MC_PR"): + sTree.fitTrack2MC = sTree.fitTrack2MC_PR + if sTree.GetBranch("Particles_PR"): + sTree.Particles = sTree.Particles_PR + if not checkHNLorigin(sTree): + return + if not sTree.MCTrack.GetEntries() > 1: + wg = 1.0 else: - pName = 'ecalReconstructed_unknown' - if pName not in h: - ut.bookHist(h,pName,'x/y and energy for '+pName.split('_')[1],50,-3.,3.,50,-6.,6.) - rc = h[pName].Fill(aClus.X()/u.m,aClus.Y()/u.m,aClus.RecoE()/u.GeV) -# look at distance to tracks - for fT in sTree.FitTracks: - rc,pos,mom = TrackExtrapolateTool.extrapolateToPlane(fT,z_ecal) - if rc: - pdgcode = fT.getFittedState().getPDG() - tmp = PDG.GetParticle(pdgcode) - if tmp: tName = 'ecalReconstructed_dist_'+tmp.GetName() - else: tName = 'ecalReconstructed_dist_'+str(aP.GetPdgCode()) - if tName not in h: - p = tName.split('dist_')[1] - ut.bookHist(h,tName,'Ecal cluster distance t0 '+p,100,0.,100.*u.cm) - ut.bookHist(h,tName.replace('dist','distx'),'Ecal cluster distance to '+p+' in X ',100,-50.*u.cm,50.*u.cm) - ut.bookHist(h,tName.replace('dist','disty'),'Ecal cluster distance to '+p+' in Y ',100,-50.*u.cm,50.*u.cm) - dist = ROOT.TMath.Sqrt( (aClus.X()-pos.X())**2+(aClus.Y()-pos.Y())**2 ) - rc = h[tName].Fill(dist) - rc = h[tName.replace('dist','distx')].Fill( aClus.X()-pos.X() ) - rc = h[tName.replace('dist','disty')].Fill( aClus.Y()-pos.Y() ) -# compare with old method - for aClus in sTree.EcalClusters: - rc = h['ecalClusters'].Fill(aClus.X()/u.m,aClus.Y()/u.m,aClus.Energy()/u.GeV) - mMax,frac = ecalCluster2MC(aClus) -# return MC track most contributing, and its fraction of energy - if mMax>0: - aP = sTree.MCTrack[mMax] - tmp = PDG.GetParticle(aP.GetPdgCode()) - if tmp: pName = 'ecalClusters_'+tmp.GetName() - else: pName = 'ecalClusters_'+str(aP.GetPdgCode()) - else: - pName = 'ecalClusters_unknown' - if pName not in h: ut.bookHist(h,pName,'x/y and energy for '+pName.split('_')[1],50,-3.,3.,50,-6.,6.) - rc = h[pName].Fill(aClus.X()/u.m,aClus.Y()/u.m,aClus.Energy()/u.GeV) - -# make some straw hit analysis - hitlist = {} - for ahit in sTree.strawtubesPoint: - detID = ahit.GetDetectorID() - top = ROOT.TVector3() - bot = ROOT.TVector3() - modules["Strawtubes"].StrawEndPoints(detID,bot,top) - dw = ahit.dist2Wire() - if detID < 50000000 : - if abs(top.y())==abs(bot.y()): h['disty'].Fill(dw) - if abs(top.y())>abs(bot.y()): h['distu'].Fill(dw) - if abs(top.y())chi2CutOff: continue - h['delPOverP2'].Fill(Ptruth,delPOverP) - h['delPOverP2z'].Fill(Ptruth,delPOverPz) -# try measure impact parameter - trackDir = fittedState.getDir() - trackPos = fittedState.getPos() - vx = ROOT.TVector3() - mcPart.GetStartVertex(vx) - t = 0 - for i in range(3): t += trackDir(i)*(vx(i)-trackPos(i)) - dist = 0 - for i in range(3): dist += (vx(i)-trackPos(i)-t*trackDir(i))**2 - dist = ROOT.TMath.Sqrt(dist) - h['IP'].Fill(dist) -# --- -# loop over particles, 2-track combinations - for HNL in sTree.Particles: - t1,t2 = HNL.GetDaughter(0),HNL.GetDaughter(1) -# kill tracks outside fiducial volume, if enabled - if not checkFiducialVolume(sTree,t1,dy) or not checkFiducialVolume(sTree,t2,dy) : continue - checkMeasurements = True -# cut on nDOF - for tr in [t1,t2]: - fitStatus = sTree.FitTracks[tr].getFitStatus() - nmeas = fitStatus.getNdf() - if nmeas < measCut: checkMeasurements = False - if not checkMeasurements: continue -# check mc matching - if not match2HNL(HNL): continue - HNLPos = ROOT.TLorentzVector() - HNL.ProductionVertex(HNLPos) - HNLMom = ROOT.TLorentzVector() - HNL.Momentum(HNLMom) - doca = HNL.GetDoca() -# redo doca calculation - # xv,yv,zv,doca,HNLMom = RedoVertexing(t1,t2) - # if HNLMom == -1: continue - # check if decay inside decay volume - if not isInFiducial(HNLPos.X(),HNLPos.Y(),HNLPos.Z()): continue - h['Doca'].Fill(doca) - if doca > docaCut : continue - tr = ROOT.TVector3(0,0,ShipGeo.target.z0) - -# look for pi0 - for pi0 in pi0Reco.findPi0(sTree,HNLPos): - rc = h['pi0Mass'].Fill(pi0.M()) - if abs(pi0.M()-0.135)>0.02: continue -# could also be used for eta, by changing cut - HNLwithPi0 = HNLMom + pi0 - dist = ImpactParameter(tr,HNLPos,HNLwithPi0) - mass = HNLwithPi0.M() - h['IP0_pi0'].Fill(dist) - h['IP0/mass_pi0'].Fill(mass,dist) - h['HNL_pi0'].Fill(mass) - - dist = ImpactParameter(tr,HNLPos,HNLMom) - mass = HNLMom.M() - h['IP0'].Fill(dist) - h['IP0/mass'].Fill(mass,dist) - h['HNL'].Fill(mass) - h['HNLw'].Fill(mass,wg) -# - vetoDets['SBT'] = veto.SBT_decision() - vetoDets['SVT'] = veto.SVT_decision() - vetoDets['RPC'] = veto.RPC_decision() - vetoDets['TRA'] = veto.Track_decision() - h['nrtracks'].Fill(vetoDets['TRA'][2]) - h['nrSVT'].Fill(vetoDets['SVT'][2]) - h['nrSBT'].Fill(vetoDets['SBT'][2]) - h['nrRPC'].Fill(vetoDets['RPC'][2]) -# HNL true - mctrack = sTree.MCTrack[sTree.fitTrack2MC[t1]] - h['Vzresol'].Fill( (mctrack.GetStartZ()-HNLPos.Z())/u.cm ) - h['Vxresol'].Fill( (mctrack.GetStartX()-HNLPos.X())/u.cm ) - h['Vyresol'].Fill( (mctrack.GetStartY()-HNLPos.Y())/u.cm ) - PosDir,newPosDir,CovMat,scalFac = {},{},{},{} -# opening angle at vertex - newPos = ROOT.TVector3(HNLPos.X(),HNLPos.Y(),HNLPos.Z()) - st1,st2 = sTree.FitTracks[t1].getFittedState(),sTree.FitTracks[t2].getFittedState() - PosDir[t1] = {'position':st1.getPos(),'direction':st1.getDir(),'momentum':st1.getMom()} - PosDir[t2] = {'position':st2.getPos(),'direction':st2.getDir(),'momentum':st2.getMom()} - CovMat[t1] = st1.get6DCov() - CovMat[t2] = st2.get6DCov() - rep1,rep2 = ROOT.genfit.RKTrackRep(st1.getPDG()),ROOT.genfit.RKTrackRep(st2.getPDG()) - state1,state2 = ROOT.genfit.StateOnPlane(rep1),ROOT.genfit.StateOnPlane(rep2) - rep1.setPosMom(state1,st1.getPos(),st1.getMom()) - rep2.setPosMom(state2,st2.getPos(),st2.getMom()) - try: - rep1.extrapolateToPoint(state1, newPos, False) - rep2.extrapolateToPoint(state2, newPos, False) - mom1,mom2 = rep1.getMom(state1),rep2.getMom(state2) - except: - mom1,mom2 = st1.getMom(),st2.getMom() - newPosDir[t1] = {'position':rep1.getPos(state1),'direction':rep1.getDir(state1),'momentum':mom1} - newPosDir[t2] = {'position':rep2.getPos(state2),'direction':rep2.getDir(state2),'momentum':mom2} - oa = mom1.Dot(mom2)/(mom1.Mag()*mom2.Mag()) - h['oa'].Fill(oa) -# - covX = HNL.GetCovV() - dist = HNL.GetDoca() - h['Vzpull'].Fill( (mctrack.GetStartZ()-HNLPos.Z())/ROOT.TMath.Sqrt(covX[2][2]) ) - h['Vxpull'].Fill( (mctrack.GetStartX()-HNLPos.X())/ROOT.TMath.Sqrt(covX[0][0]) ) - h['Vypull'].Fill( (mctrack.GetStartY()-HNLPos.Y())/ROOT.TMath.Sqrt(covX[1][1]) ) - -# check extrapolation to TimeDet if exists - if hasattr(ShipGeo,"TimeDet"): - for fT in sTree.FitTracks: - rc,pos,mom = TrackExtrapolateTool.extrapolateToPlane(fT,ShipGeo.TimeDet.z) - if rc: - for aPoint in sTree.TimeDetPoint: - h['extrapTimeDetX'].Fill(pos.X()-aPoint.GetX()) - h['extrapTimeDetY'].Fill(pos.Y()-aPoint.GetY()) + wg = sTree.MCTrack[1].GetWeight() + if not wg > 0.0: + wg = 1.0 + + # make some ecal cluster analysis if exist + if hasattr(sTree, "EcalClusters"): + if calReco: + ecalReconstructed.Delete() + else: + ecalReconstructed = sTree.EcalReconstructed + for x in caloTasks: + if x.GetName() == "ecalFiller": + x.Exec("start", sTree.EcalPointLite) + elif x.GetName() == "ecalMatch": + x.Exec("start", ecalReconstructed, sTree.MCTrack) + else: + x.Exec("start") + for aClus in ecalReconstructed: + mMax = aClus.MCTrack() + if mMax < 0 or mMax > sTree.MCTrack.GetEntries(): + aP = None # this should never happen, otherwise the ECAL MC matching has a bug + else: + aP = sTree.MCTrack[mMax] + if aP: + tmp = PDG.GetParticle(aP.GetPdgCode()) + if tmp: + pName = "ecalReconstructed_" + tmp.GetName() + else: + pName = "ecalReconstructed_" + str(aP.GetPdgCode()) + else: + pName = "ecalReconstructed_unknown" + if pName not in h: + ut.bookHist( + h, + pName, + "x/y and energy for " + pName.split("_")[1], + 50, + -3.0, + 3.0, + 50, + -6.0, + 6.0, + ) + rc = h[pName].Fill(aClus.X() / u.m, aClus.Y() / u.m, aClus.RecoE() / u.GeV) + # look at distance to tracks + for fT in sTree.FitTracks: + rc, pos, mom = TrackExtrapolateTool.extrapolateToPlane(fT, z_ecal) + if rc: + pdgcode = fT.getFittedState().getPDG() + tmp = PDG.GetParticle(pdgcode) + if tmp: + tName = "ecalReconstructed_dist_" + tmp.GetName() + else: + tName = "ecalReconstructed_dist_" + str(aP.GetPdgCode()) + if tName not in h: + p = tName.split("dist_")[1] + ut.bookHist( + h, + tName, + "Ecal cluster distance t0 " + p, + 100, + 0.0, + 100.0 * u.cm, + ) + ut.bookHist( + h, + tName.replace("dist", "distx"), + "Ecal cluster distance to " + p + " in X ", + 100, + -50.0 * u.cm, + 50.0 * u.cm, + ) + ut.bookHist( + h, + tName.replace("dist", "disty"), + "Ecal cluster distance to " + p + " in Y ", + 100, + -50.0 * u.cm, + 50.0 * u.cm, + ) + dist = ROOT.TMath.Sqrt( + (aClus.X() - pos.X()) ** 2 + (aClus.Y() - pos.Y()) ** 2 + ) + rc = h[tName].Fill(dist) + rc = h[tName.replace("dist", "distx")].Fill(aClus.X() - pos.X()) + rc = h[tName.replace("dist", "disty")].Fill(aClus.Y() - pos.Y()) + # compare with old method + for aClus in sTree.EcalClusters: + rc = h["ecalClusters"].Fill( + aClus.X() / u.m, aClus.Y() / u.m, aClus.Energy() / u.GeV + ) + mMax, frac = ecalCluster2MC(aClus) + # return MC track most contributing, and its fraction of energy + if mMax > 0: + aP = sTree.MCTrack[mMax] + tmp = PDG.GetParticle(aP.GetPdgCode()) + if tmp: + pName = "ecalClusters_" + tmp.GetName() + else: + pName = "ecalClusters_" + str(aP.GetPdgCode()) + else: + pName = "ecalClusters_unknown" + if pName not in h: + ut.bookHist( + h, + pName, + "x/y and energy for " + pName.split("_")[1], + 50, + -3.0, + 3.0, + 50, + -6.0, + 6.0, + ) + rc = h[pName].Fill(aClus.X() / u.m, aClus.Y() / u.m, aClus.Energy() / u.GeV) + + # make some straw hit analysis + hitlist = {} + for ahit in sTree.strawtubesPoint: + detID = ahit.GetDetectorID() + top = ROOT.TVector3() + bot = ROOT.TVector3() + modules["Strawtubes"].StrawEndPoints(detID, bot, top) + dw = ahit.dist2Wire() + if detID < 50000000: + if abs(top.y()) == abs(bot.y()): + h["disty"].Fill(dw) + if abs(top.y()) > abs(bot.y()): + h["distu"].Fill(dw) + if abs(top.y()) < abs(bot.y()): + h["distv"].Fill(dw) + # + trID = ahit.GetTrackID() + if not trID < 0: + if trID in hitlist: + hitlist[trID] += 1 + else: + hitlist[trID] = 1 + for tr in hitlist: + h["meanhits"].Fill(hitlist[tr]) + key = -1 + fittedTracks = {} + for atrack in sTree.FitTracks: + key += 1 + # kill tracks outside fiducial volume + if not checkFiducialVolume(sTree, key, dy): + continue + fitStatus = atrack.getFitStatus() + nmeas = fitStatus.getNdf() + h["meas"].Fill(nmeas) + if not fitStatus.isFitConverged(): + continue + h["meas2"].Fill(nmeas) + if nmeas < measCut: + continue + fittedTracks[key] = atrack + # needs different study why fit has not converged, continue with fitted tracks + rchi2 = fitStatus.getChi2() + prob = ROOT.TMath.Prob(rchi2, int(nmeas)) + h["prob"].Fill(prob) + chi2 = rchi2 / nmeas + fittedState = atrack.getFittedState() + h["chi2"].Fill(chi2, wg) + h["measVSchi2"].Fill(atrack.getNumPoints(), chi2) + P = fittedState.getMomMag() + Px, Py, Pz = ( + fittedState.getMom().x(), + fittedState.getMom().y(), + fittedState.getMom().z(), + ) + cov = fittedState.get6DCov() + if len(sTree.fitTrack2MC) - 1 < key: + continue + mcPartKey = sTree.fitTrack2MC[key] + mcPart = sTree.MCTrack[mcPartKey] + if not mcPart: + continue + Ptruth_start = mcPart.GetP() + Ptruthz_start = mcPart.GetPz() + # get p truth from first strawpoint + Ptruth, Ptruthx, Ptruthy, Ptruthz = getPtruthFirst(sTree, mcPartKey) + delPOverP = (Ptruth - P) / Ptruth + h["delPOverP"].Fill(Ptruth, delPOverP) + delPOverPz = (1.0 / Ptruthz - 1.0 / Pz) * Ptruthz + h["pullPOverPx"].Fill(Ptruth, (Ptruthx - Px) / ROOT.TMath.Sqrt(cov[3][3])) + h["pullPOverPy"].Fill(Ptruth, (Ptruthy - Py) / ROOT.TMath.Sqrt(cov[4][4])) + h["pullPOverPz"].Fill(Ptruth, (Ptruthz - Pz) / ROOT.TMath.Sqrt(cov[5][5])) + h["delPOverPz"].Fill(Ptruthz, delPOverPz) + if chi2 > chi2CutOff: + continue + h["delPOverP2"].Fill(Ptruth, delPOverP) + h["delPOverP2z"].Fill(Ptruth, delPOverPz) + # try measure impact parameter + trackDir = fittedState.getDir() + trackPos = fittedState.getPos() + vx = ROOT.TVector3() + mcPart.GetStartVertex(vx) + t = 0 + for i in range(3): + t += trackDir(i) * (vx(i) - trackPos(i)) + dist = 0 + for i in range(3): + dist += (vx(i) - trackPos(i) - t * trackDir(i)) ** 2 + dist = ROOT.TMath.Sqrt(dist) + h["IP"].Fill(dist) + # --- + # loop over particles, 2-track combinations + for HNL in sTree.Particles: + t1, t2 = HNL.GetDaughter(0), HNL.GetDaughter(1) + # kill tracks outside fiducial volume, if enabled + if not checkFiducialVolume(sTree, t1, dy) or not checkFiducialVolume( + sTree, t2, dy + ): + continue + checkMeasurements = True + # cut on nDOF + for tr in [t1, t2]: + fitStatus = sTree.FitTracks[tr].getFitStatus() + nmeas = fitStatus.getNdf() + if nmeas < measCut: + checkMeasurements = False + if not checkMeasurements: + continue + # check mc matching + if not match2HNL(HNL): + continue + HNLPos = ROOT.TLorentzVector() + HNL.ProductionVertex(HNLPos) + HNLMom = ROOT.TLorentzVector() + HNL.Momentum(HNLMom) + doca = HNL.GetDoca() + # redo doca calculation + # xv,yv,zv,doca,HNLMom = RedoVertexing(t1,t2) + # if HNLMom == -1: continue + # check if decay inside decay volume + if not isInFiducial(HNLPos.X(), HNLPos.Y(), HNLPos.Z()): + continue + h["Doca"].Fill(doca) + if doca > docaCut: + continue + tr = ROOT.TVector3(0, 0, ShipGeo.target.z0) + + # look for pi0 + for pi0 in pi0Reco.findPi0(sTree, HNLPos): + rc = h["pi0Mass"].Fill(pi0.M()) + if abs(pi0.M() - 0.135) > 0.02: + continue + # could also be used for eta, by changing cut + HNLwithPi0 = HNLMom + pi0 + dist = ImpactParameter(tr, HNLPos, HNLwithPi0) + mass = HNLwithPi0.M() + h["IP0_pi0"].Fill(dist) + h["IP0/mass_pi0"].Fill(mass, dist) + h["HNL_pi0"].Fill(mass) + + dist = ImpactParameter(tr, HNLPos, HNLMom) + mass = HNLMom.M() + h["IP0"].Fill(dist) + h["IP0/mass"].Fill(mass, dist) + h["HNL"].Fill(mass) + h["HNLw"].Fill(mass, wg) + # + vetoDets["SBT"] = veto.SBT_decision() + vetoDets["SVT"] = veto.SVT_decision() + vetoDets["RPC"] = veto.RPC_decision() + vetoDets["TRA"] = veto.Track_decision() + h["nrtracks"].Fill(vetoDets["TRA"][2]) + h["nrSVT"].Fill(vetoDets["SVT"][2]) + h["nrSBT"].Fill(vetoDets["SBT"][2]) + h["nrRPC"].Fill(vetoDets["RPC"][2]) + # HNL true + mctrack = sTree.MCTrack[sTree.fitTrack2MC[t1]] + h["Vzresol"].Fill((mctrack.GetStartZ() - HNLPos.Z()) / u.cm) + h["Vxresol"].Fill((mctrack.GetStartX() - HNLPos.X()) / u.cm) + h["Vyresol"].Fill((mctrack.GetStartY() - HNLPos.Y()) / u.cm) + PosDir, newPosDir, CovMat, scalFac = {}, {}, {}, {} + # opening angle at vertex + newPos = ROOT.TVector3(HNLPos.X(), HNLPos.Y(), HNLPos.Z()) + st1, st2 = ( + sTree.FitTracks[t1].getFittedState(), + sTree.FitTracks[t2].getFittedState(), + ) + PosDir[t1] = { + "position": st1.getPos(), + "direction": st1.getDir(), + "momentum": st1.getMom(), + } + PosDir[t2] = { + "position": st2.getPos(), + "direction": st2.getDir(), + "momentum": st2.getMom(), + } + CovMat[t1] = st1.get6DCov() + CovMat[t2] = st2.get6DCov() + rep1, rep2 = ( + ROOT.genfit.RKTrackRep(st1.getPDG()), + ROOT.genfit.RKTrackRep(st2.getPDG()), + ) + state1, state2 = ROOT.genfit.StateOnPlane(rep1), ROOT.genfit.StateOnPlane(rep2) + rep1.setPosMom(state1, st1.getPos(), st1.getMom()) + rep2.setPosMom(state2, st2.getPos(), st2.getMom()) + try: + rep1.extrapolateToPoint(state1, newPos, False) + rep2.extrapolateToPoint(state2, newPos, False) + mom1, mom2 = rep1.getMom(state1), rep2.getMom(state2) + except: + mom1, mom2 = st1.getMom(), st2.getMom() + newPosDir[t1] = { + "position": rep1.getPos(state1), + "direction": rep1.getDir(state1), + "momentum": mom1, + } + newPosDir[t2] = { + "position": rep2.getPos(state2), + "direction": rep2.getDir(state2), + "momentum": mom2, + } + oa = mom1.Dot(mom2) / (mom1.Mag() * mom2.Mag()) + h["oa"].Fill(oa) + # + covX = HNL.GetCovV() + dist = HNL.GetDoca() + h["Vzpull"].Fill( + (mctrack.GetStartZ() - HNLPos.Z()) / ROOT.TMath.Sqrt(covX[2][2]) + ) + h["Vxpull"].Fill( + (mctrack.GetStartX() - HNLPos.X()) / ROOT.TMath.Sqrt(covX[0][0]) + ) + h["Vypull"].Fill( + (mctrack.GetStartY() - HNLPos.Y()) / ROOT.TMath.Sqrt(covX[1][1]) + ) + + # check extrapolation to TimeDet if exists + if hasattr(ShipGeo, "TimeDet"): + for fT in sTree.FitTracks: + rc, pos, mom = TrackExtrapolateTool.extrapolateToPlane( + fT, ShipGeo.TimeDet.z + ) + if rc: + for aPoint in sTree.TimeDetPoint: + h["extrapTimeDetX"].Fill(pos.X() - aPoint.GetX()) + h["extrapTimeDetY"].Fill(pos.Y() - aPoint.GetY()) + + # def HNLKinematics(): - HNLorigin={} - ut.bookHist(h,'HNLmomNoW','momentum unweighted',100,0.,300.) - ut.bookHist(h,'HNLmom','momentum',100,0.,300.) - ut.bookHist(h,'HNLPtNoW','Pt unweighted',100,0.,10.) - ut.bookHist(h,'HNLPt','Pt',100,0.,10.) - ut.bookHist(h,'HNLmom_recTracks','momentum',100,0.,300.) - ut.bookHist(h,'HNLmomNoW_recTracks','momentum unweighted',100,0.,300.) - for n in range(sTree.GetEntries()): - rc = sTree.GetEntry(n) - for hnlkey in [1,2]: - if abs(sTree.MCTrack[hnlkey].GetPdgCode()) == 9900015: - theHNL = sTree.MCTrack[hnlkey] - wg = theHNL.GetWeight() - if not wg>0.: wg=1. - idMother = abs(sTree.MCTrack[hnlkey-1].GetPdgCode()) - if idMother not in HNLorigin: HNLorigin[idMother]=0 - HNLorigin[idMother]+=wg - P = theHNL.GetP() - Pt = theHNL.GetPt() - h['HNLmom'].Fill(P,wg) - h['HNLmomNoW'].Fill(P) - h['HNLPt'].Fill(Pt,wg) - h['HNLPtNoW'].Fill(Pt) - for HNL in sTree.Particles: - t1,t2 = HNL.GetDaughter(0),HNL.GetDaughter(1) - for tr in [t1,t2]: - xx = sTree.FitTracks[tr].getFittedState() - Prec = xx.getMom().Mag() - h['HNLmom_recTracks'].Fill(Prec,wg) - h['HNLmomNoW_recTracks'].Fill(Prec) - theSum = 0 - for x in HNLorigin: theSum+=HNLorigin[x] - for x in HNLorigin: print("%4i : %5.4F relative fraction: %5.4F "%(x,HNLorigin[x],HNLorigin[x]/theSum)) + HNLorigin = {} + ut.bookHist(h, "HNLmomNoW", "momentum unweighted", 100, 0.0, 300.0) + ut.bookHist(h, "HNLmom", "momentum", 100, 0.0, 300.0) + ut.bookHist(h, "HNLPtNoW", "Pt unweighted", 100, 0.0, 10.0) + ut.bookHist(h, "HNLPt", "Pt", 100, 0.0, 10.0) + ut.bookHist(h, "HNLmom_recTracks", "momentum", 100, 0.0, 300.0) + ut.bookHist(h, "HNLmomNoW_recTracks", "momentum unweighted", 100, 0.0, 300.0) + for n in range(sTree.GetEntries()): + rc = sTree.GetEntry(n) + for hnlkey in [1, 2]: + if abs(sTree.MCTrack[hnlkey].GetPdgCode()) == 9900015: + theHNL = sTree.MCTrack[hnlkey] + wg = theHNL.GetWeight() + if not wg > 0.0: + wg = 1.0 + idMother = abs(sTree.MCTrack[hnlkey - 1].GetPdgCode()) + if idMother not in HNLorigin: + HNLorigin[idMother] = 0 + HNLorigin[idMother] += wg + P = theHNL.GetP() + Pt = theHNL.GetPt() + h["HNLmom"].Fill(P, wg) + h["HNLmomNoW"].Fill(P) + h["HNLPt"].Fill(Pt, wg) + h["HNLPtNoW"].Fill(Pt) + for HNL in sTree.Particles: + t1, t2 = HNL.GetDaughter(0), HNL.GetDaughter(1) + for tr in [t1, t2]: + xx = sTree.FitTracks[tr].getFittedState() + Prec = xx.getMom().Mag() + h["HNLmom_recTracks"].Fill(Prec, wg) + h["HNLmomNoW_recTracks"].Fill(Prec) + theSum = 0 + for x in HNLorigin: + theSum += HNLorigin[x] + for x in HNLorigin: + print( + "%4i : %5.4F relative fraction: %5.4F " + % (x, HNLorigin[x], HNLorigin[x] / theSum) + ) + + # # initialize ecalStructure caloTasks = [] calReco = False sTree.GetEvent(0) if ecal: - ecalGeo = ecalGeoFile+'z'+str(ShipGeo.ecal.z)+".geo" - if not ecalGeo in os.listdir(os.environ["FAIRSHIP"]+"/geometry"): shipDet_conf.makeEcalGeoFile(ShipGeo.ecal.z,ShipGeo.ecal.File) - ecalFiller = ROOT.ecalStructureFiller("ecalFiller", 0,ecalGeo) - ecalFiller.SetUseMCPoints(ROOT.kTRUE) - ecalFiller.StoreTrackInformation() - ecalStructure = ecalFiller.InitPython(sTree.EcalPointLite) - caloTasks.append(ecalFiller) - - if hasattr(sTree,"EcalReconstructed"): - calReco = False - ecalReconstructed = sTree.EcalReconstructed - else: - calReco = True - print("setup calo reconstruction of ecalReconstructed objects") -# Calorimeter reconstruction - #GeV -> ADC conversion - ecalDigi=ROOT.ecalDigi("ecalDigi",0) - ecalPrepare=ROOT.ecalPrepare("ecalPrepare",0) - ecalStructure = ecalFiller.InitPython(sTree.EcalPointLite) - ecalDigi.InitPython(ecalStructure) - caloTasks.append(ecalDigi) - ecalPrepare.InitPython(ecalStructure) - caloTasks.append(ecalPrepare) - # Cluster calibration - ecalClusterCalib=ROOT.ecalClusterCalibration("ecalClusterCalibration", 0) - #4x4 cm cells - ecalCl3PhS=ROOT.TFormula("ecalCl3PhS", "[0]+x*([1]+x*([2]+x*[3]))") - ecalCl3PhS.SetParameters(6.77797e-04, 5.75385e+00, 3.42690e-03, -1.16383e-04) - ecalClusterCalib.SetStraightCalibration(3, ecalCl3PhS) - ecalCl3Ph=ROOT.TFormula("ecalCl3Ph", "[0]+x*([1]+x*([2]+x*[3]))+[4]*x*y+[5]*x*y*y") - ecalCl3Ph.SetParameters(0.000750975, 5.7552, 0.00282783, -8.0025e-05, -0.000823651, 0.000111561) - ecalClusterCalib.SetCalibration(3, ecalCl3Ph) -#6x6 cm cells - ecalCl2PhS=ROOT.TFormula("ecalCl2PhS", "[0]+x*([1]+x*([2]+x*[3]))") - ecalCl2PhS.SetParameters(8.14724e-04, 5.67428e+00, 3.39030e-03, -1.28388e-04) - ecalClusterCalib.SetStraightCalibration(2, ecalCl2PhS) - ecalCl2Ph=ROOT.TFormula("ecalCl2Ph", "[0]+x*([1]+x*([2]+x*[3]))+[4]*x*y+[5]*x*y*y") - ecalCl2Ph.SetParameters(0.000948095, 5.67471, 0.00339177, -0.000122629, -0.000169109, 8.33448e-06) - ecalClusterCalib.SetCalibration(2, ecalCl2Ph) - caloTasks.append(ecalClusterCalib) - ecalReco=ROOT.ecalReco('ecalReco',0) - caloTasks.append(ecalReco) -# Match reco to MC - ecalMatch=ROOT.ecalMatch('ecalMatch',0) - caloTasks.append(ecalMatch) - ecalCalib = ecalClusterCalib.InitPython() - ecalReconstructed = ecalReco.InitPython(sTree.EcalClusters, ecalStructure, ecalCalib) - ecalMatch.InitPython(ecalStructure, ecalReconstructed, sTree.MCTrack) - -options.nEvents = min(sTree.GetEntries(),options.nEvents) + ecalGeo = ecalGeoFile + "z" + str(ShipGeo.ecal.z) + ".geo" + if not ecalGeo in os.listdir(os.environ["FAIRSHIP"] + "/geometry"): + shipDet_conf.makeEcalGeoFile(ShipGeo.ecal.z, ShipGeo.ecal.File) + ecalFiller = ROOT.ecalStructureFiller("ecalFiller", 0, ecalGeo) + ecalFiller.SetUseMCPoints(ROOT.kTRUE) + ecalFiller.StoreTrackInformation() + ecalStructure = ecalFiller.InitPython(sTree.EcalPointLite) + caloTasks.append(ecalFiller) + + if hasattr(sTree, "EcalReconstructed"): + calReco = False + ecalReconstructed = sTree.EcalReconstructed + else: + calReco = True + print("setup calo reconstruction of ecalReconstructed objects") + # Calorimeter reconstruction + # GeV -> ADC conversion + ecalDigi = ROOT.ecalDigi("ecalDigi", 0) + ecalPrepare = ROOT.ecalPrepare("ecalPrepare", 0) + ecalStructure = ecalFiller.InitPython(sTree.EcalPointLite) + ecalDigi.InitPython(ecalStructure) + caloTasks.append(ecalDigi) + ecalPrepare.InitPython(ecalStructure) + caloTasks.append(ecalPrepare) + # Cluster calibration + ecalClusterCalib = ROOT.ecalClusterCalibration("ecalClusterCalibration", 0) + # 4x4 cm cells + ecalCl3PhS = ROOT.TFormula("ecalCl3PhS", "[0]+x*([1]+x*([2]+x*[3]))") + ecalCl3PhS.SetParameters(6.77797e-04, 5.75385e00, 3.42690e-03, -1.16383e-04) + ecalClusterCalib.SetStraightCalibration(3, ecalCl3PhS) + ecalCl3Ph = ROOT.TFormula( + "ecalCl3Ph", "[0]+x*([1]+x*([2]+x*[3]))+[4]*x*y+[5]*x*y*y" + ) + ecalCl3Ph.SetParameters( + 0.000750975, 5.7552, 0.00282783, -8.0025e-05, -0.000823651, 0.000111561 + ) + ecalClusterCalib.SetCalibration(3, ecalCl3Ph) + # 6x6 cm cells + ecalCl2PhS = ROOT.TFormula("ecalCl2PhS", "[0]+x*([1]+x*([2]+x*[3]))") + ecalCl2PhS.SetParameters(8.14724e-04, 5.67428e00, 3.39030e-03, -1.28388e-04) + ecalClusterCalib.SetStraightCalibration(2, ecalCl2PhS) + ecalCl2Ph = ROOT.TFormula( + "ecalCl2Ph", "[0]+x*([1]+x*([2]+x*[3]))+[4]*x*y+[5]*x*y*y" + ) + ecalCl2Ph.SetParameters( + 0.000948095, 5.67471, 0.00339177, -0.000122629, -0.000169109, 8.33448e-06 + ) + ecalClusterCalib.SetCalibration(2, ecalCl2Ph) + caloTasks.append(ecalClusterCalib) + ecalReco = ROOT.ecalReco("ecalReco", 0) + caloTasks.append(ecalReco) + # Match reco to MC + ecalMatch = ROOT.ecalMatch("ecalMatch", 0) + caloTasks.append(ecalMatch) + ecalCalib = ecalClusterCalib.InitPython() + ecalReconstructed = ecalReco.InitPython( + sTree.EcalClusters, ecalStructure, ecalCalib + ) + ecalMatch.InitPython(ecalStructure, ecalReconstructed, sTree.MCTrack) + +options.nEvents = min(sTree.GetEntries(), options.nEvents) import pi0Reco -ut.bookHist(h,'pi0Mass','gamma gamma inv mass',100,0.,0.5) + +ut.bookHist(h, "pi0Mass", "gamma gamma inv mass", 100, 0.0, 0.5) for n in range(options.nEvents): - myEventLoop(n) - sTree.FitTracks.Delete() + myEventLoop(n) + sTree.FitTracks.Delete() makePlots() # output histograms -hfile = options.inputFile.split(',')[0].replace('_rec','_ana') -if hfile[0:4] == "/eos" or not options.inputFile.find(',')<0: -# do not write to eos, write to local directory - tmp = hfile.split('/') - hfile = tmp[len(tmp)-1] +hfile = options.inputFile.split(",")[0].replace("_rec", "_ana") +if hfile[0:4] == "/eos" or not options.inputFile.find(",") < 0: + # do not write to eos, write to local directory + tmp = hfile.split("/") + hfile = tmp[len(tmp) - 1] ROOT.gROOT.cd() -ut.writeHists(h,hfile) +ut.writeHists(h, hfile) diff --git a/macro/ShipReco.py b/macro/ShipReco.py index 4be4cb6545..a9a09b07b7 100644 --- a/macro/ShipReco.py +++ b/macro/ShipReco.py @@ -2,113 +2,209 @@ from argparse import ArgumentParser withHists = True -pidProton = False # if true, take truth, if False fake with pion mass +pidProton = False # if true, take truth, if False fake with pion mass import resource + + def mem_monitor(): - # Getting virtual memory size + # Getting virtual memory size pid = os.getpid() with open(os.path.join("/proc", str(pid), "status")) as f: lines = f.readlines() _vmsize = [l for l in lines if l.startswith("VmSize")][0] vmsize = int(_vmsize.split()[1]) - #Getting physical memory size + # Getting physical memory size pmsize = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss - print("memory: virtuell = %5.2F MB physical = %5.2F MB"%(vmsize/1.0E3,pmsize/1.0E3)) + print( + "memory: virtuell = %5.2F MB physical = %5.2F MB" + % (vmsize / 1.0e3, pmsize / 1.0e3) + ) + + +import os +import sys -import ROOT,os,sys import global_variables +import ROOT import rootUtils as ut -import shipunit as u import shipRoot_conf +import shipunit as u shipRoot_conf.configure() parser = ArgumentParser() -parser.add_argument("-f", "--inputFile", dest="inputFile", help="Input file", required=True) -parser.add_argument("-n", "--nEvents", dest="nEvents", help="Number of events to reconstruct", required=False, default=999999,type=int) -parser.add_argument("-g", "--geoFile", dest="geoFile", help="ROOT geofile", required=True) -parser.add_argument("--noVertexing", dest="noVertexing", help="switch off vertexing", required=False, action="store_true") -parser.add_argument("--noStrawSmearing", dest="withNoStrawSmearing", help="no smearing of distance to wire, default on", required=False, action="store_true") -parser.add_argument("--withT0", dest="withT0", help="simulate arbitrary T0 and correct for it", required=False, action="store_true") -parser.add_argument("--ecalDebugDraw", dest="EcalDebugDraw", help="switch in debog for ECAL", required=False, action="store_true") -parser.add_argument("--saveDisk", dest="saveDisk", help="if set, will remove input file, only rec file kept", required=False, action="store_true") -parser.add_argument("-i", "--firstEvent",dest="firstEvent", help="First event of input file to use", required=False, default=0,type=int) -parser.add_argument("--realPR", dest="realPR", help="Option for pattern recognition without MC truth. \n\ +parser.add_argument( + "-f", "--inputFile", dest="inputFile", help="Input file", required=True +) +parser.add_argument( + "-n", + "--nEvents", + dest="nEvents", + help="Number of events to reconstruct", + required=False, + default=999999, + type=int, +) +parser.add_argument( + "-g", "--geoFile", dest="geoFile", help="ROOT geofile", required=True +) +parser.add_argument( + "--noVertexing", + dest="noVertexing", + help="switch off vertexing", + required=False, + action="store_true", +) +parser.add_argument( + "--noStrawSmearing", + dest="withNoStrawSmearing", + help="no smearing of distance to wire, default on", + required=False, + action="store_true", +) +parser.add_argument( + "--withT0", + dest="withT0", + help="simulate arbitrary T0 and correct for it", + required=False, + action="store_true", +) +parser.add_argument( + "--ecalDebugDraw", + dest="EcalDebugDraw", + help="switch in debog for ECAL", + required=False, + action="store_true", +) +parser.add_argument( + "--saveDisk", + dest="saveDisk", + help="if set, will remove input file, only rec file kept", + required=False, + action="store_true", +) +parser.add_argument( + "-i", + "--firstEvent", + dest="firstEvent", + help="First event of input file to use", + required=False, + default=0, + type=int, +) +parser.add_argument( + "--realPR", + dest="realPR", + help="Option for pattern recognition without MC truth. \n\ FH : Hough transform.\n\ AR : Artificial retina.\n\ - TemplateMatching : Tracks are searched for based on the template: track seed + hits within a window around the seed."\ - , required=False, choices=['FH','AR','TemplateMatching'], default='') -parser.add_argument("-dy", dest="dy", help="Max height of tank", required=False, default=None,type=int) -parser.add_argument("--Debug", dest="Debug", help="Switch on debugging", required=False, action="store_true") + TemplateMatching : Tracks are searched for based on the template: track seed + hits within a window around the seed.", + required=False, + choices=["FH", "AR", "TemplateMatching"], + default="", +) +parser.add_argument( + "-dy", dest="dy", help="Max height of tank", required=False, default=None, type=int +) +parser.add_argument( + "--Debug", + dest="Debug", + help="Switch on debugging", + required=False, + action="store_true", +) options = parser.parse_args() vertexing = not options.noVertexing -if options.EcalDebugDraw: ROOT.gSystem.Load("libASImage") +if options.EcalDebugDraw: + ROOT.gSystem.Load("libASImage") # need to figure out which geometry was used, only needed if no geo file if not options.dy: - # try to extract from input file name - tmp = options.inputFile.split('.') - try: - dy = float( tmp[1]+'.'+tmp[2] ) - except: - dy = None - -print('configured to process ', options.nEvents, ' events from ', options.inputFile, - ' starting with event ', options.firstEvent, ' with option Yheight = ' ,dy, - ' with vertexing', vertexing, ' and real pattern reco ', options.realPR) -if not options.inputFile.find('_rec.root') < 0: - outFile = options.inputFile - options.inputFile = outFile.replace('_rec.root','.root') + # try to extract from input file name + tmp = options.inputFile.split(".") + try: + dy = float(tmp[1] + "." + tmp[2]) + except: + dy = None + +print( + "configured to process ", + options.nEvents, + " events from ", + options.inputFile, + " starting with event ", + options.firstEvent, + " with option Yheight = ", + dy, + " with vertexing", + vertexing, + " and real pattern reco ", + options.realPR, +) +if not options.inputFile.find("_rec.root") < 0: + outFile = options.inputFile + options.inputFile = outFile.replace("_rec.root", ".root") else: - outFile = options.inputFile.replace('.root','_rec.root') -# outfile should be in local directory - tmp = outFile.split('/') - outFile = tmp[len(tmp)-1] - if options.inputFile[:7]=="root://" : os.system('xrdcp '+options.inputFile+' '+outFile) - elif options.saveDisk: os.system('mv '+options.inputFile+' '+outFile) - else : os.system('cp '+options.inputFile+' '+outFile) + outFile = options.inputFile.replace(".root", "_rec.root") + # outfile should be in local directory + tmp = outFile.split("/") + outFile = tmp[len(tmp) - 1] + if options.inputFile[:7] == "root://": + os.system("xrdcp " + options.inputFile + " " + outFile) + elif options.saveDisk: + os.system("mv " + options.inputFile + " " + outFile) + else: + os.system("cp " + options.inputFile + " " + outFile) if not options.geoFile: - tmp = options.inputFile.replace('ship.','geofile_full.') - options.geoFile = tmp.replace('_rec','') + tmp = options.inputFile.replace("ship.", "geofile_full.") + options.geoFile = tmp.replace("_rec", "") fgeo = ROOT.TFile.Open(options.geoFile) -geoMat = ROOT.genfit.TGeoMaterialInterface() # if only called in ShipDigiReco -> crash, reason unknown +geoMat = ( + ROOT.genfit.TGeoMaterialInterface() +) # if only called in ShipDigiReco -> crash, reason unknown -from ShipGeoConfig import ConfigRegistry from rootpyPickler import Unpickler -#load Shipgeo dictionary -upkl = Unpickler(fgeo) -ShipGeo = upkl.load('ShipGeo') +from ShipGeoConfig import ConfigRegistry + +# load Shipgeo dictionary +upkl = Unpickler(fgeo) +ShipGeo = upkl.load("ShipGeo") ecalGeoFile = ShipGeo.ecal.File -h={} -log={} +h = {} +log = {} if withHists: - ut.bookHist(h,'distu','distance to wire',100,0.,5.) - ut.bookHist(h,'distv','distance to wire',100,0.,5.) - ut.bookHist(h,'disty','distance to wire',100,0.,5.) - ut.bookHist(h,'nmeas','nr measuerements',100,0.,50.) - ut.bookHist(h,'chi2','Chi2/DOF',100,0.,20.) + ut.bookHist(h, "distu", "distance to wire", 100, 0.0, 5.0) + ut.bookHist(h, "distv", "distance to wire", 100, 0.0, 5.0) + ut.bookHist(h, "disty", "distance to wire", 100, 0.0, 5.0) + ut.bookHist(h, "nmeas", "nr measuerements", 100, 0.0, 50.0) + ut.bookHist(h, "chi2", "Chi2/DOF", 100, 0.0, 20.0) import shipDet_conf + run = ROOT.FairRunSim() run.SetName("TGeant4") # Transport engine -run.SetSink(ROOT.FairRootFileSink(ROOT.TMemFile('output', 'recreate'))) # Dummy output file -run.SetUserConfig("g4Config_basic.C") # geant4 transport not used, only needed for creating VMC field +run.SetSink( + ROOT.FairRootFileSink(ROOT.TMemFile("output", "recreate")) +) # Dummy output file +run.SetUserConfig( + "g4Config_basic.C" +) # geant4 transport not used, only needed for creating VMC field rtdb = run.GetRuntimeDb() # -----Create geometry---------------------------------------------- -modules = shipDet_conf.configure(run,ShipGeo) +modules = shipDet_conf.configure(run, ShipGeo) # run.Init() fgeo.FAIRGeom import geomGeant4 -if hasattr(ShipGeo.Bfield,"fieldMap"): - fieldMaker = geomGeant4.addVMCFields(ShipGeo, '', True,withVirtualMC = False) +if hasattr(ShipGeo.Bfield, "fieldMap"): + fieldMaker = geomGeant4.addVMCFields(ShipGeo, "", True, withVirtualMC=False) # make global variables global_variables.debug = options.Debug @@ -129,16 +225,16 @@ def mem_monitor(): # import reco tasks import shipDigiReco -SHiP = shipDigiReco.ShipDigiReco(outFile,fgeo) -options.nEvents = min(SHiP.sTree.GetEntries(),options.nEvents) +SHiP = shipDigiReco.ShipDigiReco(outFile, fgeo) +options.nEvents = min(SHiP.sTree.GetEntries(), options.nEvents) # main loop for global_variables.iEvent in range(options.firstEvent, options.nEvents): if global_variables.iEvent % 1000 == 0 or global_variables.debug: - print('event ', global_variables.iEvent) + print("event ", global_variables.iEvent) rc = SHiP.sTree.GetEvent(global_variables.iEvent) SHiP.digitize() SHiP.reconstruct() - # memory monitoring - # mem_monitor() +# memory monitoring +# mem_monitor() # end loop over events SHiP.finish() diff --git a/macro/checkZpositions.py b/macro/checkZpositions.py index 5b0fb7cf63..384c128434 100644 --- a/macro/checkZpositions.py +++ b/macro/checkZpositions.py @@ -1,18 +1,23 @@ -import ROOT,sys +import sys + +import ROOT from rootpyPickler import Unpickler -badBoys={} -f1,f2 = sys.argv[1], sys.argv[2] -fgeoOld=ROOT.TFile(f1) -upkl = Unpickler(fgeoOld) -ShipGeoOld = upkl.load('ShipGeo') -fgeoNew=ROOT.TFile(f2) -upkl = Unpickler(fgeoNew) -ShipGeoNew = upkl.load('ShipGeo') + +badBoys = {} +f1, f2 = sys.argv[1], sys.argv[2] +fgeoOld = ROOT.TFile(f1) +upkl = Unpickler(fgeoOld) +ShipGeoOld = upkl.load("ShipGeo") +fgeoNew = ROOT.TFile(f2) +upkl = Unpickler(fgeoNew) +ShipGeoNew = upkl.load("ShipGeo") for x in ShipGeoNew: - if hasattr(eval('ShipGeoNew.'+x),'z'): - zold,znew = eval('ShipGeoOld.'+x+'.z'),eval('ShipGeoNew.'+x+'.z') - print(x,'z=',znew, ' old:', zold) - if zold!=znew: badBoys[x]=[znew,zold] -if len(badBoys)>0: print("following differences detected:") + if hasattr(eval("ShipGeoNew." + x), "z"): + zold, znew = eval("ShipGeoOld." + x + ".z"), eval("ShipGeoNew." + x + ".z") + print(x, "z=", znew, " old:", zold) + if zold != znew: + badBoys[x] = [znew, zold] +if len(badBoys) > 0: + print("following differences detected:") for x in badBoys: - print(x,badBoys[x]) + print(x, badBoys[x]) diff --git a/macro/convertEvtCalc.py b/macro/convertEvtCalc.py index 96600de0e4..9fafc63863 100644 --- a/macro/convertEvtCalc.py +++ b/macro/convertEvtCalc.py @@ -1,7 +1,7 @@ """Convert files from EventCalc to ROOT format.""" -import sys import os +import sys from argparse import ArgumentParser import numpy as np @@ -93,11 +93,11 @@ def convert_file(infile, outdir): "vz", ] daughter_vars = [ - "px_prod", - "py_prod", - "pz_prod", - "e_prod", - "mass_prod", + "px_prod", + "py_prod", + "pz_prod", + "e_prod", + "mass_prod", "pdg_prod", ] fname = infile.split("/")[-1] @@ -111,19 +111,17 @@ def convert_file(infile, outdir): infile = f"{outdir}/{fname}" parsed_data = parse_file(infile) outfile = infile.split(".dat")[0] + ".root" - ncols = len(parsed_data[0][2]) + ncols = len(parsed_data[0][2]) nvardau = 6 # qualifiers for each daughter remaining_vars = ncols - len(vars_names) - - if (remaining_vars % nvardau)!=0: + + if (remaining_vars % nvardau) != 0: raise ValueError(f"- convertEvtCalc - Error: number of daughters is not exact.") - ndau = remaining_vars // nvardau + ndau = remaining_vars // nvardau print(f"- convertEvtCalc - Max multiplicity of daughters: {ndau}") - vars_names.extend( - f"{var}{i}" for i in range(1, ndau + 1) for var in daughter_vars - ) + vars_names.extend(f"{var}{i}" for i in range(1, ndau + 1) for var in daughter_vars) try: check_consistency_infile(nvars=len(vars_names), ncols=ncols) @@ -145,9 +143,9 @@ def convert_file(infile, outdir): for pt, sp, vars in parsed_data: for row in zip(*vars): for i, value in enumerate(row): - if i < len(vars_names)-1: + if i < len(vars_names) - 1: branch_f[vars_names[i]][0] = value - branch_f["ndau"][0] = ndau/1. + branch_f["ndau"][0] = ndau / 1.0 tree.Fill() tree.Write() @@ -185,4 +183,3 @@ def main(): if __name__ == "__main__": main() - diff --git a/macro/create_field_perturbation.py b/macro/create_field_perturbation.py index dfec0b62f1..6d237580b1 100644 --- a/macro/create_field_perturbation.py +++ b/macro/create_field_perturbation.py @@ -1,22 +1,30 @@ -import ROOT as r -import shipunit as u +import os +from argparse import ArgumentParser + import geomGeant4 -from ShipGeoConfig import ConfigRegistry -import shipDet_conf +import ROOT as r import saveBasicParameters -import os import ShieldUtils -from argparse import ArgumentParser +import shipDet_conf +import shipunit as u +from ShipGeoConfig import ConfigRegistry +globalDesigns = { + "dy": 10.0, + "dv": 6, + "ds": 9, + "nud": 3, + "caloDesign": 3, + "strawDesign": 10, +} -globalDesigns = {'dy': 10., 'dv': 6, 'ds': 9, 'nud': 3, 'caloDesign': 3, 'strawDesign': 10} def create_csv_field_map(options): r.gErrorIgnoreLevel = r.kWarning - r.gSystem.Load('libpythia8') + r.gSystem.Load("libpythia8") ship_geo = ConfigRegistry.loadpy( - '$FAIRSHIP/geometry/geometry_config.py', + "$FAIRSHIP/geometry/geometry_config.py", Yheight=globalDesigns["dy"], tankDesign=globalDesigns["dv"], nuTauTargetDesign=globalDesigns["nud"], @@ -25,46 +33,71 @@ def create_csv_field_map(options): muShieldDesign=options.ds, muShieldStepGeo=options.muShieldStepGeo, muShieldWithCobaltMagnet=options.muShieldWithCobaltMagnet, - muShieldGeo=options.geofile) + muShieldGeo=options.geofile, + ) ship_geo.muShield.WithConstField = True - run = r.FairRunSim() - run.SetName('TGeant4') # Transport engine + run.SetName("TGeant4") # Transport engine run.SetOutputFile("tmp_file") # Output file # user configuration file default g4Config.C - run.SetUserConfig('g4Config.C') + run.SetUserConfig("g4Config.C") modules = shipDet_conf.configure(run, ship_geo) primGen = r.FairPrimaryGenerator() - primGen.SetTarget(ship_geo.target.z0+70.845*u.m, 0.) + primGen.SetTarget(ship_geo.target.z0 + 70.845 * u.m, 0.0) # run.SetGenerator(primGen) run.SetStoreTraj(r.kFALSE) run.Init() - fieldMaker = geomGeant4.addVMCFields(ship_geo, '', True) + fieldMaker = geomGeant4.addVMCFields(ship_geo, "", True) field_center, shield_half_length = ShieldUtils.find_shield_center(ship_geo) - print("SHIELD ONLY: CENTER: {}, HALFLENGTH: {}, half_X: {}, half_Y: {}".format(field_center, - shield_half_length, - ship_geo.muShield.half_X_max, - ship_geo.muShield.half_Y_max)) - fieldMaker.generateFieldMap(os.path.expandvars("$FAIRSHIP/files/fieldMap.csv"), 2.5, - ship_geo.muShield.half_X_max, ship_geo.muShield.half_Y_max, - shield_half_length, field_center) + print( + "SHIELD ONLY: CENTER: {}, HALFLENGTH: {}, half_X: {}, half_Y: {}".format( + field_center, + shield_half_length, + ship_geo.muShield.half_X_max, + ship_geo.muShield.half_Y_max, + ) + ) + fieldMaker.generateFieldMap( + os.path.expandvars("$FAIRSHIP/files/fieldMap.csv"), + 2.5, + ship_geo.muShield.half_X_max, + ship_geo.muShield.half_Y_max, + shield_half_length, + field_center, + ) -if __name__ == '__main__': +if __name__ == "__main__": parser = ArgumentParser() parser.add_argument("--muShieldDesign", dest="ds", required=True, type=int) - parser.add_argument("--stepMuonShield", dest="muShieldStepGeo", help="activate steps geometry for the muon shield", - required=False, action="store_true", default=False) - parser.add_argument("--coMuonShield", dest="muShieldWithCobaltMagnet", - help="""replace one of the magnets in the shield with 2.2T cobalt one, + parser.add_argument( + "--stepMuonShield", + dest="muShieldStepGeo", + help="activate steps geometry for the muon shield", + required=False, + action="store_true", + default=False, + ) + parser.add_argument( + "--coMuonShield", + dest="muShieldWithCobaltMagnet", + help="""replace one of the magnets in the shield with 2.2T cobalt one, downscales other fields, works only for muShieldDesign >2""", - required=False, type=int, default=0) - parser.add_argument("-g", dest="geofile", help="geofile for muon shield geometry, for experts only", required=False, - default=None) + required=False, + type=int, + default=0, + ) + parser.add_argument( + "-g", + dest="geofile", + help="geofile for muon shield geometry, for experts only", + required=False, + default=None, + ) options = parser.parse_args() create_csv_field_map(options) diff --git a/macro/dumpEvent.py b/macro/dumpEvent.py index 3376e8f16f..f7eaeabfae 100644 --- a/macro/dumpEvent.py +++ b/macro/dumpEvent.py @@ -1,29 +1,50 @@ # example for dumping an MC event -import ROOT,os,sys +import os +import sys + +import ROOT import rootUtils as ut -import shipunit as u import ShipGeoConfig +import shipunit as u + ship_geo = ShipGeoConfig.Config().loadpy("$FAIRSHIP/geometry/geometry_config.py") PDG = ROOT.TDatabasePDG.Instance() -def printMCTrack(n,MCTrack): - mcp = MCTrack[n] - print(' %6i %7i %6.3F %6.3F %7.3F %7.3F %7.3F %7.3F %6i '%(n,mcp.GetPdgCode(),mcp.GetPx()/u.GeV,mcp.GetPy()/u.GeV,mcp.GetPz()/u.GeV, \ - mcp.GetStartX()/u.m,mcp.GetStartY()/u.m,mcp.GetStartZ()/u.m,mcp.GetMotherId() )) - -def dump(i,pcut): - tree = ROOT.gROOT.FindObjectAny('cbmsim') - tree.GetEntry(i) - print(' # pid px py pz vx vy vz mid') - n=-1 - for mcp in tree.MCTrack: - n+=1 - if mcp.GetP()/u.GeV < pcut : continue - printMCTrack(n,tree.MCTrack) + +def printMCTrack(n, MCTrack): + mcp = MCTrack[n] + print( + " %6i %7i %6.3F %6.3F %7.3F %7.3F %7.3F %7.3F %6i " + % ( + n, + mcp.GetPdgCode(), + mcp.GetPx() / u.GeV, + mcp.GetPy() / u.GeV, + mcp.GetPz() / u.GeV, + mcp.GetStartX() / u.m, + mcp.GetStartY() / u.m, + mcp.GetStartZ() / u.m, + mcp.GetMotherId(), + ) + ) + + +def dump(i, pcut): + tree = ROOT.gROOT.FindObjectAny("cbmsim") + tree.GetEntry(i) + print(" # pid px py pz vx vy vz mid") + n = -1 + for mcp in tree.MCTrack: + n += 1 + if mcp.GetP() / u.GeV < pcut: + continue + printMCTrack(n, tree.MCTrack) + + def dumpStraw(i): - tree = ROOT.gROOT.FindObjectAny('cbmsim') - tree.GetEntry(i) - for aStraw in tree.strawtubesPoint: - trID = astraw.GetTrackID() - if not trID < 0: - printMCTrack(trID,tree.MCTrack) + tree = ROOT.gROOT.FindObjectAny("cbmsim") + tree.GetEntry(i) + for aStraw in tree.strawtubesPoint: + trID = astraw.GetTrackID() + if not trID < 0: + printMCTrack(trID, tree.MCTrack) diff --git a/macro/evd_addParticleFollower.py b/macro/evd_addParticleFollower.py index ad7bcd7c43..dd551ba33a 100644 --- a/macro/evd_addParticleFollower.py +++ b/macro/evd_addParticleFollower.py @@ -1,80 +1,94 @@ -import ROOT,evd_fillEnergy -gEve=ROOT.gEve +import evd_fillEnergy +import ROOT + +gEve = ROOT.gEve import eveGlobal + + def execute(): - if not gEve.GetViewers().FindChild('Bar Embedded Viewer side'): - slot = ROOT.TEveWindow.CreateWindowInTab(gEve.GetBrowser().GetTabRight()) - pack1 = slot.MakePack() - pack1.SetShowTitleBar(ROOT.kFALSE) - pack1.SetElementName("Top/Side View") - pack1.SetVertical() -# Embedded viewer. - cams = ['side','top'] - for c in cams: - slot = pack1.NewSlot() - v = ROOT.TEveViewer("BarViewer"+c) - v.SpawnGLEmbeddedViewer(gEve.GetEditor()) - slot.ReplaceWindow(v) - v.SetElementName("Bar Embedded Viewer "+c) # gEve.GetViewers().FindChild('Bar Embedded Viewer') - v.SetShowTitleBar(ROOT.kFALSE) - gEve.GetViewers().AddElement(v) - v.AddScene(gEve.GetEventScene()) - v.AddScene(gEve.GetScenes().FindChild('Geometry scene')) - vw = v.GetGLViewer() - if c=='top': - vw.SetCurrentCamera(ROOT.TGLViewer.kCameraOrthoZnOX) - else: - vw.SetCurrentCamera(ROOT.TGLViewer.kCameraOrthoZOY) - vw.ResetCameras() - cam = vw.CurrentCamera() - cam.Reset() - ed = v.GetEditorObject() - co = ed.GetCameraOverlay() - if c=='top': - # doesn't really work - center = array('d',[0,500.,0]) - cam.Configure(1.0,0.,center,0.,0.) - co.SetShowOrthographic(True) - co.SetOrthographicMode(ROOT.TGLCameraOverlay.kAll) # ROOT.TGLCameraOverlay.kAxis - # cam.SetExternalCenter(ROOT.kTRUE) - ls = vw.GetLightSet() - ls.SetSidePower(1.0) - ls.SetFrontPower(1.0) - ls.SetSpecularPower(1.0) - else: - center = array('d',[0,0,0]) - cam.Configure(1.0,0.,center,0,0) - co.SetShowOrthographic(True) - co.SetOrthographicMode(ROOT.TGLCameraOverlay.kAll) # ROOT.TGLCameraOverlay.kAxis - ls = vw.GetLightSet() - ls.SetFrontPower(0.2) - ls.SetSidePower(0.4) - ls.SetSpecularPower(1.1) -# problems with light, Camera home - #cam.SetExternalCenter(ROOT.kTRUE) - vw.DoDraw() -# - slot = pack1.NewSlot() - slot.StartEmbedding() - can = ROOT.TCanvas("Root Canvas EnergyLoss") # ROOT.gROOT.FindObject('Root Canvas') - can.SetTitle('Energy as function of z') - can.ToggleEditor() - slot.StopEmbedding() - ls = ROOT.gROOT.GetListOfGlobals() - ls.Add(can) - SHiPDisplay = eveGlobal.SHiPDisplay - SHiPDisplay.transparentMode('on') -if __name__=="__main__": - execute() - v = ROOT.gEve.GetViewers().FindChild('Bar Embedded Viewer side') - vw = v.GetGLViewer() - cam = vw.CurrentCamera() - fr = vw.GetFrame() - test = ROOT.TGLVertex3(0.,0.,0.) - vtest = cam.ViewportToWorld(test) - zmin = vtest.Z() - test = ROOT.TGLVertex3(fr.GetWidth(),0.,0.) - vtest = cam.ViewportToWorld(test) - zmax = vtest.Z() - print("?",zmin,zmax) - evd_fillEnergy.execute() + if not gEve.GetViewers().FindChild("Bar Embedded Viewer side"): + slot = ROOT.TEveWindow.CreateWindowInTab(gEve.GetBrowser().GetTabRight()) + pack1 = slot.MakePack() + pack1.SetShowTitleBar(ROOT.kFALSE) + pack1.SetElementName("Top/Side View") + pack1.SetVertical() + # Embedded viewer. + cams = ["side", "top"] + for c in cams: + slot = pack1.NewSlot() + v = ROOT.TEveViewer("BarViewer" + c) + v.SpawnGLEmbeddedViewer(gEve.GetEditor()) + slot.ReplaceWindow(v) + v.SetElementName( + "Bar Embedded Viewer " + c + ) # gEve.GetViewers().FindChild('Bar Embedded Viewer') + v.SetShowTitleBar(ROOT.kFALSE) + gEve.GetViewers().AddElement(v) + v.AddScene(gEve.GetEventScene()) + v.AddScene(gEve.GetScenes().FindChild("Geometry scene")) + vw = v.GetGLViewer() + if c == "top": + vw.SetCurrentCamera(ROOT.TGLViewer.kCameraOrthoZnOX) + else: + vw.SetCurrentCamera(ROOT.TGLViewer.kCameraOrthoZOY) + vw.ResetCameras() + cam = vw.CurrentCamera() + cam.Reset() + ed = v.GetEditorObject() + co = ed.GetCameraOverlay() + if c == "top": + # doesn't really work + center = array("d", [0, 500.0, 0]) + cam.Configure(1.0, 0.0, center, 0.0, 0.0) + co.SetShowOrthographic(True) + co.SetOrthographicMode( + ROOT.TGLCameraOverlay.kAll + ) # ROOT.TGLCameraOverlay.kAxis + # cam.SetExternalCenter(ROOT.kTRUE) + ls = vw.GetLightSet() + ls.SetSidePower(1.0) + ls.SetFrontPower(1.0) + ls.SetSpecularPower(1.0) + else: + center = array("d", [0, 0, 0]) + cam.Configure(1.0, 0.0, center, 0, 0) + co.SetShowOrthographic(True) + co.SetOrthographicMode( + ROOT.TGLCameraOverlay.kAll + ) # ROOT.TGLCameraOverlay.kAxis + ls = vw.GetLightSet() + ls.SetFrontPower(0.2) + ls.SetSidePower(0.4) + ls.SetSpecularPower(1.1) + # problems with light, Camera home + # cam.SetExternalCenter(ROOT.kTRUE) + vw.DoDraw() + # + slot = pack1.NewSlot() + slot.StartEmbedding() + can = ROOT.TCanvas( + "Root Canvas EnergyLoss" + ) # ROOT.gROOT.FindObject('Root Canvas') + can.SetTitle("Energy as function of z") + can.ToggleEditor() + slot.StopEmbedding() + ls = ROOT.gROOT.GetListOfGlobals() + ls.Add(can) + SHiPDisplay = eveGlobal.SHiPDisplay + SHiPDisplay.transparentMode("on") + + +if __name__ == "__main__": + execute() + v = ROOT.gEve.GetViewers().FindChild("Bar Embedded Viewer side") + vw = v.GetGLViewer() + cam = vw.CurrentCamera() + fr = vw.GetFrame() + test = ROOT.TGLVertex3(0.0, 0.0, 0.0) + vtest = cam.ViewportToWorld(test) + zmin = vtest.Z() + test = ROOT.TGLVertex3(fr.GetWidth(), 0.0, 0.0) + vtest = cam.ViewportToWorld(test) + zmax = vtest.Z() + print("?", zmin, zmax) + evd_fillEnergy.execute() diff --git a/macro/evd_fillEnergy.py b/macro/evd_fillEnergy.py index fc50951fc8..bea66f66e3 100644 --- a/macro/evd_fillEnergy.py +++ b/macro/evd_fillEnergy.py @@ -1,111 +1,124 @@ +import eveGlobal import ROOT import shipunit as u -import eveGlobal def collect_hits(lsOfGlobals, checked_muons): - MUON = 13 - sTree = lsOfGlobals.FindObject('cbmsim') - - fPos = ROOT.TVector3() - fMom = ROOT.TVector3() - - muon_to_follow = -1 - for index, track in enumerate(sTree.MCTrack): - if abs(track.GetPdgCode()) == MUON and index not in checked_muons: - muon_to_follow = index - checked_muons.add(muon_to_follow) - break - - if muon_to_follow == -1: - return {} - - fT = sTree.MCTrack[muon_to_follow] - fT.GetStartVertex(fPos) - hitlist = {} - hitlist[fPos.Z()] = [fPos.X(), fPos.Y(), fT.GetP()] -# loop over all sensitive volumes to find hits - for P in ["vetoPoint", "muonPoint", "EcalPoint", "HcalPoint", - "strawtubesPoint", "ShipRpcPoint", "TargetPoint"]: - if not sTree.GetBranch(P): - continue - c = eval("sTree." + P) - for p in c: - if p.GetTrackID() == muon_to_follow: - p.Momentum(fMom) - if hasattr(p, "LastPoint"): - lp = p.LastPoint() - hitlist[lp.z()] = [lp.x(), lp.y(), p.LastMom().Mag()] - hitlist[2. * p.GetZ() - lp.z()] = [2. * p.GetX() - lp.x(), - 2. * p.GetY() - lp.y(), - fMom.Mag()] - else: - hitlist[p.GetZ()] = [p.GetX(), p.GetY(), fMom.Mag()] - return hitlist - - -def trajectory_init(lsOfGlobals, name='SHiP MuonTraj'): - traj = lsOfGlobals.FindObject(name) - if not traj: - traj = ROOT.TGraph() - traj.SetName(name) - traj.SetLineWidth(2) - lsOfGlobals.Add(traj) - traj.Set(0) - return traj + MUON = 13 + sTree = lsOfGlobals.FindObject("cbmsim") + + fPos = ROOT.TVector3() + fMom = ROOT.TVector3() + + muon_to_follow = -1 + for index, track in enumerate(sTree.MCTrack): + if abs(track.GetPdgCode()) == MUON and index not in checked_muons: + muon_to_follow = index + checked_muons.add(muon_to_follow) + break + + if muon_to_follow == -1: + return {} + + fT = sTree.MCTrack[muon_to_follow] + fT.GetStartVertex(fPos) + hitlist = {} + hitlist[fPos.Z()] = [fPos.X(), fPos.Y(), fT.GetP()] + # loop over all sensitive volumes to find hits + for P in [ + "vetoPoint", + "muonPoint", + "EcalPoint", + "HcalPoint", + "strawtubesPoint", + "ShipRpcPoint", + "TargetPoint", + ]: + if not sTree.GetBranch(P): + continue + c = eval("sTree." + P) + for p in c: + if p.GetTrackID() == muon_to_follow: + p.Momentum(fMom) + if hasattr(p, "LastPoint"): + lp = p.LastPoint() + hitlist[lp.z()] = [lp.x(), lp.y(), p.LastMom().Mag()] + hitlist[2.0 * p.GetZ() - lp.z()] = [ + 2.0 * p.GetX() - lp.x(), + 2.0 * p.GetY() - lp.y(), + fMom.Mag(), + ] + else: + hitlist[p.GetZ()] = [p.GetX(), p.GetY(), fMom.Mag()] + return hitlist + + +def trajectory_init(lsOfGlobals, name="SHiP MuonTraj"): + traj = lsOfGlobals.FindObject(name) + if not traj: + traj = ROOT.TGraph() + traj.SetName(name) + traj.SetLineWidth(2) + lsOfGlobals.Add(traj) + traj.Set(0) + return traj + def execute(): N_MUONS = 2 - canvas = ROOT.gROOT.FindObject('Root Canvas EnergyLoss') + canvas = ROOT.gROOT.FindObject("Root Canvas EnergyLoss") if not canvas: - print("add particle flower not started!") - return + print("add particle flower not started!") + return lsOfGlobals = ROOT.gROOT.GetListOfGlobals() c1 = canvas.cd(1) c1.Clear() -# get zmin, zmax from graphic + # get zmin, zmax from graphic SHiPDisplay = eveGlobal.SHiPDisplay - v = ROOT.gEve.GetViewers().FindChild('Bar Embedded Viewer side') + v = ROOT.gEve.GetViewers().FindChild("Bar Embedded Viewer side") vw = v.GetGLViewer() cam = vw.CurrentCamera() ed = v.GetEditorObject() co = ed.GetCameraOverlay() ax = co.GetAttAxis() fr = vw.GetFrame() - test = ROOT.TGLVertex3(0., 0., 0.) + test = ROOT.TGLVertex3(0.0, 0.0, 0.0) vtest = cam.ViewportToWorld(test) zmin = vtest.Z() - test = ROOT.TGLVertex3(fr.GetWidth(), 0., 0.) + test = ROOT.TGLVertex3(fr.GetWidth(), 0.0, 0.0) vtest = cam.ViewportToWorld(test) zmax = vtest.Z() - checked_muons = set() - all_muons_hitlist = [collect_hits(lsOfGlobals, checked_muons) for _ in range(N_MUONS)] + all_muons_hitlist = [ + collect_hits(lsOfGlobals, checked_muons) for _ in range(N_MUONS) + ] all_muons_hitlist = list(filter(lambda x: x, all_muons_hitlist)) - trajectories = [trajectory_init(lsOfGlobals, "SHiP MuonTraj_" + str(index)) - for index in range(len(all_muons_hitlist))] + trajectories = [ + trajectory_init(lsOfGlobals, "SHiP MuonTraj_" + str(index)) + for index in range(len(all_muons_hitlist)) + ] - emin, emax = 1E9, -1E9 + emin, emax = 1e9, -1e9 for trajectory, hitlist in zip(trajectories, all_muons_hitlist): - for index, z in enumerate(sorted(hitlist.keys())): - E = hitlist[z][2] - trajectory.SetPoint(index, z, E) - emax = max(emax, E) - emin = min(emin, E) + for index, z in enumerate(sorted(hitlist.keys())): + E = hitlist[z][2] + trajectory.SetPoint(index, z, E) + emax = max(emax, E) + emin = min(emin, E) emin, emax = emin * 0.9, emax * 1.1 print("zmin/max", zmin, zmax) hist = c1.DrawFrame(zmin, emin, zmax, emax) - hist.SetYTitle('p (GeV/c)') - hist.SetXTitle('z cm') + hist.SetYTitle("p (GeV/c)") + hist.SetXTitle("z cm") xaxis = hist.GetXaxis() xaxis.SetNdivisions(ax.GetNdivisions()) for trajectory in trajectories: - trajectory.Draw() + trajectory.Draw() txt = ROOT.TLatex() - txt.DrawLatexNDC(0.6, 0.8, 'event index:' + str(SHiPDisplay.n)) + txt.DrawLatexNDC(0.6, 0.8, "event index:" + str(SHiPDisplay.n)) c1.Update() diff --git a/macro/evd_nextEvent.py b/macro/evd_nextEvent.py index 414cf0d5dc..0df63d58d2 100644 --- a/macro/evd_nextEvent.py +++ b/macro/evd_nextEvent.py @@ -1,10 +1,15 @@ -import ROOT#,evd_fillEnergy -import eveGlobal +import eveGlobal +import ROOT # ,evd_fillEnergy + + def execute(): - lsOfGlobals = ROOT.gROOT.GetListOfGlobals() - SHiPDisplay = eveGlobal.SHiPDisplay - SHiPDisplay.NextEvent() - if ROOT.gROOT.FindObject('Root Canvas'): evd_fillEnergy.execute() - pass -if __name__=="__main__": - execute() + lsOfGlobals = ROOT.gROOT.GetListOfGlobals() + SHiPDisplay = eveGlobal.SHiPDisplay + SHiPDisplay.NextEvent() + if ROOT.gROOT.FindObject("Root Canvas"): + evd_fillEnergy.execute() + pass + + +if __name__ == "__main__": + execute() diff --git a/macro/evd_transparentMode.py b/macro/evd_transparentMode.py index 1572b2277c..088834c042 100644 --- a/macro/evd_transparentMode.py +++ b/macro/evd_transparentMode.py @@ -1,5 +1,8 @@ +import eveGlobal import ROOT -import eveGlobal + SHiPDisplay = eveGlobal.SHiPDisplay -if SHiPDisplay.TransparentMode == 0 : SHiPDisplay.transparentMode() -else: SHiPDisplay.transparentMode('off') +if SHiPDisplay.TransparentMode == 0: + SHiPDisplay.transparentMode() +else: + SHiPDisplay.transparentMode("off") diff --git a/macro/eventDisplay.py b/macro/eventDisplay.py index 6db5dc0a53..985ca92f11 100644 --- a/macro/eventDisplay.py +++ b/macro/eventDisplay.py @@ -1,20 +1,22 @@ #!/usr/bin/env python -i -import ROOT +import atexit import os import tkinter -import atexit + +import ROOT ROOT.gROOT.ProcessLine('#include "FairEventHeader.h"') # only helps if class version in FairEventHeader.h is increased from argparse import ArgumentParser -from ShipGeoConfig import ConfigRegistry -from rootpyPickler import Unpickler from array import array + +import shipDet_conf +import shipRoot_conf import shipunit as u from decorators import * -import shipRoot_conf -import shipDet_conf +from rootpyPickler import Unpickler +from ShipGeoConfig import ConfigRegistry shipRoot_conf.configure() diff --git a/macro/flux_map.py b/macro/flux_map.py index 1261d48681..abcc86dbdf 100755 --- a/macro/flux_map.py +++ b/macro/flux_map.py @@ -1,128 +1,289 @@ #!/usr/bin/env python3 import argparse + +import logger as log import numpy as np import ROOT as r -import shipunit as u import rootUtils as ut -import logger as log +import shipunit as u def main(): - parser = argparse.ArgumentParser(description='Script to create flux maps.') + parser = argparse.ArgumentParser(description="Script to create flux maps.") parser.add_argument( - 'inputfile', - help='''Simulation results to use as input. ''' - '''Supports retrieving files from EOS via the XRootD protocol.''') + "inputfile", + help="""Simulation results to use as input. """ + """Supports retrieving files from EOS via the XRootD protocol.""", + ) parser.add_argument( - '-o', - '--outputfile', - default='flux_map.root', - help='''File to write the flux maps to. ''' - '''Will be recreated if it already exists.''') + "-o", + "--outputfile", + default="flux_map.root", + help="""File to write the flux maps to. """ + """Will be recreated if it already exists.""", + ) args = parser.parse_args() - f = r.TFile.Open(args.outputfile, 'recreate') + f = r.TFile.Open(args.outputfile, "recreate") f.cd() - maxpt = 10. * u.GeV - maxp = 360. * u.GeV + maxpt = 10.0 * u.GeV + maxp = 360.0 * u.GeV h = {} # Define histograms for nplane in range(0, 23): - ut.bookHist(h, 'NuTauMu_all_{}'.format(nplane), - 'Rpc_{};x[cm];y[cm]'.format( - nplane), 100, -300, +300, 100, -300, - 300) - ut.bookHist(h, 'NuTauMu_mu_{}'.format(nplane), - 'Rpc_{};x[cm];y[cm]'.format( - nplane), 100, -300, +300, 100, -300, - 300) - for suffix, title in [('mu', '#mu#pm hits'), ('all', 'All hits')]: - ut.bookHist(h, 'muon_tiles_{}'.format(suffix), - '{};x[cm];y[cm]'.format(title), 200, -1000, +1000, 90, - -900, 900) - ut.bookHist(h, 'muon_bars_x_{}'.format(suffix), - '{};x[cm];y[cm]'.format(title), 2, -300, +300, 240, -600, - 600) - ut.bookHist(h, 'muon_bars_y_{}'.format(suffix), - '{};x[cm];y[cm]'.format(title), 120, -300, +300, 4, -600, - 600) - ut.bookHist(h, 'timing_{}'.format(suffix), - '{};x[cm];y[cm]'.format(title), 3, -252, +252, 167, -501, - 501) - ut.bookHist(h, 'TargetTracker_{}'.format(suffix), - '{};x[cm];y[cm]'.format(title), 120, -60, 60, 120, -60, - 60) - ut.bookHist(h, 'TargetTracker_yvsz_{}'.format(suffix), - '{};z[cm];y[cm]'.format( - title), 400, -3300, -2900, 120, -60, - 60) - ut.bookHist(h, 'TargetTracker_xvsz_{}'.format(suffix), - '{};z[cm];x[cm]'.format( - title), 400, -3300, -2900, 120, -60, - 60) - ut.bookHist(h, 'NuTauMu_{}'.format(suffix), - '{};x[cm];y[cm]'.format(title), 100, -300, +300, 100, -300, - 300) - ut.bookHist(h, 'NuTauMu_yvsz_{}'.format(suffix), - '{};z[cm];y[cm]'.format( - title), 200, -2680, -2480, 600, -300, - 300) - ut.bookHist(h, 'NuTauMu_xvsz_{}'.format(suffix), - '{};z[cm];x[cm]'.format( - title), 200, -2680, -2480, 600, -300, - 300) - ut.bookHist(h, 'ECAL_TP_{}'.format(suffix), - '{};x[cm];y[cm]'.format(title), 167, -501, +501, 334, - -1002, 1002) - ut.bookHist(h, 'ECAL_Alt_{}'.format(suffix), - '{};x[cm];y[cm]'.format(title), 50, -500, +500, 100, -1000, - 1000) - ut.bookHist(h, 'SBT_Liquid_{}'.format(suffix), - '{};z[cm];#phi'.format(title), 100, -3000, +3000, 100, - -r.TMath.Pi(), r.TMath.Pi()) - ut.bookHist(h, 'SBT_Plastic_{}'.format(suffix), - '{};z[cm];#phi'.format(title), 100, -3000, +3000, 100, - -r.TMath.Pi(), r.TMath.Pi()) + ut.bookHist( + h, + "NuTauMu_all_{}".format(nplane), + "Rpc_{};x[cm];y[cm]".format(nplane), + 100, + -300, + +300, + 100, + -300, + 300, + ) + ut.bookHist( + h, + "NuTauMu_mu_{}".format(nplane), + "Rpc_{};x[cm];y[cm]".format(nplane), + 100, + -300, + +300, + 100, + -300, + 300, + ) + for suffix, title in [("mu", "#mu#pm hits"), ("all", "All hits")]: + ut.bookHist( + h, + "muon_tiles_{}".format(suffix), + "{};x[cm];y[cm]".format(title), + 200, + -1000, + +1000, + 90, + -900, + 900, + ) + ut.bookHist( + h, + "muon_bars_x_{}".format(suffix), + "{};x[cm];y[cm]".format(title), + 2, + -300, + +300, + 240, + -600, + 600, + ) + ut.bookHist( + h, + "muon_bars_y_{}".format(suffix), + "{};x[cm];y[cm]".format(title), + 120, + -300, + +300, + 4, + -600, + 600, + ) + ut.bookHist( + h, + "timing_{}".format(suffix), + "{};x[cm];y[cm]".format(title), + 3, + -252, + +252, + 167, + -501, + 501, + ) + ut.bookHist( + h, + "TargetTracker_{}".format(suffix), + "{};x[cm];y[cm]".format(title), + 120, + -60, + 60, + 120, + -60, + 60, + ) + ut.bookHist( + h, + "TargetTracker_yvsz_{}".format(suffix), + "{};z[cm];y[cm]".format(title), + 400, + -3300, + -2900, + 120, + -60, + 60, + ) + ut.bookHist( + h, + "TargetTracker_xvsz_{}".format(suffix), + "{};z[cm];x[cm]".format(title), + 400, + -3300, + -2900, + 120, + -60, + 60, + ) + ut.bookHist( + h, + "NuTauMu_{}".format(suffix), + "{};x[cm];y[cm]".format(title), + 100, + -300, + +300, + 100, + -300, + 300, + ) + ut.bookHist( + h, + "NuTauMu_yvsz_{}".format(suffix), + "{};z[cm];y[cm]".format(title), + 200, + -2680, + -2480, + 600, + -300, + 300, + ) + ut.bookHist( + h, + "NuTauMu_xvsz_{}".format(suffix), + "{};z[cm];x[cm]".format(title), + 200, + -2680, + -2480, + 600, + -300, + 300, + ) + ut.bookHist( + h, + "ECAL_TP_{}".format(suffix), + "{};x[cm];y[cm]".format(title), + 167, + -501, + +501, + 334, + -1002, + 1002, + ) + ut.bookHist( + h, + "ECAL_Alt_{}".format(suffix), + "{};x[cm];y[cm]".format(title), + 50, + -500, + +500, + 100, + -1000, + 1000, + ) + ut.bookHist( + h, + "SBT_Liquid_{}".format(suffix), + "{};z[cm];#phi".format(title), + 100, + -3000, + +3000, + 100, + -r.TMath.Pi(), + r.TMath.Pi(), + ) + ut.bookHist( + h, + "SBT_Plastic_{}".format(suffix), + "{};z[cm];#phi".format(title), + 100, + -3000, + +3000, + 100, + -r.TMath.Pi(), + r.TMath.Pi(), + ) for station in range(1, 5): - ut.bookHist(h, 'T{}_{}'.format(station, suffix), - '{};x[cm];y[cm]'.format(title), 10, -250, +250, 20, - -500, 500) + ut.bookHist( + h, + "T{}_{}".format(station, suffix), + "{};x[cm];y[cm]".format(title), + 10, + -250, + +250, + 20, + -500, + 500, + ) - ut.bookHist(h, 'NuTauMu_mu_p', '#mu#pm;p[GeV];', 100, 0, maxp) - ut.bookHist(h, 'NuTauMu_mu_pt', '#mu#pm;p_t[GeV];', 100, 0, - maxpt) - ut.bookHist(h, 'NuTauMu_mu_ppt', '#mu#pm;p[GeV];p_t[GeV];', - 100, 0, maxp, 100, 0, maxpt) - ut.bookHist(h, 'NuTauMu_all_p', '#mu#pm;p[GeV];', 100, 0, maxp) - ut.bookHist(h, 'NuTauMu_all_pt', '#mu#pm;p_t[GeV];', 100, 0, - maxpt) - ut.bookHist(h, 'NuTauMu_all_ppt', '#mu#pm;p[GeV];p_t[GeV];', - 100, 0, maxp, 100, 0, maxpt) + ut.bookHist(h, "NuTauMu_mu_p", "#mu#pm;p[GeV];", 100, 0, maxp) + ut.bookHist(h, "NuTauMu_mu_pt", "#mu#pm;p_t[GeV];", 100, 0, maxpt) + ut.bookHist( + h, "NuTauMu_mu_ppt", "#mu#pm;p[GeV];p_t[GeV];", 100, 0, maxp, 100, 0, maxpt + ) + ut.bookHist(h, "NuTauMu_all_p", "#mu#pm;p[GeV];", 100, 0, maxp) + ut.bookHist(h, "NuTauMu_all_pt", "#mu#pm;p_t[GeV];", 100, 0, maxpt) + ut.bookHist( + h, "NuTauMu_all_ppt", "#mu#pm;p[GeV];p_t[GeV];", 100, 0, maxp, 100, 0, maxpt + ) - for suffix in ['', '_original']: - ut.bookHist(h, 'mu_p{}'.format(suffix), '#mu#pm;p[GeV];', 100, 0, maxp) - ut.bookHist(h, 'mu_pt{}'.format(suffix), '#mu#pm;p_t[GeV];', 100, 0, - maxpt) - ut.bookHist(h, 'mu_ppt{}'.format(suffix), '#mu#pm;p[GeV];p_t[GeV];', - 100, 0, maxp, 100, 0, maxpt) - ut.bookHist(h, 'ECAL_TP_e', 'e#pm with E#geq 250 MeV;x[cm];y[cm]', 167, - -501, +501, 334, -1002, 1002) - ut.bookHist(h, 'ECAL_Alt_e', 'e#pm with E#geq 250 MeV;x[cm];y[cm]', 50, - -500, +500, 100, -1000, 1000) - ut.bookHist(h, 'ECAL_TP_gamma', '#gamma;x[cm];y[cm]', 167, -501, +501, 334, - -1002, 1002) - ut.bookHist(h, 'ECAL_Alt_gamma', '#gamma;x[cm];y[cm]', 50, -500, +500, 100, - -1000, 1000) - ut.bookHist(h, 'ECAL_e_E', 'e#pm;E[GeV/c^{2}];', 100, 0, 1) - ut.bookHist(h, 'ECAL_gamma_E', '#gamma;E[GeV/c^{2}];', 100, 0, 1) - ch = r.TChain('cbmsim') + for suffix in ["", "_original"]: + ut.bookHist(h, "mu_p{}".format(suffix), "#mu#pm;p[GeV];", 100, 0, maxp) + ut.bookHist(h, "mu_pt{}".format(suffix), "#mu#pm;p_t[GeV];", 100, 0, maxpt) + ut.bookHist( + h, + "mu_ppt{}".format(suffix), + "#mu#pm;p[GeV];p_t[GeV];", + 100, + 0, + maxp, + 100, + 0, + maxpt, + ) + ut.bookHist( + h, + "ECAL_TP_e", + "e#pm with E#geq 250 MeV;x[cm];y[cm]", + 167, + -501, + +501, + 334, + -1002, + 1002, + ) + ut.bookHist( + h, + "ECAL_Alt_e", + "e#pm with E#geq 250 MeV;x[cm];y[cm]", + 50, + -500, + +500, + 100, + -1000, + 1000, + ) + ut.bookHist( + h, "ECAL_TP_gamma", "#gamma;x[cm];y[cm]", 167, -501, +501, 334, -1002, 1002 + ) + ut.bookHist( + h, "ECAL_Alt_gamma", "#gamma;x[cm];y[cm]", 50, -500, +500, 100, -1000, 1000 + ) + ut.bookHist(h, "ECAL_e_E", "e#pm;E[GeV/c^{2}];", 100, 0, 1) + ut.bookHist(h, "ECAL_gamma_E", "#gamma;E[GeV/c^{2}];", 100, 0, 1) + ch = r.TChain("cbmsim") ch.Add(args.inputfile) n = ch.GetEntries() log.info(n) i = 0 for event in ch: if i % 10000 == 0: - log.info('{}/{}'.format(i, n)) + log.info("{}/{}".format(i, n)) i += 1 muon = False for hit in event.strawtubesPoint: @@ -144,14 +305,14 @@ def main(): assert pid not in [12, -12, 14, -14, 16, -16] detector_ID = hit.GetDetectorID() station = detector_ID // 10000000 - h['T{}_all'.format(station)].Fill(x, y, weight) + h["T{}_all".format(station)].Fill(x, y, weight) if abs(pid) == 13: muon = True muonid = trid - h['T{}_mu'.format(station)].Fill(x, y, weight) - h['mu_p'].Fill(P, weight) - h['mu_pt'].Fill(pt, weight) - h['mu_ppt'].Fill(P, pt, weight) + h["T{}_mu".format(station)].Fill(x, y, weight) + h["mu_p"].Fill(P, weight) + h["mu_pt"].Fill(pt, weight) + h["mu_ppt"].Fill(P, pt, weight) for hit in event.EcalPoint: if hit: if not hit.GetEnergyLoss() > 0: @@ -169,26 +330,26 @@ def main(): pid = hit.PdgCode() if pid in [12, -12, 14, -14, 16, -16]: continue - h['ECAL_TP_all'].Fill(x, y, weight) - h['ECAL_Alt_all'].Fill(x, y, weight) + h["ECAL_TP_all"].Fill(x, y, weight) + h["ECAL_Alt_all"].Fill(x, y, weight) if abs(pid) == 13: muon = True muonid = trid - h['mu_p'].Fill(P, weight) - h['mu_pt'].Fill(pt, weight) - h['mu_ppt'].Fill(P, pt, weight) - h['ECAL_TP_mu'].Fill(x, y, weight) - h['ECAL_Alt_mu'].Fill(x, y, weight) + h["mu_p"].Fill(P, weight) + h["mu_pt"].Fill(pt, weight) + h["mu_ppt"].Fill(P, pt, weight) + h["ECAL_TP_mu"].Fill(x, y, weight) + h["ECAL_Alt_mu"].Fill(x, y, weight) elif abs(pid) == 11: - Esq = px ** 2 + py ** 2 + pz ** 2 + 0.000511 ** 2 - h['ECAL_e_E'].Fill(np.sqrt(Esq), weight) - h['ECAL_TP_e'].Fill(x, y, weight) - h['ECAL_Alt_e'].Fill(x, y, weight) + Esq = px**2 + py**2 + pz**2 + 0.000511**2 + h["ECAL_e_E"].Fill(np.sqrt(Esq), weight) + h["ECAL_TP_e"].Fill(x, y, weight) + h["ECAL_Alt_e"].Fill(x, y, weight) elif abs(pid) == 22: - Esq = px ** 2 + py ** 2 + pz ** 2 - h['ECAL_gamma_E'].Fill(np.sqrt(Esq), weight) - h['ECAL_TP_gamma'].Fill(x, y, weight) - h['ECAL_Alt_gamma'].Fill(x, y, weight) + Esq = px**2 + py**2 + pz**2 + h["ECAL_gamma_E"].Fill(np.sqrt(Esq), weight) + h["ECAL_TP_gamma"].Fill(x, y, weight) + h["ECAL_Alt_gamma"].Fill(x, y, weight) for hit in event.TTPoint: if hit: if not hit.GetEnergyLoss() > 0: @@ -208,19 +369,19 @@ def main(): pid = hit.PdgCode() assert pid not in [12, -12, 14, -14, 16, -16] if detID == 0: - h['TargetTracker_all'].Fill(x, y, weight) - h['TargetTracker_xvsz_all'].Fill(z, x, weight) - h['TargetTracker_yvsz_all'].Fill(z, y, weight) + h["TargetTracker_all"].Fill(x, y, weight) + h["TargetTracker_xvsz_all"].Fill(z, x, weight) + h["TargetTracker_yvsz_all"].Fill(z, y, weight) if abs(pid) == 13: muon = True muonid = trid - h['mu_p'].Fill(P, weight) - h['mu_pt'].Fill(pt, weight) - h['mu_ppt'].Fill(P, pt, weight) + h["mu_p"].Fill(P, weight) + h["mu_pt"].Fill(pt, weight) + h["mu_ppt"].Fill(P, pt, weight) if detID == 0: - h['TargetTracker_mu'].Fill(x, y, weight) - h['TargetTracker_xvsz_mu'].Fill(z, x, weight) - h['TargetTracker_yvsz_mu'].Fill(z, y, weight) + h["TargetTracker_mu"].Fill(x, y, weight) + h["TargetTracker_xvsz_mu"].Fill(z, x, weight) + h["TargetTracker_yvsz_mu"].Fill(z, y, weight) for hit in event.ShipRpcPoint: if hit: if not hit.GetEnergyLoss() > 0: @@ -240,31 +401,31 @@ def main(): P = np.hypot(pz, pt) pid = hit.PdgCode() assert pid not in [12, -12, 14, -14, 16, -16] - h['NuTauMu_all'].Fill(x, y, weight) + h["NuTauMu_all"].Fill(x, y, weight) if nplane >= 0: - h['NuTauMu_all_{}'.format(nplane)].Fill(x, y, weight) - h['NuTauMu_xvsz_all'].Fill(z, x, weight) - h['NuTauMu_yvsz_all'].Fill(z, y, weight) + h["NuTauMu_all_{}".format(nplane)].Fill(x, y, weight) + h["NuTauMu_xvsz_all"].Fill(z, x, weight) + h["NuTauMu_yvsz_all"].Fill(z, y, weight) if detID == 10000: - h['NuTauMu_all_p'].Fill(P, weight) - h['NuTauMu_all_pt'].Fill(pt, weight) - h['NuTauMu_all_ppt'].Fill(P, pt, weight) + h["NuTauMu_all_p"].Fill(P, weight) + h["NuTauMu_all_pt"].Fill(pt, weight) + h["NuTauMu_all_ppt"].Fill(P, pt, weight) if abs(pid) == 13: muon = True muonid = trid - h['mu_p'].Fill(P, weight) - h['mu_pt'].Fill(pt, weight) - h['mu_ppt'].Fill(P, pt, weight) - h['NuTauMu_mu'].Fill(x, y, weight) + h["mu_p"].Fill(P, weight) + h["mu_pt"].Fill(pt, weight) + h["mu_ppt"].Fill(P, pt, weight) + h["NuTauMu_mu"].Fill(x, y, weight) if nplane >= 0: # fill the histogram corresponding to nplane - h['NuTauMu_mu_{}'.format(nplane)].Fill(x, y, weight) + h["NuTauMu_mu_{}".format(nplane)].Fill(x, y, weight) if detID == 10000: - h['NuTauMu_mu_p'].Fill(P, weight) - h['NuTauMu_mu_pt'].Fill(pt, weight) - h['NuTauMu_mu_ppt'].Fill(P, pt, weight) - h['NuTauMu_xvsz_mu'].Fill(z, x, weight) - h['NuTauMu_yvsz_mu'].Fill(z, y, weight) + h["NuTauMu_mu_p"].Fill(P, weight) + h["NuTauMu_mu_pt"].Fill(pt, weight) + h["NuTauMu_mu_ppt"].Fill(P, pt, weight) + h["NuTauMu_xvsz_mu"].Fill(z, x, weight) + h["NuTauMu_yvsz_mu"].Fill(z, y, weight) for hit in event.TimeDetPoint: if hit: if not hit.GetEnergyLoss() > 0: @@ -282,14 +443,14 @@ def main(): P = np.hypot(pz, pt) pid = hit.PdgCode() assert pid not in [12, -12, 14, -14, 16, -16] - h['timing_all'].Fill(x, y, weight) + h["timing_all"].Fill(x, y, weight) if abs(pid) == 13: muon = True muonid = trid - h['mu_p'].Fill(P, weight) - h['mu_pt'].Fill(pt, weight) - h['mu_ppt'].Fill(P, pt, weight) - h['timing_mu'].Fill(x, y, weight) + h["mu_p"].Fill(P, weight) + h["mu_pt"].Fill(pt, weight) + h["mu_ppt"].Fill(P, pt, weight) + h["timing_mu"].Fill(x, y, weight) for hit in event.muonPoint: if hit: if not hit.GetEnergyLoss() > 0: @@ -306,18 +467,18 @@ def main(): P = np.hypot(pz, pt) pid = hit.PdgCode() assert pid not in [12, -12, 14, -14, 16, -16] - h['muon_tiles_all'].Fill(x, y, weight) - h['muon_bars_x_all'].Fill(x, y, weight) - h['muon_bars_y_all'].Fill(x, y, weight) + h["muon_tiles_all"].Fill(x, y, weight) + h["muon_bars_x_all"].Fill(x, y, weight) + h["muon_bars_y_all"].Fill(x, y, weight) if abs(pid) == 13: muon = True muonid = trid - h['mu_p'].Fill(P, weight) - h['mu_pt'].Fill(pt, weight) - h['mu_ppt'].Fill(P, pt, weight) - h['muon_tiles_mu'].Fill(x, y, weight) - h['muon_bars_y_mu'].Fill(x, y, weight) - h['muon_bars_x_mu'].Fill(x, y, weight) + h["mu_p"].Fill(P, weight) + h["mu_pt"].Fill(pt, weight) + h["mu_ppt"].Fill(P, pt, weight) + h["muon_tiles_mu"].Fill(x, y, weight) + h["muon_bars_y_mu"].Fill(x, y, weight) + h["muon_bars_x_mu"].Fill(x, y, weight) for hit in event.vetoPoint: if hit: if not hit.GetEnergyLoss() > 0: @@ -338,44 +499,45 @@ def main(): assert pid not in [12, -12, 14, -14, 16, -16] phi = r.TMath.ATan2(y, x) if 99999 < detector_ID < 999999: - h['SBT_Liquid_all'].Fill(z, phi, weight) + h["SBT_Liquid_all"].Fill(z, phi, weight) if abs(pid) == 13: muon = True muonid = trid - h['mu_p'].Fill(P, weight) - h['mu_pt'].Fill(pt, weight) - h['mu_ppt'].Fill(P, pt, weight) - h['SBT_Liquid_mu'].Fill(z, phi, weight) + h["mu_p"].Fill(P, weight) + h["mu_pt"].Fill(pt, weight) + h["mu_ppt"].Fill(P, pt, weight) + h["SBT_Liquid_mu"].Fill(z, phi, weight) continue elif detector_ID > 999999: - h['SBT_Plastic_all'].Fill(z, phi, weight) + h["SBT_Plastic_all"].Fill(z, phi, weight) if abs(pid) == 13: muon = True muonid = trid - h['mu_p'].Fill(P, weight) - h['mu_pt'].Fill(pt, weight) - h['mu_ppt'].Fill(P, pt, weight) - h['SBT_Plastic_mu'].Fill(z, phi, weight) + h["mu_p"].Fill(P, weight) + h["mu_pt"].Fill(pt, weight) + h["mu_ppt"].Fill(P, pt, weight) + h["SBT_Plastic_mu"].Fill(z, phi, weight) continue - log.warn('Unidentified vetoPoint.') + log.warn("Unidentified vetoPoint.") if muon: original_muon = event.MCTrack[muonid] weight = original_muon.GetWeight() - h['mu_p_original'].Fill(original_muon.GetP(), weight) - h['mu_pt_original'].Fill(original_muon.GetPt(), weight) - h['mu_ppt_original'].Fill(original_muon.GetP(), - original_muon.GetPt(), weight) + h["mu_p_original"].Fill(original_muon.GetP(), weight) + h["mu_pt_original"].Fill(original_muon.GetPt(), weight) + h["mu_ppt_original"].Fill( + original_muon.GetP(), original_muon.GetPt(), weight + ) # NOTE: muons are counted several times if they create several hits # But the original muon is only counted once. - log.info('Event loop done') + log.info("Event loop done") for key in h: classname = h[key].Class().GetName() - if 'TH' in classname or 'TP' in classname: + if "TH" in classname or "TP" in classname: h[key].Write() f.Close() -if __name__ == '__main__': +if __name__ == "__main__": r.gErrorIgnoreLevel = r.kWarning r.gROOT.SetBatch(True) main() diff --git a/macro/getGeoInformation.py b/macro/getGeoInformation.py index 35e288e549..f2e33f9394 100644 --- a/macro/getGeoInformation.py +++ b/macro/getGeoInformation.py @@ -1,116 +1,149 @@ #!/usr/bin/env python -#prints z-coordinators of SHiP detector volumes -#WARNING: printing the entire geometry takes a lot of time -#24-02-2015 comments to EvH +# prints z-coordinators of SHiP detector volumes +# WARNING: printing the entire geometry takes a lot of time +# 24-02-2015 comments to EvH import operator +import os from argparse import ArgumentParser from array import array -import os,ROOT + +import ROOT + def local2Global(n): - Info={} + Info = {} nav = ROOT.gGeoManager.GetCurrentNavigator() nav.cd(n) - Info['node'] = nav.GetCurrentNode() - Info['path'] = n - tmp = Info['node'].GetVolume().GetShape() - Info['material'] = Info['node'].GetVolume().GetMaterial().GetName() + Info["node"] = nav.GetCurrentNode() + Info["path"] = n + tmp = Info["node"].GetVolume().GetShape() + Info["material"] = Info["node"].GetVolume().GetMaterial().GetName() if options.moreInfo: - x = ROOT.gGeoManager.GetVerboseLevel() - ROOT.gGeoManager.SetVerboseLevel(0) - Info['weight']=Info['node'].GetVolume().Weight() # kg - Info['cubicmeter']=Info['node'].GetVolume().Capacity()/1000000. # - ROOT.gGeoManager.SetVerboseLevel(x) - o = [tmp.GetOrigin()[0],tmp.GetOrigin()[1],tmp.GetOrigin()[2]] - Info['locorign'] = o - local = array('d',o) - globOrigin = array('d',[0,0,0]) - nav.LocalToMaster(local,globOrigin) - Info['origin'] = globOrigin - shifts = [ [-tmp.GetDX()+o[0],o[1],o[2]], - [tmp.GetDX()+o[0],o[1],o[2]], - [o[0],-tmp.GetDY()+o[1],o[2]], - [o[0],tmp.GetDY()+o[1],o[2]], - [o[0],o[1],-tmp.GetDZ()+o[2]],[o[0],o[1],tmp.GetDZ()+o[2]] - ] + x = ROOT.gGeoManager.GetVerboseLevel() + ROOT.gGeoManager.SetVerboseLevel(0) + Info["weight"] = Info["node"].GetVolume().Weight() # kg + Info["cubicmeter"] = Info["node"].GetVolume().Capacity() / 1000000.0 # + ROOT.gGeoManager.SetVerboseLevel(x) + o = [tmp.GetOrigin()[0], tmp.GetOrigin()[1], tmp.GetOrigin()[2]] + Info["locorign"] = o + local = array("d", o) + globOrigin = array("d", [0, 0, 0]) + nav.LocalToMaster(local, globOrigin) + Info["origin"] = globOrigin + shifts = [ + [-tmp.GetDX() + o[0], o[1], o[2]], + [tmp.GetDX() + o[0], o[1], o[2]], + [o[0], -tmp.GetDY() + o[1], o[2]], + [o[0], tmp.GetDY() + o[1], o[2]], + [o[0], o[1], -tmp.GetDZ() + o[2]], + [o[0], o[1], tmp.GetDZ() + o[2]], + ] shifted = [] for s in shifts: - local = array('d',s) - glob = array('d',[0,0,0]) - nav.LocalToMaster(local,glob) - shifted.append([glob[0],glob[1],glob[2]]) - Info['boundingbox']={} + local = array("d", s) + glob = array("d", [0, 0, 0]) + nav.LocalToMaster(local, glob) + shifted.append([glob[0], glob[1], glob[2]]) + Info["boundingbox"] = {} for j in range(3): - jmin = 1E30 - jmax = -1E30 - for s in shifted: - if s[j]jmax: jmax = s[j] - Info['boundingbox'][j]=[jmin,jmax] + jmin = 1e30 + jmax = -1e30 + for s in shifted: + if s[j] < jmin: + jmin = s[j] + if s[j] > jmax: + jmax = s[j] + Info["boundingbox"][j] = [jmin, jmax] return Info -def print_info(path, node, level, currentlevel, print_sub_det_info=False): - sub_nodes = {} - fullInfo = {} - for subnode in node.GetNodes(): - name = subnode.GetName() - fullInfo[name] = local2Global(path + '/' + name) - sub_nodes[name] = fullInfo[name]['origin'][2] - - for name, _ in sorted(list(sub_nodes.items()), key=operator.itemgetter(1)): - boundingbox = fullInfo[name]['boundingbox'] - - format_string = "{:<28s}: z={:10.4F}cm dZ={:10.4F}cm [{:10.4F} {:10.4F}]"+\ - " dx={:10.4F}cm [{:10.4F} {:10.4F}] dy={:10.4F}cm [{:10.4F} {:10.4F}] {:>20s}" - - format_variable = [" " * int(currentlevel) + name, fullInfo[name]['origin'][2], - abs(boundingbox[2][0]-boundingbox[2][1])/2., boundingbox[2][0],boundingbox[2][1], - abs(boundingbox[0][0]-boundingbox[0][1])/2., boundingbox[0][0],boundingbox[0][1], - abs(boundingbox[1][0]-boundingbox[1][1])/2., boundingbox[1][0],boundingbox[1][1], - fullInfo[name]['material']] - if options.moreInfo: - cubicmeter = fullInfo[name]['cubicmeter'] - weight = fullInfo[name]['weight'] - format_string += " {:10.1F}kg {:10.1F}m3" - format_variable.extend([weight, cubicmeter]) - - print (format_string.format(*format_variable)) - - if options.volume in ["", name]: - print_sub_det_info = True - - if print_sub_det_info and currentlevel < level and fullInfo[name]['node'].GetNodes(): - print_info(fullInfo[name]['path'], fullInfo[name]['node'], level, currentlevel + 1, - print_sub_det_info) - - if currentlevel == 0: - print_sub_det_info = False +def print_info(path, node, level, currentlevel, print_sub_det_info=False): + sub_nodes = {} + fullInfo = {} + for subnode in node.GetNodes(): + name = subnode.GetName() + fullInfo[name] = local2Global(path + "/" + name) + sub_nodes[name] = fullInfo[name]["origin"][2] + + for name, _ in sorted(list(sub_nodes.items()), key=operator.itemgetter(1)): + boundingbox = fullInfo[name]["boundingbox"] + + format_string = ( + "{:<28s}: z={:10.4F}cm dZ={:10.4F}cm [{:10.4F} {:10.4F}]" + + " dx={:10.4F}cm [{:10.4F} {:10.4F}] dy={:10.4F}cm [{:10.4F} {:10.4F}] {:>20s}" + ) + + format_variable = [ + " " * int(currentlevel) + name, + fullInfo[name]["origin"][2], + abs(boundingbox[2][0] - boundingbox[2][1]) / 2.0, + boundingbox[2][0], + boundingbox[2][1], + abs(boundingbox[0][0] - boundingbox[0][1]) / 2.0, + boundingbox[0][0], + boundingbox[0][1], + abs(boundingbox[1][0] - boundingbox[1][1]) / 2.0, + boundingbox[1][0], + boundingbox[1][1], + fullInfo[name]["material"], + ] + + if options.moreInfo: + cubicmeter = fullInfo[name]["cubicmeter"] + weight = fullInfo[name]["weight"] + format_string += " {:10.1F}kg {:10.1F}m3" + format_variable.extend([weight, cubicmeter]) + + print(format_string.format(*format_variable)) + + if options.volume in ["", name]: + print_sub_det_info = True + + if ( + print_sub_det_info + and currentlevel < level + and fullInfo[name]["node"].GetNodes() + ): + print_info( + fullInfo[name]["path"], + fullInfo[name]["node"], + level, + currentlevel + 1, + print_sub_det_info, + ) + + if currentlevel == 0: + print_sub_det_info = False parser = ArgumentParser() -parser.add_argument("-g", "--geometry", help="Input geometry file", - required=True) +parser.add_argument("-g", "--geometry", help="Input geometry file", required=True) parser.add_argument("-l", "--level", help="Max subnode level", default=0) parser.add_argument("-v", "--volume", help="Name of node to expand", default="") -parser.add_argument("-X", "--moreInfo", help="Print weight and capacity", action="store_true") +parser.add_argument( + "-X", "--moreInfo", help="Print weight and capacity", action="store_true" +) options = parser.parse_args() fname = options.geometry -if fname.startswith('/eos/'): - fname = os.environ['EOSSHIP'] + fname +if fname.startswith("/eos/"): + fname = os.environ["EOSSHIP"] + fname fgeom = ROOT.TFile.Open(fname) fGeo = fgeom.FAIRGeom top = fGeo.GetTopVolume() if options.moreInfo: - print (" Detector element z(midpoint) halflength volume-start volume-end dx"\ - " x-start x-end dy y-start y-end material weight capacity") + print( + " Detector element z(midpoint) halflength volume-start volume-end dx" + " x-start x-end dy y-start y-end material weight capacity" + ) else: - print (" Detector element z(midpoint) halflength volume-start volume-end dx"\ - " x-start x-end dy y-start y-end material") + print( + " Detector element z(midpoint) halflength volume-start volume-end dx" + " x-start x-end dy y-start y-end material" + ) currentlevel = 0 print_info("", top, int(options.level), currentlevel) diff --git a/macro/getInteractionAndRadiationLength.py b/macro/getInteractionAndRadiationLength.py index 5b81a77495..48e065e20a 100644 --- a/macro/getInteractionAndRadiationLength.py +++ b/macro/getInteractionAndRadiationLength.py @@ -4,9 +4,9 @@ # python $FAIRSHIP/macro/getGeoInformation.py -g geofile_full.conical.Genie-TGeant4.root # python -i $FAIRSHIP/macro/run_simScript.py --Genie -f /eos/experiment/ship/data/GenieEvents/genie-nu_mu.root -start=array('d',[0,0,3666.5]) -end=array('d',[0,0,3898.700]) -mparam=array('d',[0,0,0,0,0,0,0,0,0,0,0,0]) +start = array("d", [0, 0, 3666.5]) +end = array("d", [0, 0, 3898.700]) +mparam = array("d", [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) Geniegen.MeanMaterialBudget(start, end, mparam) print(mparam[8], " equivalent interaction length fraction") diff --git a/macro/inspectGeant4Geo.py b/macro/inspectGeant4Geo.py index f6b15172fc..030088bc76 100644 --- a/macro/inspectGeant4Geo.py +++ b/macro/inspectGeant4Geo.py @@ -1,25 +1,29 @@ import sys + import ROOT -from rootpyPickler import Unpickler import shipRoot_conf +from rootpyPickler import Unpickler + shipRoot_conf.configure() -fname = 'geofile_full.10.0.Pythia8-TGeant4.root' +fname = "geofile_full.10.0.Pythia8-TGeant4.root" if len(sys.argv) > 1: fname = sys.argv[1] fgeo = ROOT.TFile(fname) sGeo = fgeo.FAIRGeom import shipDet_conf + run = ROOT.FairRunSim() upkl = Unpickler(fgeo) -ShipGeo = upkl.load('ShipGeo') +ShipGeo = upkl.load("ShipGeo") modules = shipDet_conf.configure(run, ShipGeo) -run.SetUserConfig('g4Config.C') -run.SetName('TGeant4') -run.SetOutputFile(ROOT.TMemFile('output', 'recreate')) +run.SetUserConfig("g4Config.C") +run.SetName("TGeant4") +run.SetOutputFile(ROOT.TMemFile("output", "recreate")) run.Init() run.Run(0) import geomGeant4 + geomGeant4.printVMCFields() geomGeant4.printWeightsandFields() diff --git a/macro/makeCascade.py b/macro/makeCascade.py index 0273cae9b9..36df5fd137 100644 --- a/macro/makeCascade.py +++ b/macro/makeCascade.py @@ -1,401 +1,560 @@ -import ROOT,time,os,sys,random,getopt,copy +import copy +import getopt +import os +import random +import sys +import time from array import array + +import ROOT import rootUtils as ut + ROOT.gROOT.LoadMacro("$VMCWORKDIR/gconfig/basiclibs.C") ROOT.basiclibs() timer = ROOT.TStopwatch() timer.Start() -R = '' -#generate ccbar (msel=4) or bbbar(msel=5) -mselcb=4 -pbeamh=400. +R = "" +# generate ccbar (msel=4) or bbbar(msel=5) +mselcb = 4 +pbeamh = 400.0 storePrimaries = False -nevgen=100000 -Fntuple='Cascade100k-parp16-MSTP82-1-MSEL'+str(mselcb)+'-ntuple.root' +nevgen = 100000 +Fntuple = "Cascade100k-parp16-MSTP82-1-MSEL" + str(mselcb) + "-ntuple.root" print("usage: python $FAIRSHIP/macro/makeCascade.py -n (20000) -msel (4) -E (400)") try: - opts, args = getopt.getopt(sys.argv[1:], "s:t:H:n:E:m:P",[\ - "msel=","seed=","beam="]) + opts, args = getopt.getopt( + sys.argv[1:], "s:t:H:n:E:m:P", ["msel=", "seed=", "beam="] + ) except getopt.GetoptError: - # print help information and exit: - print(' enter -n: number of events to produce, default 20000') - print(' -m --msel=4 (5): charm (beauty) production, default charm') - print(' -E --beam=: energy of beam, default 400 GeV') - print(' -t: name of ntuple output file, default: Cascade20k-parp16-MSTP82-1-MSEL"+msel+"-ntuple.root') - print(' -s --seed: random number seed, integer, if not given, current time will be used.') - print(' -P : store all particles produced together with charm') - sys.exit() + # print help information and exit: + print(" enter -n: number of events to produce, default 20000") + print(" -m --msel=4 (5): charm (beauty) production, default charm") + print(" -E --beam=: energy of beam, default 400 GeV") + print( + ' -t: name of ntuple output file, default: Cascade20k-parp16-MSTP82-1-MSEL"+msel+"-ntuple.root' + ) + print( + " -s --seed: random number seed, integer, if not given, current time will be used." + ) + print(" -P : store all particles produced together with charm") + sys.exit() for o, a in opts: - if o in ("-n",): - nevgen = int(a) - if o in ("-E","--beam"): - pbeamh = float(a) - if o in ("-m","--msel"): - mselcb = int(a) - if o in ("-t",): - Fntuple = a - if o in ("-s","--seed"): - R = int(a) - if o in ("-P",): - storePrimaries = True -print('Generate ',nevgen,' p.o.t. with msel=',mselcb,' proton beam ',pbeamh,'GeV') -print('Output ntuples written to: ',Fntuple) - - -#some parameters for generating the chi (sigma(signal)/sigma(total) as a function of momentum + if o in ("-n",): + nevgen = int(a) + if o in ("-E", "--beam"): + pbeamh = float(a) + if o in ("-m", "--msel"): + mselcb = int(a) + if o in ("-t",): + Fntuple = a + if o in ("-s", "--seed"): + R = int(a) + if o in ("-P",): + storePrimaries = True +print("Generate ", nevgen, " p.o.t. with msel=", mselcb, " proton beam ", pbeamh, "GeV") +print("Output ntuples written to: ", Fntuple) + + +# some parameters for generating the chi (sigma(signal)/sigma(total) as a function of momentum # event/momentum, and number of momentum points taken to calculate sig/sigtot -nev=5000 -nrpoints=20 +nev = 5000 +nrpoints = 20 # cascade beam particles, anti-particles are generated automatically if they exist. -idbeam=[2212,211,2112,321,130,310] -target=['p+','n0'] -print('Chi generation with ',nev,' events/point, nr points=',nrpoints) -print('Cascade beam particle: ',idbeam) +idbeam = [2212, 211, 2112, 321, 130, 310] +target = ["p+", "n0"] +print("Chi generation with ", nev, " events/point, nr points=", nrpoints) +print("Cascade beam particle: ", idbeam) # Assume Molybdum target, fracp is the fraction of protons in nucleus, i.e. 42/98. # Used to average chi on p and n target in Pythia. -fracp=0.43 +fracp = 0.43 # -print('Target particles: ',target,' fraction of protons in Mo=',fracp) +print("Target particles: ", target, " fraction of protons in Mo=", fracp) # lower/upper momentum limit for beam, depends on msel.. # signal particles wanted (and their antis), which could decay semi-leptonically. -if mselcb==4: - pbeaml=34. - idsig=[411, 421, 431,4122,4132,4232,4332,4412,4414,4422,4424,4432,4434,4444] -elif mselcb==5: - pbeaml=130. - idsig=[511, 521, 531, 541,5122,5132,5142,5232,5242,5332,5342,5412,5414,5422,5424,5432,5434,5442,5444,5512,5514,5522,5524,5532,5534,5542,5544,5554] +if mselcb == 4: + pbeaml = 34.0 + idsig = [ + 411, + 421, + 431, + 4122, + 4132, + 4232, + 4332, + 4412, + 4414, + 4422, + 4424, + 4432, + 4434, + 4444, + ] +elif mselcb == 5: + pbeaml = 130.0 + idsig = [ + 511, + 521, + 531, + 541, + 5122, + 5132, + 5142, + 5232, + 5242, + 5332, + 5342, + 5412, + 5414, + 5422, + 5424, + 5432, + 5434, + 5442, + 5444, + 5512, + 5514, + 5522, + 5524, + 5532, + 5534, + 5542, + 5544, + 5554, + ] else: - print('Error: msel is unknown',mselcb,' STOP program') - sys.exit('ERROR on input, exit') + print("Error: msel is unknown", mselcb, " STOP program") + sys.exit("ERROR on input, exit") PDG = ROOT.TDatabasePDG.Instance() myPythia = ROOT.TPythia6() tp = ROOT.tPythia6Generator() # Pythia6 can only accept names below in pyinit, hence reset PDG table: -PDG.GetParticle(2212).SetName('p+') -PDG.GetParticle(-2212).SetName('pbar-') -PDG.GetParticle(2112).SetName('n0') -PDG.GetParticle(-2112).SetName('nbar0') -PDG.GetParticle(130).SetName('KL0') -PDG.GetParticle(310).SetName('KS0') -#lower lowest sqrt(s) allowed for generating events -myPythia.SetPARP(2,2.) +PDG.GetParticle(2212).SetName("p+") +PDG.GetParticle(-2212).SetName("pbar-") +PDG.GetParticle(2112).SetName("n0") +PDG.GetParticle(-2112).SetName("nbar0") +PDG.GetParticle(130).SetName("KL0") +PDG.GetParticle(310).SetName("KS0") +# lower lowest sqrt(s) allowed for generating events +myPythia.SetPARP(2, 2.0) + def PoorE791_tune(P6): -# settings with default Pythia6 pdf, based on getting at 500 GeV pi- -# same as that of E791: http://arxiv.org/pdf/hep-ex/9906034.pdf - print(' ') - print('********** PoorE791_tune **********') - #change pt of D's to mimic E791 data. - P6.SetPARP(91,1.6) - print('PARP(91)=',P6.GetPARP(91)) - #what PDFs etc.. are being used: - print('MSTP PDF info, i.e. (51) and (52)=',P6.GetMSTP(51),P6.GetMSTP(52)) - #set multiple interactions equal to Fortran version, i.e.=1, default=4, and adapt parp(89) accordingly - P6.SetMSTP(82,1) - P6.SetPARP(89,1000.) - print('And corresponding multiple parton stuff, i.e. MSTP(82),PARP(81,89,90)=',P6.GetMSTP(82),P6.GetPARP(81),P6.GetPARP(89),P6.GetPARP(90)) - print('********** PoorE791_tune **********') - print(' ') + # settings with default Pythia6 pdf, based on getting at 500 GeV pi- + # same as that of E791: http://arxiv.org/pdf/hep-ex/9906034.pdf + print(" ") + print("********** PoorE791_tune **********") + # change pt of D's to mimic E791 data. + P6.SetPARP(91, 1.6) + print("PARP(91)=", P6.GetPARP(91)) + # what PDFs etc.. are being used: + print("MSTP PDF info, i.e. (51) and (52)=", P6.GetMSTP(51), P6.GetMSTP(52)) + # set multiple interactions equal to Fortran version, i.e.=1, default=4, and adapt parp(89) accordingly + P6.SetMSTP(82, 1) + P6.SetPARP(89, 1000.0) + print( + "And corresponding multiple parton stuff, i.e. MSTP(82),PARP(81,89,90)=", + P6.GetMSTP(82), + P6.GetPARP(81), + P6.GetPARP(89), + P6.GetPARP(90), + ) + print("********** PoorE791_tune **********") + print(" ") + def LHCb_tune(P6): -# settings by LHCb for Pythia 6.427 -# https://twiki.cern.ch/twiki/bin/view/LHCb/SettingsSim08 - print(' ') - print('********** LHCb_tune **********') - #P6.SetCKIN(41,3.0) - P6.SetMSTP(2, 2) - P6.SetMSTP(33, 3) - #P6.SetMSTP(128, 2) #store or not store - P6.SetMSTP(81, 21) - P6.SetMSTP(82, 3) - P6.SetMSTP(52, 2) - P6.SetMSTP(51, 10042)# (ie CTEQ6 LO fit, with LOrder alpha_S PDF from LHAPDF) - P6.SetMSTP(142, 0) #do not weigh events - P6.SetPARP(67, 1.0) - P6.SetPARP(82, 4.28) - P6.SetPARP(89, 14000) - P6.SetPARP(90, 0.238) - P6.SetPARP(85, 0.33) - P6.SetPARP(86, 0.66) - P6.SetPARP(91, 1.0) - P6.SetPARP(149, 0.02) - P6.SetPARP(150, 0.085) - P6.SetPARJ(11, 0.4) - P6.SetPARJ(12, 0.4) - P6.SetPARJ(13, 0.769) - P6.SetPARJ(14, 0.09) - P6.SetPARJ(15, 0.018) - P6.SetPARJ(16, 0.0815) - P6.SetPARJ(17, 0.0815) - P6.SetMSTJ(26, 0) - P6.SetPARJ(33, 0.4) - print('********** LHCb_tune **********') - print(' ') + # settings by LHCb for Pythia 6.427 + # https://twiki.cern.ch/twiki/bin/view/LHCb/SettingsSim08 + print(" ") + print("********** LHCb_tune **********") + # P6.SetCKIN(41,3.0) + P6.SetMSTP(2, 2) + P6.SetMSTP(33, 3) + # P6.SetMSTP(128, 2) #store or not store + P6.SetMSTP(81, 21) + P6.SetMSTP(82, 3) + P6.SetMSTP(52, 2) + P6.SetMSTP(51, 10042) # (ie CTEQ6 LO fit, with LOrder alpha_S PDF from LHAPDF) + P6.SetMSTP(142, 0) # do not weigh events + P6.SetPARP(67, 1.0) + P6.SetPARP(82, 4.28) + P6.SetPARP(89, 14000) + P6.SetPARP(90, 0.238) + P6.SetPARP(85, 0.33) + P6.SetPARP(86, 0.66) + P6.SetPARP(91, 1.0) + P6.SetPARP(149, 0.02) + P6.SetPARP(150, 0.085) + P6.SetPARJ(11, 0.4) + P6.SetPARJ(12, 0.4) + P6.SetPARJ(13, 0.769) + P6.SetPARJ(14, 0.09) + P6.SetPARJ(15, 0.018) + P6.SetPARJ(16, 0.0815) + P6.SetPARJ(17, 0.0815) + P6.SetMSTJ(26, 0) + P6.SetPARJ(33, 0.4) + print("********** LHCb_tune **********") + print(" ") + def fillp1(hist): -# scan filled bins in hist, and fill intermediate bins with lineair interpolation - nb=hist.GetNbinsX() - i1=hist.FindBin(pbeaml,0.,0.) - y1=hist.GetBinContent(i1) - p1=hist.GetBinCenter(i1) - for i in range(i1+1,nb+1): - if hist.GetBinContent(i)>0.: - y2=hist.GetBinContent(i) - p2=hist.GetBinCenter(i) - tg=(y2-y1)/(p2-p1) - for ib in range(i1+1,i): - px=hist.GetBinCenter(ib) - yx=(px-p1)*tg+y1 - hist.Fill(px,yx) - i1=i - y1=y2 - p1=p2 - - -#choose the Pythia tune: + # scan filled bins in hist, and fill intermediate bins with lineair interpolation + nb = hist.GetNbinsX() + i1 = hist.FindBin(pbeaml, 0.0, 0.0) + y1 = hist.GetBinContent(i1) + p1 = hist.GetBinCenter(i1) + for i in range(i1 + 1, nb + 1): + if hist.GetBinContent(i) > 0.0: + y2 = hist.GetBinContent(i) + p2 = hist.GetBinCenter(i) + tg = (y2 - y1) / (p2 - p1) + for ib in range(i1 + 1, i): + px = hist.GetBinCenter(ib) + yx = (px - p1) * tg + y1 + hist.Fill(px, yx) + i1 = i + y1 = y2 + p1 = p2 + + +# choose the Pythia tune: PoorE791_tune(myPythia) -#LHCb_tune(myPythia) -#avoid any printing to the screen, only when LHAPDF is used, i.e. LHCb tune. -#myPythia.OpenFortranFile(6, os.devnull) +# LHCb_tune(myPythia) +# avoid any printing to the screen, only when LHAPDF is used, i.e. LHCb tune. +# myPythia.OpenFortranFile(6, os.devnull) # Pythia output to dummy (11) file (to screen use 6) myPythia.OpenFortranFile(11, os.devnull) myPythia.SetMSTU(11, 11) -#start with different random number for each run... -if R == '': R = int(time.time()*100000000%900000000) -print('Setting random number seed =',R) -myPythia.SetMRPY(1,R) +# start with different random number for each run... +if R == "": + R = int(time.time() * 100000000 % 900000000) +print("Setting random number seed =", R) +myPythia.SetMRPY(1, R) -#histogram helper -h={} +# histogram helper +h = {} # initalise phase, determine chi=sigma(signal)/sigma(total) for many beam momenta. # loop over beam particles -id=0 -nb=400 -t0=time.time() -idhist=len(idbeam)*4*[0] -print('Get chi vs momentum for all beam+target particles') -for idp in range(0,len(idbeam)): -# particle or antiparticle - for idpm in range(-1,3,2): - idw=idbeam[idp]*idpm - if PDG.GetParticle(idw)!=None: - name=PDG.GetParticle(idw).GetName() -# particle exists, book hists etc.. - id=id+1 - for idnp in range(2): - idb=id*10+idnp*4 - ut.bookHist(h,str(idb+1),'sigma vs p, '+name+'->'+target[idnp],nb,0.5,pbeamh+0.5) - ut.bookHist(h,str(idb+2),'sigma-tot vs p, '+name+'->'+target[idnp],nb,0.5,pbeamh+0.5) - ut.bookHist(h,str(idb+3),'chi vs p, '+name+'->'+target[idnp],nb,0.5,pbeamh+0.5) - ut.bookHist(h,str(idb+4),'Prob(normalised), '+name+'->'+target[idnp],nb,0.5,pbeamh+0.5) -# keep track of histogram<->Particle id relation. - idhist[id]=idw -# target is proton or neutron - for idpn in range(2): - idadd=idpn*4 -# loop over beam momentum - print(name,'+',target[idpn],' for chi, seconds:',time.time()-t0) - for ipbeam in range(nrpoints): - pbw=ipbeam*(pbeamh-pbeaml)/(nrpoints-1)+pbeaml -# convert to center of a bin - ibin=h[str(id*10+1+idadd)].FindBin(pbw,0.,0.) - pbw=h[str(id*10+1+idadd)].GetBinCenter(ibin) -# new particle/momentum, init again, first signal run. - myPythia.SetMSEL(mselcb) # set forced ccbar or bbbar generation - myPythia.Initialize('FIXT',name,target[idpn],pbw) - for iev in range(nev): - myPythia.GenerateEvent() -# signal run finished, get cross-section - h[str(id*10+1+idadd)].Fill(pbw,tp.getPyint5_XSEC(2,0)) -# now total cross-section, i.e. msel=2 - myPythia.SetMSEL(2) - myPythia.Initialize('FIXT',name,target[idpn],pbw) - for iev in range(nev//10): -# if iev%100==0: print 'generated mbias events',iev,' seconds:',time.time()-t0 - myPythia.GenerateEvent() -# get cross-section - h[str(id*10+2+idadd)].Fill(pbw,tp.getPyint5_XSEC(2,0)) -# for this beam particle, do arithmetics to get chi. - h[str(id*10+3+idadd)].Divide(h[str(id*10+1+idadd)],h[str(id*10+2+idadd)],1.,1.) -# fill with lineair function between evaluated momentum points. - fillp1(h[str(id*10+3+idadd)]) +id = 0 +nb = 400 +t0 = time.time() +idhist = len(idbeam) * 4 * [0] +print("Get chi vs momentum for all beam+target particles") +for idp in range(0, len(idbeam)): + # particle or antiparticle + for idpm in range(-1, 3, 2): + idw = idbeam[idp] * idpm + if PDG.GetParticle(idw) != None: + name = PDG.GetParticle(idw).GetName() + # particle exists, book hists etc.. + id = id + 1 + for idnp in range(2): + idb = id * 10 + idnp * 4 + ut.bookHist( + h, + str(idb + 1), + "sigma vs p, " + name + "->" + target[idnp], + nb, + 0.5, + pbeamh + 0.5, + ) + ut.bookHist( + h, + str(idb + 2), + "sigma-tot vs p, " + name + "->" + target[idnp], + nb, + 0.5, + pbeamh + 0.5, + ) + ut.bookHist( + h, + str(idb + 3), + "chi vs p, " + name + "->" + target[idnp], + nb, + 0.5, + pbeamh + 0.5, + ) + ut.bookHist( + h, + str(idb + 4), + "Prob(normalised), " + name + "->" + target[idnp], + nb, + 0.5, + pbeamh + 0.5, + ) + # keep track of histogram<->Particle id relation. + idhist[id] = idw + # target is proton or neutron + for idpn in range(2): + idadd = idpn * 4 + # loop over beam momentum + print(name, "+", target[idpn], " for chi, seconds:", time.time() - t0) + for ipbeam in range(nrpoints): + pbw = ipbeam * (pbeamh - pbeaml) / (nrpoints - 1) + pbeaml + # convert to center of a bin + ibin = h[str(id * 10 + 1 + idadd)].FindBin(pbw, 0.0, 0.0) + pbw = h[str(id * 10 + 1 + idadd)].GetBinCenter(ibin) + # new particle/momentum, init again, first signal run. + myPythia.SetMSEL(mselcb) # set forced ccbar or bbbar generation + myPythia.Initialize("FIXT", name, target[idpn], pbw) + for iev in range(nev): + myPythia.GenerateEvent() + # signal run finished, get cross-section + h[str(id * 10 + 1 + idadd)].Fill(pbw, tp.getPyint5_XSEC(2, 0)) + # now total cross-section, i.e. msel=2 + myPythia.SetMSEL(2) + myPythia.Initialize("FIXT", name, target[idpn], pbw) + for iev in range(nev // 10): + # if iev%100==0: print 'generated mbias events',iev,' seconds:',time.time()-t0 + myPythia.GenerateEvent() + # get cross-section + h[str(id * 10 + 2 + idadd)].Fill(pbw, tp.getPyint5_XSEC(2, 0)) + # for this beam particle, do arithmetics to get chi. + h[str(id * 10 + 3 + idadd)].Divide( + h[str(id * 10 + 1 + idadd)], h[str(id * 10 + 2 + idadd)], 1.0, 1.0 + ) + # fill with lineair function between evaluated momentum points. + fillp1(h[str(id * 10 + 3 + idadd)]) # collected all, now re-scale to make max chi at 400 Gev==1. -chimx=0. -for i in range(1,id+1): - for idpn in range(2): - idw=i*10+idpn*4+3 - ibh=h[str(idw)].FindBin(pbeamh) - print('beam id, momentum,chi,chimx=',i,idw,idhist[i],pbeamh,h[str(idw)].GetBinContent(ibh),chimx) - if h[str(idw)].GetBinContent(ibh)>chimx: chimx=h[str(idw)].GetBinContent(ibh) -chimx=1./chimx -for i in range(1,id+1): - for idpn in range(2): - idw=i*10+idpn*4+3 - h[str(idw+1)].Add(h[str(idw)],h[str(idw)],chimx,0.) +chimx = 0.0 +for i in range(1, id + 1): + for idpn in range(2): + idw = i * 10 + idpn * 4 + 3 + ibh = h[str(idw)].FindBin(pbeamh) + print( + "beam id, momentum,chi,chimx=", + i, + idw, + idhist[i], + pbeamh, + h[str(idw)].GetBinContent(ibh), + chimx, + ) + if h[str(idw)].GetBinContent(ibh) > chimx: + chimx = h[str(idw)].GetBinContent(ibh) +chimx = 1.0 / chimx +for i in range(1, id + 1): + for idpn in range(2): + idw = i * 10 + idpn * 4 + 3 + h[str(idw + 1)].Add(h[str(idw)], h[str(idw)], chimx, 0.0) # switch output printing OFF for generation phase. # Generate ccbar (or bbbar) pairs according to probability in hists i*10+8. # some check histos -ut.bookHist(h,str(1),'E of signals',100,0.,400.) -ut.bookHist(h,str(2),'nr signal per cascade depth',50,0.5,50.5) -ut.bookHist(h,str(3),'D0 pt**2',40,0.,4.) -ut.bookHist(h,str(4),'D0 pt**2',100,0.,18.) -ut.bookHist(h,str(5),'D0 pt',100,0.,10.) -ut.bookHist(h,str(6),'D0 XF',100,-1.,1.) - -ftup = ROOT.TFile.Open(Fntuple, 'RECREATE') -Ntup = ROOT.TNtuple("pythia6","pythia6 heavy flavour",\ - "id:px:py:pz:E:M:mid:mpx:mpy:mpz:mE:mM:k:a0:a1:a2:a3:a4:a5:a6:a7:a8:a9:a10:a11:a12:a13:a14:a15:\ -s0:s1:s2:s3:s4:s5:s6:s7:s8:s9:s10:s11:s12:s13:s14:s15") - -#make sure all particles for cascade production are stable +ut.bookHist(h, str(1), "E of signals", 100, 0.0, 400.0) +ut.bookHist(h, str(2), "nr signal per cascade depth", 50, 0.5, 50.5) +ut.bookHist(h, str(3), "D0 pt**2", 40, 0.0, 4.0) +ut.bookHist(h, str(4), "D0 pt**2", 100, 0.0, 18.0) +ut.bookHist(h, str(5), "D0 pt", 100, 0.0, 10.0) +ut.bookHist(h, str(6), "D0 XF", 100, -1.0, 1.0) + +ftup = ROOT.TFile.Open(Fntuple, "RECREATE") +Ntup = ROOT.TNtuple( + "pythia6", + "pythia6 heavy flavour", + "id:px:py:pz:E:M:mid:mpx:mpy:mpz:mE:mM:k:a0:a1:a2:a3:a4:a5:a6:a7:a8:a9:a10:a11:a12:a13:a14:a15:\ +s0:s1:s2:s3:s4:s5:s6:s7:s8:s9:s10:s11:s12:s13:s14:s15", +) + +# make sure all particles for cascade production are stable for kf in idbeam: - kc = myPythia.Pycomp(kf) - myPythia.SetMDCY(kc,1,0) + kc = myPythia.Pycomp(kf) + myPythia.SetMDCY(kc, 1, 0) # make charm or beauty signal hadrons stable for kf in idsig: - kc = myPythia.Pycomp(kf) - myPythia.SetMDCY(kc,1,0) + kc = myPythia.Pycomp(kf) + myPythia.SetMDCY(kc, 1, 0) -#declare the stack for the cascade particles -stack=1000*[0] +# declare the stack for the cascade particles +stack = 1000 * [0] for iev in range(nevgen): - if iev%1000==0: print('Generate event ',iev) -#put 400. GeV proton on the stack - nstack=0 -# stack: PID,px,py,pz,cascade depth,nstack of mother - stack[nstack]=[2212,0.,0.,pbeamh,1,100*[0],100*[0]] - stack[nstack][5][0]=2212 - while nstack>=0: -# generate a signal based on probabilities in hists i*10+8? - ptot=ROOT.TMath.Sqrt(stack[nstack][1]**2+stack[nstack][2]**2+stack[nstack][3]**2) - prbsig=0. - for i in range(1,id+1): -# get hist id for this beam particle - if stack[nstack][0]==idhist[i]: - idpn=0 -# decide on p or n target in Mo - if random.random>fracp: idpn=1 - idw=i*10+idpn*4+4 - ib=h[str(idw)].FindBin(ptot,0.,0.) - prbsig=h[str(idw)].GetBinContent(ib) - if prbsig>random.random(): -# last particle on the stack as beam particle - for k in range(1,4): - myPythia.SetP(1,k,stack[nstack][k]) - myPythia.SetP(2,k,0.) -# new particle/momentum, init again: signal run. - myPythia.SetMSEL(mselcb) # set forced ccbar or bbbar generation - myPythia.Initialize('3MOM',PDG.GetParticle(stack[nstack][0]).GetName(),target[idpn],0.) - myPythia.GenerateEvent() -# look for the signal particles - charmFound = [] - for itrk in range(1,myPythia.GetN()+1): - idabs = ROOT.TMath.Abs(myPythia.GetK(itrk,2)) - if idabs in idsig: - #signal found store in ntuple - vl=array('f') - vl.append(float(myPythia.GetK(itrk,2))) - for i in range(1,6): - vl.append(float(myPythia.GetP(itrk,i))) - vl.append(float(myPythia.GetK(1,2))) - for i in range(1,6): - vl.append(float(myPythia.GetP(1,i))) - vl.append(float(stack[nstack][4])) - for i in range(16): - vl.append(float(stack[nstack][5][i])) - nsub=stack[nstack][4]-1 - if nsub>15: nsub=15 - for i in range(nsub): - vl.append(float(stack[nstack][6][i])) - vl.append(float(myPythia.GetMSTI(1))) - for i in range(nsub+1,16): - vl.append(float(0)) - Ntup.Fill(vl) - charmFound.append(itrk) - h['1'].Fill(myPythia.GetP(itrk,4)) - h['2'].Fill(stack[nstack][4]) - if idabs==421 and stack[nstack][4]==1 : -# some checking hist to monitor pt**2, XF of prompt D^0 - pt2=myPythia.GetP(itrk,1)**2+myPythia.GetP(itrk,2)**2 - h['3'].Fill(pt2) - h['4'].Fill(pt2) - h['5'].Fill(ROOT.TMath.Sqrt(pt2)) -# boost to Cm frame for XF ccalculation of D^0 - beta=pbeamh/(myPythia.GetP(1,4)+myPythia.GetP(2,5)) - gamma=(1-beta**2)**-0.5 - pbcm=-gamma*beta*myPythia.GetP(1,4)+gamma*myPythia.GetP(1,3) - pDcm=-gamma*beta*myPythia.GetP(itrk,4)+gamma*myPythia.GetP(itrk,3) - xf=pDcm/pbcm - h['6'].Fill(xf) - if len(charmFound)>0 and storePrimaries: - for itP in range(1,myPythia.GetN()+1): - if itP in charmFound: continue - if myPythia.GetK(itP,1)==1: -# store only undecayed particle and no charm found -# ***WARNING****: with new with new ancestor and process info (a0-15, s0-15) add to ntuple, might not work??? - Ntup.Fill(float(myPythia.GetK(itP,2)),float(myPythia.GetP(itP,1)),float(myPythia.GetP(itP,2)),float(myPythia.GetP(itP,3)),\ - float(myPythia.GetP(itP,4)),float(myPythia.GetP(itP,5)),-1,\ - float(myPythia.GetV(itP,1)-myPythia.GetV(charmFound[0],1)),\ - float(myPythia.GetV(itP,2)-myPythia.GetV(charmFound[0],2)),\ - float(myPythia.GetV(itP,3)-myPythia.GetV(charmFound[0],3)),0,0,stack[nstack][4]) - -# now generate msel=2 to add new cascade particles to the stack - for k in range(1,4): - myPythia.SetP(1,k,stack[nstack][k]) - myPythia.SetP(2,k,0.) -# new particle/momentum, init again, generate total cross-section event - myPythia.SetMSEL(2) # mbias event - idpn=0 - if random.random()>fracp: idpn=1 - myPythia.Initialize('3MOM',PDG.GetParticle(stack[nstack][0]).GetName(),target[idpn],0.) - myPythia.GenerateEvent() -# remove used particle from the stack, before adding new -# first store its history: cascade depth and ancestors-list - icas=stack[nstack][4]+1 - if icas>98: icas=98 - anclist=copy.copy(stack[nstack][5]) - sublist=copy.copy(stack[nstack][6]) - #fill in interaction process of first proton - if nstack==0: sublist[0]=myPythia.GetMSTI(1) - nstack=nstack-1 - for itrk in range(1,myPythia.GetN()+1): - if myPythia.GetK(itrk,1)==1: - ptot=ROOT.TMath.Sqrt(myPythia.GetP(itrk,1)**2+myPythia.GetP(itrk,2)**2+myPythia.GetP(itrk,3)**2) - if ptot>pbeaml: -# produced particle is stable and has enough momentum, is it in the wanted list? - for isig in range(len(idbeam)): - if ROOT.TMath.Abs(myPythia.GetK(itrk,2))==idbeam[isig] and nstack<999: - if nstack<999: nstack+=1 - #update ancestor list - tmp=copy.copy(anclist) - tmp[icas-1]=myPythia.GetK(itrk,2) - stmp=copy.copy(sublist) - #Pythia interaction process identifier - stmp[icas-1]=myPythia.GetMSTI(1) - stack[nstack]=[myPythia.GetK(itrk,2),myPythia.GetP(itrk,1),myPythia.GetP(itrk,2),myPythia.GetP(itrk,3),icas,tmp,stmp] - -print('Now at Ntup.Write()') + if iev % 1000 == 0: + print("Generate event ", iev) + # put 400. GeV proton on the stack + nstack = 0 + # stack: PID,px,py,pz,cascade depth,nstack of mother + stack[nstack] = [2212, 0.0, 0.0, pbeamh, 1, 100 * [0], 100 * [0]] + stack[nstack][5][0] = 2212 + while nstack >= 0: + # generate a signal based on probabilities in hists i*10+8? + ptot = ROOT.TMath.Sqrt( + stack[nstack][1] ** 2 + stack[nstack][2] ** 2 + stack[nstack][3] ** 2 + ) + prbsig = 0.0 + for i in range(1, id + 1): + # get hist id for this beam particle + if stack[nstack][0] == idhist[i]: + idpn = 0 + # decide on p or n target in Mo + if random.random > fracp: + idpn = 1 + idw = i * 10 + idpn * 4 + 4 + ib = h[str(idw)].FindBin(ptot, 0.0, 0.0) + prbsig = h[str(idw)].GetBinContent(ib) + if prbsig > random.random(): + # last particle on the stack as beam particle + for k in range(1, 4): + myPythia.SetP(1, k, stack[nstack][k]) + myPythia.SetP(2, k, 0.0) + # new particle/momentum, init again: signal run. + myPythia.SetMSEL(mselcb) # set forced ccbar or bbbar generation + myPythia.Initialize( + "3MOM", PDG.GetParticle(stack[nstack][0]).GetName(), target[idpn], 0.0 + ) + myPythia.GenerateEvent() + # look for the signal particles + charmFound = [] + for itrk in range(1, myPythia.GetN() + 1): + idabs = ROOT.TMath.Abs(myPythia.GetK(itrk, 2)) + if idabs in idsig: + # signal found store in ntuple + vl = array("f") + vl.append(float(myPythia.GetK(itrk, 2))) + for i in range(1, 6): + vl.append(float(myPythia.GetP(itrk, i))) + vl.append(float(myPythia.GetK(1, 2))) + for i in range(1, 6): + vl.append(float(myPythia.GetP(1, i))) + vl.append(float(stack[nstack][4])) + for i in range(16): + vl.append(float(stack[nstack][5][i])) + nsub = stack[nstack][4] - 1 + if nsub > 15: + nsub = 15 + for i in range(nsub): + vl.append(float(stack[nstack][6][i])) + vl.append(float(myPythia.GetMSTI(1))) + for i in range(nsub + 1, 16): + vl.append(float(0)) + Ntup.Fill(vl) + charmFound.append(itrk) + h["1"].Fill(myPythia.GetP(itrk, 4)) + h["2"].Fill(stack[nstack][4]) + if idabs == 421 and stack[nstack][4] == 1: + # some checking hist to monitor pt**2, XF of prompt D^0 + pt2 = myPythia.GetP(itrk, 1) ** 2 + myPythia.GetP(itrk, 2) ** 2 + h["3"].Fill(pt2) + h["4"].Fill(pt2) + h["5"].Fill(ROOT.TMath.Sqrt(pt2)) + # boost to Cm frame for XF ccalculation of D^0 + beta = pbeamh / (myPythia.GetP(1, 4) + myPythia.GetP(2, 5)) + gamma = (1 - beta**2) ** -0.5 + pbcm = -gamma * beta * myPythia.GetP( + 1, 4 + ) + gamma * myPythia.GetP(1, 3) + pDcm = -gamma * beta * myPythia.GetP( + itrk, 4 + ) + gamma * myPythia.GetP(itrk, 3) + xf = pDcm / pbcm + h["6"].Fill(xf) + if len(charmFound) > 0 and storePrimaries: + for itP in range(1, myPythia.GetN() + 1): + if itP in charmFound: + continue + if myPythia.GetK(itP, 1) == 1: + # store only undecayed particle and no charm found + # ***WARNING****: with new with new ancestor and process info (a0-15, s0-15) add to ntuple, might not work??? + Ntup.Fill( + float(myPythia.GetK(itP, 2)), + float(myPythia.GetP(itP, 1)), + float(myPythia.GetP(itP, 2)), + float(myPythia.GetP(itP, 3)), + float(myPythia.GetP(itP, 4)), + float(myPythia.GetP(itP, 5)), + -1, + float( + myPythia.GetV(itP, 1) - myPythia.GetV(charmFound[0], 1) + ), + float( + myPythia.GetV(itP, 2) - myPythia.GetV(charmFound[0], 2) + ), + float( + myPythia.GetV(itP, 3) - myPythia.GetV(charmFound[0], 3) + ), + 0, + 0, + stack[nstack][4], + ) + + # now generate msel=2 to add new cascade particles to the stack + for k in range(1, 4): + myPythia.SetP(1, k, stack[nstack][k]) + myPythia.SetP(2, k, 0.0) + # new particle/momentum, init again, generate total cross-section event + myPythia.SetMSEL(2) # mbias event + idpn = 0 + if random.random() > fracp: + idpn = 1 + myPythia.Initialize( + "3MOM", PDG.GetParticle(stack[nstack][0]).GetName(), target[idpn], 0.0 + ) + myPythia.GenerateEvent() + # remove used particle from the stack, before adding new + # first store its history: cascade depth and ancestors-list + icas = stack[nstack][4] + 1 + if icas > 98: + icas = 98 + anclist = copy.copy(stack[nstack][5]) + sublist = copy.copy(stack[nstack][6]) + # fill in interaction process of first proton + if nstack == 0: + sublist[0] = myPythia.GetMSTI(1) + nstack = nstack - 1 + for itrk in range(1, myPythia.GetN() + 1): + if myPythia.GetK(itrk, 1) == 1: + ptot = ROOT.TMath.Sqrt( + myPythia.GetP(itrk, 1) ** 2 + + myPythia.GetP(itrk, 2) ** 2 + + myPythia.GetP(itrk, 3) ** 2 + ) + if ptot > pbeaml: + # produced particle is stable and has enough momentum, is it in the wanted list? + for isig in range(len(idbeam)): + if ( + ROOT.TMath.Abs(myPythia.GetK(itrk, 2)) == idbeam[isig] + and nstack < 999 + ): + if nstack < 999: + nstack += 1 + # update ancestor list + tmp = copy.copy(anclist) + tmp[icas - 1] = myPythia.GetK(itrk, 2) + stmp = copy.copy(sublist) + # Pythia interaction process identifier + stmp[icas - 1] = myPythia.GetMSTI(1) + stack[nstack] = [ + myPythia.GetK(itrk, 2), + myPythia.GetP(itrk, 1), + myPythia.GetP(itrk, 2), + myPythia.GetP(itrk, 3), + icas, + tmp, + stmp, + ] + +print("Now at Ntup.Write()") Ntup.Write() -for akey in h: h[akey].Write() +for akey in h: + h[akey].Write() ftup.Close() timer.Stop() rtime = timer.RealTime() ctime = timer.CpuTime() -print(' ') +print(" ") print("Macro finished succesfully.") -print("Output file is ", ftup.GetName()) -print("Real time ",rtime, " s, CPU time ",ctime,"s") +print("Output file is ", ftup.GetName()) +print("Real time ", rtime, " s, CPU time ", ctime, "s") diff --git a/macro/makeDecay.py b/macro/makeDecay.py index 7488f4986a..0d7e94117c 100644 --- a/macro/makeDecay.py +++ b/macro/makeDecay.py @@ -1,174 +1,243 @@ -#Use Pythia8 to decay the signals (Charm/Beauty) as produced by makeCascade. -#Output is an ntuple with muon/neutrinos -import ROOT,time,os,sys,random,getopt +# Use Pythia8 to decay the signals (Charm/Beauty) as produced by makeCascade. +# Output is an ntuple with muon/neutrinos +import getopt +import os +import random +import sys +import time + +import ROOT import rootUtils as ut + ROOT.gROOT.LoadMacro("$VMCWORKDIR/gconfig/basiclibs.C") ROOT.basiclibs() # latest production May 2016,76 M pot which produce a charm event equivalent,roughly 150 M charm hadrons -fname='/eos/experiment/ship/data/Charm/Cascade-parp16-MSTP82-1-MSEL4-76Mpot_1' +fname = "/eos/experiment/ship/data/Charm/Cascade-parp16-MSTP82-1-MSEL4-76Mpot_1" -nrpotspill=5.e13 #number of pot/spill -chicc=1.7e-3 #prob to produce primary ccbar pair/pot -chibb=1.6e-7 #prob to produce primary bbbar pair/pot +nrpotspill = 5.0e13 # number of pot/spill +chicc = 1.7e-3 # prob to produce primary ccbar pair/pot +chibb = 1.6e-7 # prob to produce primary bbbar pair/pot setByHand = False print("usage: python $FAIRSHIP/macro/makeDecay.py -f ") try: - opts, args = getopt.getopt(sys.argv[1:], "f:p:c:",[\ - "pot=","chicc="]) + opts, args = getopt.getopt(sys.argv[1:], "f:p:c:", ["pot=", "chicc="]) except getopt.GetoptError: - # print help information and exit: - print(' enter -f: input file with charm hadrons') - print(' for experts: p pot= number of protons on target per spill to normalize on') - print(' : c chicc= ccbar over mbias cross section') - sys.exit() + # print help information and exit: + print(" enter -f: input file with charm hadrons") + print(" for experts: p pot= number of protons on target per spill to normalize on") + print(" : c chicc= ccbar over mbias cross section") + sys.exit() for o, a in opts: - if o in ("-f",): - fname = a.replace('.root','') - if o in ("-p","--pot"): - nrpotspill = float(a) - if o in ("-c","--chicc"): - chicc = float(a) - setByHand = True - -FIN =fname+'.root' -tmp = os.path.abspath(FIN).split('/') -FOUT='Decay-'+tmp[len(tmp)-1] -if FIN.find('eos')<0: fin = ROOT.TFile(FIN) -else: fin = ROOT.TFile.Open(ROOT.gSystem.Getenv("EOSSHIP")+FIN) + if o in ("-f",): + fname = a.replace(".root", "") + if o in ("-p", "--pot"): + nrpotspill = float(a) + if o in ("-c", "--chicc"): + chicc = float(a) + setByHand = True + +FIN = fname + ".root" +tmp = os.path.abspath(FIN).split("/") +FOUT = "Decay-" + tmp[len(tmp) - 1] +if FIN.find("eos") < 0: + fin = ROOT.TFile(FIN) +else: + fin = ROOT.TFile.Open(ROOT.gSystem.Getenv("EOSSHIP") + FIN) sTree = fin.FindObjectAny("pythia6") nEvents = sTree.GetEntries() -#Calculate weights, for the whole file. -#get histogram with number of pot to normalise -hc={} -if fin.GetKey("2") : - hc['2']=fin.Get("2") +# Calculate weights, for the whole file. +# get histogram with number of pot to normalise +hc = {} +if fin.GetKey("2"): + hc["2"] = fin.Get("2") else: - fhin = ROOT.TFile(FIN.replace('ntuple','hists')) - hc['2']=fhin.Get("2") + fhin = ROOT.TFile(FIN.replace("ntuple", "hists")) + hc["2"] = fhin.Get("2") -#pot are counted double, i.e. for each signal, i.e. pot/2. -nrcpot=hc['2'].GetBinContent(1)/2. -print('Input file: ',FIN,' with ',nEvents,' entries, corresponding to nr-pot=',nrcpot) -#nEvents=100 -print('Output ntuples written to: ',FOUT) +# pot are counted double, i.e. for each signal, i.e. pot/2. +nrcpot = hc["2"].GetBinContent(1) / 2.0 +print( + "Input file: ", FIN, " with ", nEvents, " entries, corresponding to nr-pot=", nrcpot +) +# nEvents=100 +print("Output ntuples written to: ", FOUT) P8gen = ROOT.TPythia8() -P8=P8gen.Pythia8() +P8 = P8gen.Pythia8() P8.readString("ProcessLevel:all = off") # let strange particle decay in Geant4 -n=1 -while n!=0: - n = p8.particleData.nextId(n) - p = p8.particleData.particleDataEntryPtr(n) - if p.tau0()>1: - command = str(n)+":mayDecay = false" - p8.readString(command) - print("Pythia8 configuration: Made %s stable for Pythia, should decay in Geant4",p.name()) +n = 1 +while n != 0: + n = p8.particleData.nextId(n) + p = p8.particleData.particleDataEntryPtr(n) + if p.tau0() > 1: + command = str(n) + ":mayDecay = false" + p8.readString(command) + print( + "Pythia8 configuration: Made %s stable for Pythia, should decay in Geant4", + p.name(), + ) P8.init() -#output ntuple: -ftup = ROOT.TFile.Open(FOUT, 'RECREATE') -Ntup = ROOT.TNtuple("Decay","pythia8 heavy flavour decays","id:px:py:pz:E:M:weight:mid:mpx:mpy:mpz:mE:pot:ptGM:pzGM") +# output ntuple: +ftup = ROOT.TFile.Open(FOUT, "RECREATE") +Ntup = ROOT.TNtuple( + "Decay", + "pythia8 heavy flavour decays", + "id:px:py:pz:E:M:weight:mid:mpx:mpy:mpz:mE:pot:ptGM:pzGM", +) -h={} -#book hists for Genie neutrino momentum distrubition, just as check +h = {} +# book hists for Genie neutrino momentum distrubition, just as check # type of neutrino PDG = ROOT.TDatabasePDG.Instance() -for idnu in range(12,18,2): -#nu or anti-nu - for idadd in range(-1,3,2): - idhnu=1000+idnu - idw=idnu - if idadd==-1: - idhnu+=1000 - idw=-idnu - name=PDG.GetParticle(idw).GetName() - ut.bookHist(h,str(idhnu),name+' momentum (GeV)',400,0.,400.) - ut.bookHist(h,str(idhnu+100),name+' log10-p vs log10-pt',100,-0.3,1.7,100,-2.,0.5) - ut.bookHist(h,str(idhnu+200),name+' log10-p vs log10-pt',25,-0.3,1.7,100,-2.,0.5) - -pot=0. -#Determine fDs on this file for primaries -nDsprim=0 -ntotprim=0 +for idnu in range(12, 18, 2): + # nu or anti-nu + for idadd in range(-1, 3, 2): + idhnu = 1000 + idnu + idw = idnu + if idadd == -1: + idhnu += 1000 + idw = -idnu + name = PDG.GetParticle(idw).GetName() + ut.bookHist(h, str(idhnu), name + " momentum (GeV)", 400, 0.0, 400.0) + ut.bookHist( + h, + str(idhnu + 100), + name + " log10-p vs log10-pt", + 100, + -0.3, + 1.7, + 100, + -2.0, + 0.5, + ) + ut.bookHist( + h, + str(idhnu + 200), + name + " log10-p vs log10-pt", + 25, + -0.3, + 1.7, + 100, + -2.0, + 0.5, + ) + +pot = 0.0 +# Determine fDs on this file for primaries +nDsprim = 0 +ntotprim = 0 for n in range(nEvents): - rc = sTree.GetEvent(n) -# check if we deal with charm or beauty: - if n == 0: - if not setByHand and sTree.M>5: - chicc = chibb - print("automatic detection of beauty, configured for beauty") - print('bb cross section / mbias ',chicc) - else: - print('cc cross section / mbias ',chicc) - #convert pot to weight corresponding to one spill of 5e13 pot - print('weights: ',nrpotspill,' p.o.t. per spill') - print(' ') - wspill=nrpotspill*chicc/nrcpot - #sanity check, count number of p.o.t. on input file. - pt=ROOT.TMath.Sqrt(sTree.mpx**2+sTree.mpy**2) - #every event appears twice, i.e. - if pt<1.e-5 and int(sTree.mid)==2212: - pot=pot+0.5 - ntotprim+=1 - idabs=int(abs(sTree.id)) - if idabs==431: nDsprim+=1 - P8.event.reset() - P8.event.append(int(sTree.id),1,0,0,sTree.px,sTree.py,sTree.pz,sTree.E,sTree.M,0.,9.) - next(P8) - #P8.event.list() - for n in range(P8.event.size()): - #ask for stable particles - if P8.event[n].isFinal(): - #select neutrinos and mu - idabs=int(abs(P8.event[n].id())) - if idabs>11 and idabs<17: - par= P8.event[n] - ptGM = ROOT.TMath.Sqrt(sTree.mpx*sTree.mpx+sTree.mpy*sTree.mpy) - Ntup.Fill(par.id(),par.px(),par.py(),par.pz(),par.e(),par.m(),wspill,sTree.id,sTree.px,sTree.py,sTree.pz,sTree.E,sTree.M,ptGM,sTree.mpz) - #count total muons from charm/spill, and within some angluar range.. - if idabs==16 or idabs==14 or idabs==12: - idhnu=idabs+1000 - if par.id()<0: idhnu+=1000 - pt2=par.px()**2+par.py()**2 - ptot=ROOT.TMath.Sqrt(pt2+par.pz()**2) - l10ptot=min(max(ROOT.TMath.Log10(ptot),-0.3),1.69999) - l10pt=min(max(ROOT.TMath.Log10(ROOT.TMath.Sqrt(pt2)),-2.),0.4999) - h[str(idhnu)].Fill(ptot,wspill) - h[str(idhnu+100)].Fill(l10ptot,l10pt,wspill) - h[str(idhnu+200)].Fill(l10ptot,l10pt,wspill) - -print('Now at Ntup.Write() for pot=',pot,nrcpot) -if (1.-pot/nrcpot)<1.e-2: - print('write ntuple, weight/event=',nrpotspill,'x',chicc,'/',nrcpot,'=',wspill) - Ntup.Write() - for akey in h: h[akey].Write() - ftup.Close() - print('Neutrino statistics/spill of 5.e15 pot:') - for idnu in range(12,18,2): - #nu or anti-nu - for idadd in range(-1,3,2): - idhnu=1000+idnu - idw=idnu - if idadd==-1: - idhnu+=1000 - idw=-idnu - print(idhnu,h[str(idhnu)].GetTitle(),("%8.3E "%(h[str(idhnu)].Integral()))) - - fDsP6=1.*nDsprim/ntotprim - fDs=0.077 #Used in TP.. - print(' ') - print('fDs of primary proton interactions in P6=',fDsP6, ' should be ',fDs) + rc = sTree.GetEvent(n) + # check if we deal with charm or beauty: + if n == 0: + if not setByHand and sTree.M > 5: + chicc = chibb + print("automatic detection of beauty, configured for beauty") + print("bb cross section / mbias ", chicc) + else: + print("cc cross section / mbias ", chicc) + # convert pot to weight corresponding to one spill of 5e13 pot + print("weights: ", nrpotspill, " p.o.t. per spill") + print(" ") + wspill = nrpotspill * chicc / nrcpot + # sanity check, count number of p.o.t. on input file. + pt = ROOT.TMath.Sqrt(sTree.mpx**2 + sTree.mpy**2) + # every event appears twice, i.e. + if pt < 1.0e-5 and int(sTree.mid) == 2212: + pot = pot + 0.5 + ntotprim += 1 + idabs = int(abs(sTree.id)) + if idabs == 431: + nDsprim += 1 + P8.event.reset() + P8.event.append( + int(sTree.id), 1, 0, 0, sTree.px, sTree.py, sTree.pz, sTree.E, sTree.M, 0.0, 9.0 + ) + next(P8) + # P8.event.list() + for n in range(P8.event.size()): + # ask for stable particles + if P8.event[n].isFinal(): + # select neutrinos and mu + idabs = int(abs(P8.event[n].id())) + if idabs > 11 and idabs < 17: + par = P8.event[n] + ptGM = ROOT.TMath.Sqrt(sTree.mpx * sTree.mpx + sTree.mpy * sTree.mpy) + Ntup.Fill( + par.id(), + par.px(), + par.py(), + par.pz(), + par.e(), + par.m(), + wspill, + sTree.id, + sTree.px, + sTree.py, + sTree.pz, + sTree.E, + sTree.M, + ptGM, + sTree.mpz, + ) + # count total muons from charm/spill, and within some angluar range.. + if idabs == 16 or idabs == 14 or idabs == 12: + idhnu = idabs + 1000 + if par.id() < 0: + idhnu += 1000 + pt2 = par.px() ** 2 + par.py() ** 2 + ptot = ROOT.TMath.Sqrt(pt2 + par.pz() ** 2) + l10ptot = min(max(ROOT.TMath.Log10(ptot), -0.3), 1.69999) + l10pt = min( + max(ROOT.TMath.Log10(ROOT.TMath.Sqrt(pt2)), -2.0), 0.4999 + ) + h[str(idhnu)].Fill(ptot, wspill) + h[str(idhnu + 100)].Fill(l10ptot, l10pt, wspill) + h[str(idhnu + 200)].Fill(l10ptot, l10pt, wspill) + +print("Now at Ntup.Write() for pot=", pot, nrcpot) +if (1.0 - pot / nrcpot) < 1.0e-2: + print( + "write ntuple, weight/event=", nrpotspill, "x", chicc, "/", nrcpot, "=", wspill + ) + Ntup.Write() + for akey in h: + h[akey].Write() + ftup.Close() + print("Neutrino statistics/spill of 5.e15 pot:") + for idnu in range(12, 18, 2): + # nu or anti-nu + for idadd in range(-1, 3, 2): + idhnu = 1000 + idnu + idw = idnu + if idadd == -1: + idhnu += 1000 + idw = -idnu + print( + idhnu, h[str(idhnu)].GetTitle(), ("%8.3E " % (h[str(idhnu)].Integral())) + ) + + fDsP6 = 1.0 * nDsprim / ntotprim + fDs = 0.077 # Used in TP.. + print(" ") + print("fDs of primary proton interactions in P6=", fDsP6, " should be ", fDs) else: - print('*********** WARNING ***********') - print('number of POT does not agree between ntuple and hists, i.e.:',pot,'<>',nrcpot) - print('mu/neutrino ntuple has NOT been written') + print("*********** WARNING ***********") + print( + "number of POT does not agree between ntuple and hists, i.e.:", + pot, + "<>", + nrcpot, + ) + print("mu/neutrino ntuple has NOT been written") # diff --git a/macro/makeGenieEvents.py b/macro/makeGenieEvents.py index 1b92df8866..d9cfa9f999 100644 --- a/macro/makeGenieEvents.py +++ b/macro/makeGenieEvents.py @@ -1,11 +1,16 @@ #!/usr/bin/env python -import ROOT,os,sys,time -from subprocess import call -import shipunit as u -import shipRoot_conf import argparse import logging +import os +import sys +import time +from subprocess import call + import genie_interface +import ROOT +import shipRoot_conf +import shipunit as u + shipRoot_conf.configure() @@ -15,125 +20,220 @@ # this will disable Genie decays for charm particles and tau - -xsec = "gxspl-FNAL-nuSHiP-minimal.xml"# new adapted splines from Genie site -hfile = "pythia8_Geant4_1.0_withCharm_nu.root" #2018 background generation -#xsec = "Nu_splines.xml" -#hfile = "pythia8_Geant4-withCharm_onlyNeutrinos.root" - - -defaultsplinedir = '/eos/experiment/ship/user/aiuliano/GENIE_FNAL_nu_splines' #path of splines -defaultfiledir = '/eos/experiment/ship/data/Mbias/background-prod-2018' #path of flux - - - - - - -def get_arguments(): #available options - - parser = argparse.ArgumentParser( - description='Run GENIE neutrino" simulation') - subparsers = parser.add_subparsers() - ap = subparsers.add_parser('sim',help="make genie simulation file") - - ap.add_argument('-s', '--seed', type=int, dest='seed', default=65539) #default seed in $GENIE/src/Conventions/Controls.h - ap.add_argument('-o','--output' , type=str, help="output directory", dest='work_dir', default=None) - ap.add_argument('-f','--filedir', type=str, help="directory with neutrino fluxes", dest='filedir', default=defaultfiledir) - ap.add_argument('-c','--crosssectiondir', type=str, help="directory with neutrino splines crosssection", dest='splinedir', default=defaultsplinedir) - ap.add_argument('-t', '--target', type=str, help="target material", dest='target', default='iron') - ap.add_argument('-n', '--nevents', type=int, help="number of events", dest='nevents', default=100) - ap.add_argument('-e', '--event-generator-list', type=str, help="event generator list", dest='evtype', default=None) # Possbile evtypes: CC, CCDIS, CCQE, CharmCCDIS, RES, CCRES, see other evtypes in $GENIE/config/EventGeneratorListAssembler.xml - ap.add_argument("--nudet", dest="nudet", help="option for neutrino detector", required=False, action="store_true") - - ap1 = subparsers.add_parser('spline',help="make a new cross section spline file") - ap1.add_argument('-t', '--target', type=str, help="target material", dest='target', default='iron') - ap1.add_argument('-o','--output' , type=str, help="output directory", dest='work_dir', default=None) - args = parser.parse_args() - return args - -args = get_arguments() #getting options - -print('Target type: ', args.target) - -if args.target == 'iron': - targetcode = '1000260560' -elif args.target == 'lead': - targetcode = '1000822040[0.014],1000822060[0.241],1000822070[0.221],1000822080[0.524]' -elif args.target == 'tungsten': - targetcode = '1000741840' +xsec = "gxspl-FNAL-nuSHiP-minimal.xml" # new adapted splines from Genie site +hfile = "pythia8_Geant4_1.0_withCharm_nu.root" # 2018 background generation +# xsec = "Nu_splines.xml" +# hfile = "pythia8_Geant4-withCharm_onlyNeutrinos.root" + + +defaultsplinedir = ( + "/eos/experiment/ship/user/aiuliano/GENIE_FNAL_nu_splines" # path of splines +) +defaultfiledir = "/eos/experiment/ship/data/Mbias/background-prod-2018" # path of flux + + +def get_arguments(): # available options + parser = argparse.ArgumentParser(description='Run GENIE neutrino" simulation') + subparsers = parser.add_subparsers() + ap = subparsers.add_parser("sim", help="make genie simulation file") + + ap.add_argument( + "-s", "--seed", type=int, dest="seed", default=65539 + ) # default seed in $GENIE/src/Conventions/Controls.h + ap.add_argument( + "-o", + "--output", + type=str, + help="output directory", + dest="work_dir", + default=None, + ) + ap.add_argument( + "-f", + "--filedir", + type=str, + help="directory with neutrino fluxes", + dest="filedir", + default=defaultfiledir, + ) + ap.add_argument( + "-c", + "--crosssectiondir", + type=str, + help="directory with neutrino splines crosssection", + dest="splinedir", + default=defaultsplinedir, + ) + ap.add_argument( + "-t", + "--target", + type=str, + help="target material", + dest="target", + default="iron", + ) + ap.add_argument( + "-n", + "--nevents", + type=int, + help="number of events", + dest="nevents", + default=100, + ) + ap.add_argument( + "-e", + "--event-generator-list", + type=str, + help="event generator list", + dest="evtype", + default=None, + ) # Possbile evtypes: CC, CCDIS, CCQE, CharmCCDIS, RES, CCRES, see other evtypes in $GENIE/config/EventGeneratorListAssembler.xml + ap.add_argument( + "--nudet", + dest="nudet", + help="option for neutrino detector", + required=False, + action="store_true", + ) + + ap1 = subparsers.add_parser("spline", help="make a new cross section spline file") + ap1.add_argument( + "-t", + "--target", + type=str, + help="target material", + dest="target", + default="iron", + ) + ap1.add_argument( + "-o", + "--output", + type=str, + help="output directory", + dest="work_dir", + default=None, + ) + args = parser.parse_args() + return args + + +args = get_arguments() # getting options + +print("Target type: ", args.target) + +if args.target == "iron": + targetcode = "1000260560" +elif args.target == "lead": + targetcode = ( + "1000822040[0.014],1000822060[0.241],1000822070[0.221],1000822080[0.524]" + ) +elif args.target == "tungsten": + targetcode = "1000741840" else: - print('only iron, lead and tunsgten target options available') - 1/0 + print("only iron, lead and tunsgten target options available") + 1 / 0 -if os.path.exists(args.work_dir): #if the directory is already there, leave a warning, otherwise create it - print('output directory already exists.') +if os.path.exists( + args.work_dir +): # if the directory is already there, leave a warning, otherwise create it + print("output directory already exists.") else: os.makedirs(args.work_dir) os.chdir(args.work_dir) + def makeSplines(): - '''first step, make cross section splines if not exist''' - nupdglist = [16,-16,14,-14,12,-12] - genie_interface.make_splines(nupdglist, targetcode, 400, nknots = 500, outputfile = "xsec_splines.xml") - -def makeEvents(nevents = 100): - run = 11 - for p in pDict: - if p<0: print("scale number of "+sDict[p]+" events with %5.2F"%(1./nuOverNubar[abs(p)])) - if not sDict[p] in os.listdir('.'): call('mkdir '+sDict[p],shell = True) - os.chdir('./'+sDict[p]) - # stop at 350 GeV, otherwise strange warning about "Lower energy neutrinos have a higher probability of - # interacting than those at higher energy. pmaxLow(E=386.715)=2.157e-13 and pmaxHigh(E=388.044)=2.15623e-13" - N = nevents - if p<0: N = int(nevents / nuOverNubar[abs(p)]) - genie_interface.generate_genie_events(nevents = N, nupdg = p, targetcode = targetcode, emin = 0.5, emax = 350,\ - inputflux = neutrinos, spline = splines, seed = args.seed, process = args.evtype, irun = run) - run +=1 - os.chdir('../') + """first step, make cross section splines if not exist""" + nupdglist = [16, -16, 14, -14, 12, -12] + genie_interface.make_splines( + nupdglist, targetcode, 400, nknots=500, outputfile="xsec_splines.xml" + ) + + +def makeEvents(nevents=100): + run = 11 + for p in pDict: + if p < 0: + print( + "scale number of " + + sDict[p] + + " events with %5.2F" % (1.0 / nuOverNubar[abs(p)]) + ) + if not sDict[p] in os.listdir("."): + call("mkdir " + sDict[p], shell=True) + os.chdir("./" + sDict[p]) + # stop at 350 GeV, otherwise strange warning about "Lower energy neutrinos have a higher probability of + # interacting than those at higher energy. pmaxLow(E=386.715)=2.157e-13 and pmaxHigh(E=388.044)=2.15623e-13" + N = nevents + if p < 0: + N = int(nevents / nuOverNubar[abs(p)]) + genie_interface.generate_genie_events( + nevents=N, + nupdg=p, + targetcode=targetcode, + emin=0.5, + emax=350, + inputflux=neutrinos, + spline=splines, + seed=args.seed, + process=args.evtype, + irun=run, + ) + run += 1 + os.chdir("../") + + def makeNtuples(): - for p in pDict: - os.chdir('./'+sDict[p]) - genie_interface.make_ntuples("gntp.0.ghep.root","genie-"+sDict[p]+".root") - genie_interface.add_hists(neutrinos, "genie-"+sDict[p]+".root", p) - os.chdir('../') + for p in pDict: + os.chdir("./" + sDict[p]) + genie_interface.make_ntuples("gntp.0.ghep.root", "genie-" + sDict[p] + ".root") + genie_interface.add_hists(neutrinos, "genie-" + sDict[p] + ".root", p) + os.chdir("../") + def addHists(): - for p in pDict: - os.chdir('./'+sDict[p]) - genie_interface.add_hists(neutrinos, "genie-"+sDict[p]+".root", p) - os.chdir('../') + for p in pDict: + os.chdir("./" + sDict[p]) + genie_interface.add_hists(neutrinos, "genie-" + sDict[p] + ".root", p) + os.chdir("../") -if ("splinedir" not in args): - makeSplines() -else: +if "splinedir" not in args: + makeSplines() - if args.nudet: - if 'GXMLPATH' not in os.environ: - logging.warn('GXMLPATH is not set: Genie will decay charm and tau particles, which is usually not the desired behaviour') - else: logging.debug('GXMLPATH is set: Genie will not decay charm and tau particles') - - splines = args.splinedir+'/'+xsec #path of splines - neutrinos = args.filedir+'/'+hfile #path of flux - - print('Seed used in this generation: ', args.seed) - print('Splines file used', xsec) - - pdg = ROOT.TDatabasePDG() - pDict = {} - sDict = {} - nuOverNubar = {} - f = ROOT.TFile(neutrinos) - - for x in [16, 14,12]: - sDict[x] = pdg.GetParticle(x).GetName() - sDict[-x] = pdg.GetParticle(-x).GetName() - pDict[x] = "10"+str(x) - pDict[-x] = "20"+str(x) - nuOverNubar[x] = f.Get(pDict[x]).GetSumOfWeights()/f.Get(pDict[-x]).GetSumOfWeights() - f.Close() - - makeEvents(args.nevents) - makeNtuples() +else: + if args.nudet: + if "GXMLPATH" not in os.environ: + logging.warn( + "GXMLPATH is not set: Genie will decay charm and tau particles, which is usually not the desired behaviour" + ) + else: + logging.debug( + "GXMLPATH is set: Genie will not decay charm and tau particles" + ) + + splines = args.splinedir + "/" + xsec # path of splines + neutrinos = args.filedir + "/" + hfile # path of flux + + print("Seed used in this generation: ", args.seed) + print("Splines file used", xsec) + + pdg = ROOT.TDatabasePDG() + pDict = {} + sDict = {} + nuOverNubar = {} + f = ROOT.TFile(neutrinos) + + for x in [16, 14, 12]: + sDict[x] = pdg.GetParticle(x).GetName() + sDict[-x] = pdg.GetParticle(-x).GetName() + pDict[x] = "10" + str(x) + pDict[-x] = "20" + str(x) + nuOverNubar[x] = ( + f.Get(pDict[x]).GetSumOfWeights() / f.Get(pDict[-x]).GetSumOfWeights() + ) + f.Close() + + makeEvents(args.nevents) + makeNtuples() diff --git a/macro/mergeMbias.py b/macro/mergeMbias.py index 7feb051382..ba8086d926 100644 --- a/macro/mergeMbias.py +++ b/macro/mergeMbias.py @@ -1,129 +1,188 @@ -import ROOT,os,random -import shipunit as u +import os +import random +from array import array + +import ROOT import rootUtils as ut +import shipunit as u from ShipGeoConfig import ConfigRegistry -from array import array -pdg = ROOT.TDatabasePDG() -mu = pdg.GetParticle(13) -Mmu = mu.Mass() +pdg = ROOT.TDatabasePDG() +mu = pdg.GetParticle(13) +Mmu = mu.Mass() Mmu2 = Mmu * Mmu -rnr = ROOT.TRandom() -eospath = ROOT.gSystem.Getenv("EOSSHIP")+"/eos/experiment/ship/data/" -ship_geo = ConfigRegistry.loadpy("$FAIRSHIP/geometry/geometry_config.py", Yheight = 10.) -endOfHadronAbsorber = (ship_geo['hadronAbsorber'].z + ship_geo['hadronAbsorber'].length/2.) /100. -startOfTarget = -50. # value used for Geant4 production +rnr = ROOT.TRandom() +eospath = ROOT.gSystem.Getenv("EOSSHIP") + "/eos/experiment/ship/data/" +ship_geo = ConfigRegistry.loadpy("$FAIRSHIP/geometry/geometry_config.py", Yheight=10.0) +endOfHadronAbsorber = ( + ship_geo["hadronAbsorber"].z + ship_geo["hadronAbsorber"].length / 2.0 +) / 100.0 +startOfTarget = -50.0 # value used for Geant4 production + def fillPart(t): - particles = {} - for n in range(t.GetEntries()): - rc = t.GetEvent(n) - if t.parentid not in particles : - particles[t.parentid] = 0 - particles[t.parentid] +=1 - return particles + particles = {} + for n in range(t.GetEntries()): + rc = t.GetEvent(n) + if t.parentid not in particles: + particles[t.parentid] = 0 + particles[t.parentid] += 1 + return particles + + # def fillWeights(): - weights = {} - for p in productions: - f = ROOT.TFile.Open(eospath+productions[p]["file"]) - t = f.FindObjectAny("pythia8-Geant4") - weights[p]={} - for n in range(t.GetEntries()): - rc = t.GetEvent(n) - if t.w not in weights[p] : - weights[p][t.w] = [t.ecut,0] - weights[p][t.w][1] +=1 - if t.ecut > weights[p][t.w][0] : weights[p][t.w][0] = t.ecut - return weights + weights = {} + for p in productions: + f = ROOT.TFile.Open(eospath + productions[p]["file"]) + t = f.FindObjectAny("pythia8-Geant4") + weights[p] = {} + for n in range(t.GetEntries()): + rc = t.GetEvent(n) + if t.w not in weights[p]: + weights[p][t.w] = [t.ecut, 0] + weights[p][t.w][1] += 1 + if t.ecut > weights[p][t.w][0]: + weights[p][t.w][0] = t.ecut + return weights + def TplotP(sTree): - ut.bookCanvas(h,key='P',title='momentum',nx=1800,ny=1200,cx=3,cy=2) - ut.bookCanvas(h,key='>P',title='N >P', nx=1800,ny=1200,cx=3,cy=2) - ut.bookCanvas(h,key='PT',title='Pt',nx=1800,ny=1200,cx=3,cy=2) - ut.bookCanvas(h,key='>PT',title='N >Pt', nx=1800,ny=1200,cx=3,cy=2) - cuts = {'mu':'abs(id)==13','nu':'abs(id)!=13','mu-':'id==13','mu+':'id==-13', - 'nutau':'id==16','nutaubar':'id==-16','numu':'id==14','numubar':'id==-14', - 'nue':'id==12','nuebar':'id==-12','nuesum':'abs(id)==12','numusum':'abs(id)==14','nutausum':'abs(id)==16'} - OpenCharm = {'':'','charm':"&(pythiaid==id & (abs(parentid) == 15 || abs(parentid) == 4112 || abs(parentid) == 4122 || abs(parentid) == 4132 \ - || abs(parentid) == 431 || abs(parentid) == 421 || abs(parentid) == 411) )"} - ROOT.gROOT.cd('') - for x in ['','charm']: - for q in cuts: - p = q+x - hn = 'Tp'+p - hnt = 'Tpt'+p - ut.bookHist(h,hn, p +' ;p [GeV] ;N',400,0.0,400.0) - ut.bookHist(h,hnt, p +' ;pt [GeV] ;N',40,0.0,4.0) - sTree.Draw('sqrt(px**2+py**2+pz**2)>>'+hn,'w*('+cuts[q]+OpenCharm[x]+')','goff') - sTree.Draw('sqrt(px**2+py**2)>>'+hnt,'w*('+cuts[q]+OpenCharm[x]+')','goff') - if q=='mu+': h[hn].SetLineColor(3) - if q=='mu-': h[hn].SetLineColor(4) -# integrated rates - for q in [ 'mu','mu-','mu+','nu','nue','nuesum','nuebar','numusum','numu','numubar','nutau','nutaubar']: - for x in ['','charm']: - for z in ['p','pt']: - p = z+q+x - hi = 'T'+p+'_>E' - h[hi]=h['T'+p].Clone(hi) - h[hi].Reset() - nsum = 0 - for i in range(h[hi].GetNbinsX()+1,0,-1): - nsum+=h['T'+p].GetBinContent(i) - h[hi].SetBinContent(i,nsum) - for z in ['p','pt']: - k = 1 - for x in [ 'mu','nu']: - t=z.upper() - p=z+x - cv = h[t].cd(k) - cv.SetLogy(1) - h['T'+p].Draw() - if h['T'+p].GetEntries()<1: continue - if not p.find('mu')<0: - h['T'+p+'+'].Draw('same') - h['T'+p+'-'].Draw('same') - cv = h['>'+t].cd(k) - cv.SetLogy(1) - h[hi].Draw() - k+=1 -# plot different nu species: - k = 3 - cv = h[t].cd(k) - cv.SetLogy(1) - first = True - i = 2 - h['tlnu'+z+str(k)] = ROOT.TLegend(0.49,0.13,0.88,0.36) - for p in ['numu','numubar','nue','nuebar','nutau','nutaubar']: - hn = 'T'+z+p - h['tlnu'+z+str(k)].AddEntry(h[hn],z+' '+p,'PL') - h[hn].SetLineColor(i) - h[hn+'8']=h[hn].Clone() - h[hn+'8'].SetName(hn+'8') - h[hn+'8'].Rebin(8) - i+=1 - if first: - h[hn+'8'].Draw() - first = False - h[hn+'8'].Draw('same') - h['tlnu'+z+str(k)].Draw() - k+=1 + ut.bookCanvas(h, key="P", title="momentum", nx=1800, ny=1200, cx=3, cy=2) + ut.bookCanvas(h, key=">P", title="N >P", nx=1800, ny=1200, cx=3, cy=2) + ut.bookCanvas(h, key="PT", title="Pt", nx=1800, ny=1200, cx=3, cy=2) + ut.bookCanvas(h, key=">PT", title="N >Pt", nx=1800, ny=1200, cx=3, cy=2) + cuts = { + "mu": "abs(id)==13", + "nu": "abs(id)!=13", + "mu-": "id==13", + "mu+": "id==-13", + "nutau": "id==16", + "nutaubar": "id==-16", + "numu": "id==14", + "numubar": "id==-14", + "nue": "id==12", + "nuebar": "id==-12", + "nuesum": "abs(id)==12", + "numusum": "abs(id)==14", + "nutausum": "abs(id)==16", + } + OpenCharm = { + "": "", + "charm": "&(pythiaid==id & (abs(parentid) == 15 || abs(parentid) == 4112 || abs(parentid) == 4122 || abs(parentid) == 4132 \ + || abs(parentid) == 431 || abs(parentid) == 421 || abs(parentid) == 411) )", + } + ROOT.gROOT.cd("") + for x in ["", "charm"]: + for q in cuts: + p = q + x + hn = "Tp" + p + hnt = "Tpt" + p + ut.bookHist(h, hn, p + " ;p [GeV] ;N", 400, 0.0, 400.0) + ut.bookHist(h, hnt, p + " ;pt [GeV] ;N", 40, 0.0, 4.0) + sTree.Draw( + "sqrt(px**2+py**2+pz**2)>>" + hn, + "w*(" + cuts[q] + OpenCharm[x] + ")", + "goff", + ) + sTree.Draw( + "sqrt(px**2+py**2)>>" + hnt, + "w*(" + cuts[q] + OpenCharm[x] + ")", + "goff", + ) + if q == "mu+": + h[hn].SetLineColor(3) + if q == "mu-": + h[hn].SetLineColor(4) + # integrated rates + for q in [ + "mu", + "mu-", + "mu+", + "nu", + "nue", + "nuesum", + "nuebar", + "numusum", + "numu", + "numubar", + "nutau", + "nutaubar", + ]: + for x in ["", "charm"]: + for z in ["p", "pt"]: + p = z + q + x + hi = "T" + p + "_>E" + h[hi] = h["T" + p].Clone(hi) + h[hi].Reset() + nsum = 0 + for i in range(h[hi].GetNbinsX() + 1, 0, -1): + nsum += h["T" + p].GetBinContent(i) + h[hi].SetBinContent(i, nsum) + for z in ["p", "pt"]: + k = 1 + for x in ["mu", "nu"]: + t = z.upper() + p = z + x + cv = h[t].cd(k) + cv.SetLogy(1) + h["T" + p].Draw() + if h["T" + p].GetEntries() < 1: + continue + if not p.find("mu") < 0: + h["T" + p + "+"].Draw("same") + h["T" + p + "-"].Draw("same") + cv = h[">" + t].cd(k) + cv.SetLogy(1) + h[hi].Draw() + k += 1 + # plot different nu species: + k = 3 + cv = h[t].cd(k) + cv.SetLogy(1) + first = True + i = 2 + h["tlnu" + z + str(k)] = ROOT.TLegend(0.49, 0.13, 0.88, 0.36) + for p in ["numu", "numubar", "nue", "nuebar", "nutau", "nutaubar"]: + hn = "T" + z + p + h["tlnu" + z + str(k)].AddEntry(h[hn], z + " " + p, "PL") + h[hn].SetLineColor(i) + h[hn + "8"] = h[hn].Clone() + h[hn + "8"].SetName(hn + "8") + h[hn + "8"].Rebin(8) + i += 1 + if first: + h[hn + "8"].Draw() + first = False + h[hn + "8"].Draw("same") + h["tlnu" + z + str(k)].Draw() + k += 1 + + # productions = {} allProds = False if allProds: - productions["CERN-Cracow"] = {"stats":{1.:[1.1E8],10.:[1.22E9],100:[1.27E10]}, - "file":"Mbias/pythia8_Geant4_total.root" } -# checked, 10 variables, parentid = 8 - productions["Yandex"] = {"stats":{5.:[2.1E9,1E9],0.5:[1E8]}, - "file":"Mbias/pythia8_Geant4_total_Yandex.root" } -# checked, 13 variables, parentid = 11 - productions["Yandex2"] = {"stats":{10.:[1E10]}, - "file":"Mbias/pythia8_Geant4_total_Yandex2.root" } + productions["CERN-Cracow"] = { + "stats": {1.0: [1.1e8], 10.0: [1.22e9], 100: [1.27e10]}, + "file": "Mbias/pythia8_Geant4_total.root", + } + # checked, 10 variables, parentid = 8 + productions["Yandex"] = { + "stats": {5.0: [2.1e9, 1e9], 0.5: [1e8]}, + "file": "Mbias/pythia8_Geant4_total_Yandex.root", + } + # checked, 13 variables, parentid = 11 + productions["Yandex2"] = { + "stats": {10.0: [1e10]}, + "file": "Mbias/pythia8_Geant4_total_Yandex2.root", + } # now with mu momentum at prodcution, NOT after hadron absorber -productions["Yandex3"] = {"stats":{10.:[1E10]}, - "file":"Mbias/pythia8_Geant4_total_Yandex3.root" } +productions["Yandex3"] = { + "stats": {10.0: [1e10]}, + "file": "Mbias/pythia8_Geant4_total_Yandex3.root", +} # checked, 13 variables, parentid = 11 fnew = "pythia8_Geant4-noOpenCharm.root" @@ -131,416 +190,593 @@ def TplotP(sTree): || abs(parentid) == 431 || abs(parentid) == 421 || abs(parentid) == 411) )" OpCharm = "(pythiaid==id & (abs(parentid) == 15 || abs(parentid) == 4112 || abs(parentid) == 4122 || abs(parentid) == 4132 \ || abs(parentid) == 431 || abs(parentid) == 421 || abs(parentid) == 411) )" -cuts = {'':'abs(id)>0','_onlyMuons':'abs(id)==13','_onlyNeutrinos':'abs(id)==12||abs(id)==14||abs(id)==16'} +cuts = { + "": "abs(id)>0", + "_onlyMuons": "abs(id)==13", + "_onlyNeutrinos": "abs(id)==12||abs(id)==14||abs(id)==16", +} -h={} +h = {} -def mergeMinBias(pot,norm=5.E13,opt=''): - storeCharm=False - if opt != '': - storeCharm=True - opt='' - first = True - for p in productions: - f = ROOT.TFile.Open(eospath+productions[p]["file"]) - t = f.FindObjectAny("pythia8-Geant4") - if first: - first = False - tuples = '' - for l in t.GetListOfLeaves(): - if tuples == '': tuples += l.GetName() - else: tuples += ":"+l.GetName() - fxx = fnew.replace('.root',opt+'.root') - if storeCharm: fxx = fnew.replace('.root','old-charm.root') - h['N'] = ROOT.TFile(fxx, 'RECREATE') - print('new file created',fxx) - h['ntuple'] = ROOT.TNtuple("pythia8-Geant4","min bias flux after 3m hadron absorber "+opt,tuples) - ROOT.gROOT.cd() - t.SetEventList(0) - if storeCharm: t.Draw(">>temp",cuts[opt]+"&"+OpCharm) - else: t.Draw(">>temp",cuts[opt]+"&"+noOpCharm) - temp = ROOT.gROOT.FindObjectAny('temp') - t.SetEventList(temp) - nev = temp.GetN() - leaves = t.GetListOfLeaves() - nL = leaves.GetEntries() - for iev in range(nev) : - rc = t.GetEntry(temp.GetEntry(iev)) - vlist = [] - k=-1 - for x in range(nL): - k+=1 - if nL > 11 and (k==7 or k==8 or k==9): continue - vlist.append( leaves.At(x).GetValue() ) - if len(vlist) != 11 : - print("this should never happen, big error",len(vlist),k,p,iev,nev) - 1/0 - # "id:px:py:pz:x:y:z:pythiaid:parentid:w:ecut" - # yandex productions have - # "id:px:py:pz:x:y:z:ox:oy:oz:pythiaid:parentid:w:ecut" - Psq = vlist[1]**2+vlist[2]**2+vlist[3]**2 - if abs(vlist[0])==13: Ekin = ROOT.TMath.Sqrt(Mmu2+Psq)-Mmu - else: Ekin = ROOT.TMath.Sqrt(Psq) - # re calculate weights - # pot = 5E13/w - # E > 100 GeV: add all pots -> w = 5E13/pot - # w = norm/( pot["CERN-Cracow"][100.] + productions["Yandex"][5.] + productions["Yandex2"][10.] ) - # E < 100 & E > 10 GeV - # w = norm/( pot["CERN-Cracow"][10.] + productions["Yandex"][5.] + productions["Yandex2"][10.] ) - # E < 10 & E > 5 GeV - # w = norm/( pot["CERN-Cracow"][1.] + productions["Yandex"][5.] ) - # E < 5 GeV & E > 1 GeV - # w = norm/( pot["CERN-Cracow"][1.] + productions["Yandex"][0.5] ) - # E < 1 GeV & E > 0.5 GeV - # w = norm/( productions["Yandex"][0.5] ) - if Ekin > 100. : - vlist[9] = norm/( pot["CERN-Cracow"][100.] + pot["Yandex"][5.] + pot["Yandex2"][10.] ) - elif Ekin > 10. : - vlist[9] = norm/( pot["CERN-Cracow"][10.] + pot["Yandex"][5.] + pot["Yandex2"][10.] ) - elif Ekin > 5. : - vlist[9] = norm/( pot["CERN-Cracow"][1.] + pot["Yandex"][5.] ) - elif Ekin > 1. : - vlist[9] = norm/( pot["CERN-Cracow"][1.] + pot["Yandex"][0.5] ) - elif Ekin > 0.5 : - vlist[9] = norm/( pot["Yandex"][0.5] ) - else : - print("this should not happen, except some rounding errors",p,Ekin,vlist[9]) -# scoring plane, g4Ex_gap: afterHadronZ = z0Pos+targetL+absorberL+5.1*cm -# z0Pos = -50.*m absorberL = 2*150.*cm -# target length increased for Yandex2 production, ignore this, put all muons at current end of hadronabsorber - vlist[6] = endOfHadronAbsorber - h['ntuple'].Fill(vlist[0],vlist[1],vlist[2],vlist[3],vlist[4],vlist[5],vlist[6], - vlist[7],vlist[8],vlist[9],vlist[10]) - h['N'].cd() - h['ntuple'].Write() - h['N'].Close() -def runProduction(opts=''): - we = fillWeights() - pot = {} - norm = 5.E13 - for p in we: - pot[p]={} - for w in we[p]: - pot[p][we[p][w][0]] = 5.E13/w - print("pots:",pot) - # - mergeMinBias(pot,norm=5.E13,opt=opts) +def mergeMinBias(pot, norm=5.0e13, opt=""): + storeCharm = False + if opt != "": + storeCharm = True + opt = "" + first = True + for p in productions: + f = ROOT.TFile.Open(eospath + productions[p]["file"]) + t = f.FindObjectAny("pythia8-Geant4") + if first: + first = False + tuples = "" + for l in t.GetListOfLeaves(): + if tuples == "": + tuples += l.GetName() + else: + tuples += ":" + l.GetName() + fxx = fnew.replace(".root", opt + ".root") + if storeCharm: + fxx = fnew.replace(".root", "old-charm.root") + h["N"] = ROOT.TFile(fxx, "RECREATE") + print("new file created", fxx) + h["ntuple"] = ROOT.TNtuple( + "pythia8-Geant4", + "min bias flux after 3m hadron absorber " + opt, + tuples, + ) + ROOT.gROOT.cd() + t.SetEventList(0) + if storeCharm: + t.Draw(">>temp", cuts[opt] + "&" + OpCharm) + else: + t.Draw(">>temp", cuts[opt] + "&" + noOpCharm) + temp = ROOT.gROOT.FindObjectAny("temp") + t.SetEventList(temp) + nev = temp.GetN() + leaves = t.GetListOfLeaves() + nL = leaves.GetEntries() + for iev in range(nev): + rc = t.GetEntry(temp.GetEntry(iev)) + vlist = [] + k = -1 + for x in range(nL): + k += 1 + if nL > 11 and (k == 7 or k == 8 or k == 9): + continue + vlist.append(leaves.At(x).GetValue()) + if len(vlist) != 11: + print("this should never happen, big error", len(vlist), k, p, iev, nev) + 1 / 0 + # "id:px:py:pz:x:y:z:pythiaid:parentid:w:ecut" + # yandex productions have + # "id:px:py:pz:x:y:z:ox:oy:oz:pythiaid:parentid:w:ecut" + Psq = vlist[1] ** 2 + vlist[2] ** 2 + vlist[3] ** 2 + if abs(vlist[0]) == 13: + Ekin = ROOT.TMath.Sqrt(Mmu2 + Psq) - Mmu + else: + Ekin = ROOT.TMath.Sqrt(Psq) + # re calculate weights + # pot = 5E13/w + # E > 100 GeV: add all pots -> w = 5E13/pot + # w = norm/( pot["CERN-Cracow"][100.] + productions["Yandex"][5.] + productions["Yandex2"][10.] ) + # E < 100 & E > 10 GeV + # w = norm/( pot["CERN-Cracow"][10.] + productions["Yandex"][5.] + productions["Yandex2"][10.] ) + # E < 10 & E > 5 GeV + # w = norm/( pot["CERN-Cracow"][1.] + productions["Yandex"][5.] ) + # E < 5 GeV & E > 1 GeV + # w = norm/( pot["CERN-Cracow"][1.] + productions["Yandex"][0.5] ) + # E < 1 GeV & E > 0.5 GeV + # w = norm/( productions["Yandex"][0.5] ) + if Ekin > 100.0: + vlist[9] = norm / ( + pot["CERN-Cracow"][100.0] + + pot["Yandex"][5.0] + + pot["Yandex2"][10.0] + ) + elif Ekin > 10.0: + vlist[9] = norm / ( + pot["CERN-Cracow"][10.0] + pot["Yandex"][5.0] + pot["Yandex2"][10.0] + ) + elif Ekin > 5.0: + vlist[9] = norm / (pot["CERN-Cracow"][1.0] + pot["Yandex"][5.0]) + elif Ekin > 1.0: + vlist[9] = norm / (pot["CERN-Cracow"][1.0] + pot["Yandex"][0.5]) + elif Ekin > 0.5: + vlist[9] = norm / (pot["Yandex"][0.5]) + else: + print( + "this should not happen, except some rounding errors", + p, + Ekin, + vlist[9], + ) + # scoring plane, g4Ex_gap: afterHadronZ = z0Pos+targetL+absorberL+5.1*cm + # z0Pos = -50.*m absorberL = 2*150.*cm + # target length increased for Yandex2 production, ignore this, put all muons at current end of hadronabsorber + vlist[6] = endOfHadronAbsorber + h["ntuple"].Fill( + vlist[0], + vlist[1], + vlist[2], + vlist[3], + vlist[4], + vlist[5], + vlist[6], + vlist[7], + vlist[8], + vlist[9], + vlist[10], + ) + h["N"].cd() + h["ntuple"].Write() + h["N"].Close() -def removeCharm(p): - f = ROOT.TFile.Open(eospath+productions[p]["file"]) - t = f.FindObjectAny("pythia8-Geant4") - first = True - if first: - first = False - tuples = '' - for l in t.GetListOfLeaves(): - if tuples == '': tuples += l.GetName() - else: tuples += ":"+l.GetName() - h['N'] = ROOT.TFile(fnew, 'RECREATE') - print('new file created',fnew) - h['ntuple'] = ROOT.TNtuple("pythia8-Geant4",t.GetTitle()+" no charm",tuples) - ROOT.gROOT.cd() - t.SetEventList(0) - t.Draw(">>temp",noOpCharm) - temp = ROOT.gROOT.FindObjectAny('temp') - t.SetEventList(temp) - nev = temp.GetN() - leaves = t.GetListOfLeaves() - nL = leaves.GetEntries() - for iev in range(nev): - rc = t.GetEntry(temp.GetEntry(iev)) - vlist = array('f') - for x in range(leaves.GetEntries()): - vlist.append( leaves.At(x).GetValue() ) - h['ntuple'].Fill(vlist) - h['N'].cd() - h['ntuple'].Write() - h['N'].Close() -def mergeWithCharm(splitOnly=False,ramOnly=False): - # Ntup.Fill(par.id(),par.px(),par.py(),par.pz(),par.e(),par.m(),wspill,sTree.id,sTree.px,sTree.py,sTree.pz,sTree.E,sTree.M) - # i.e. the par. is for the neutrino, and the sTree. is for its mother. - # wspill is the weight for this file normalised/5e13. - if not splitOnly: - fcascade = ROOT.TFile.Open(eospath+"/Charm/Decay-Cascade-parp16-MSTP82-1-MSEL4-76Mpot_1.root") - t = fcascade.Decay - newFile = ROOT.TFile("pythia8_Charm.root", 'RECREATE') - nt = ROOT.TNtuple("pythia8-Geant4","mu/nu flux from charm","id:px:py:pz:x:y:z:opx:opy:opz:ox:oy:oz:pythiaid:parentid:w:ecut") - for n in range(t.GetEntries()): - rc = t.GetEntry(n) - ztarget = rnr.Exp(0.16) + startOfTarget - vlist = array('f') - x = t.id,t.px,t.py,t.pz,0.,0.,ztarget,t.px,t.py,t.pz,0.,0.,ztarget,t.id,t.mid,t.weight,0. - for ax in x: vlist.append(ax) - rc = nt.Fill(vlist) - newFile.cd() - nt.Write() - newFile.Close() - fcascade.Close() - os.system("hadd -f pythia8_Geant4-withCharm.root pythia8_Geant4-noOpenCharm.root pythia8_Charm.root") - print(" progress: minbias and charm merged") - ramOnly = True - if ramOnly: -# put all events in memory, otherwise will take years to finish - event = ROOT.std.vector("float") - f = ROOT.TFile("pythia8_Geant4-withCharm.root") - t = f.FindObjectAny('pythia8-Geant4') - leaves = t.GetListOfLeaves() - L = leaves.GetEntries() - m=0 - allEvents = [] - for n in range(t.GetEntries()): - rc = t.GetEvent(n) - if m%1000000==0 : print('status read',m) - m+=1 - a = event() - for l in range(L): a.push_back(leaves.At(l).GetValue()) - allEvents.append(a) -# distribute events randomly - evList = [] - for n in range(len(allEvents)): evList.append(n) - random.shuffle(evList) - leaves = t.GetListOfLeaves() - tuples = '' - for l in leaves: - if tuples=='': tuples += l.GetName() - else: tuples += ":"+l.GetName() - newFile = ROOT.TFile("pythia8_Geant4-withCharm-ram.root", 'RECREATE') - randomTuple = ROOT.TNtuple(t.GetName(),t.GetTitle(),tuples) - m=0 - for n in evList: - a = allEvents[n] - if m%1000000==0 : print('status write',m) - m+=1 - vlist = array('f') - for x in a: vlist.append(x) - randomTuple.Fill(vlist) - newFile.cd() - randomTuple.Write() - newFile.Close() - f.Close() - allEvents = [] - print(" progress: order of events randomized") - if 1>0: -# split in muons and neutrinos - cuts = {'_onlyNeutrinos':'abs(id)==12||abs(id)==14||abs(id)==16','_onlyMuons':'abs(id)==13'} - fName = "pythia8_Geant4-withCharm-ram.root" - f = ROOT.TFile(fName) - t = f.FindObjectAny("pythia8-Geant4") - tuples = '' -# add histograms - for idnu in [16,-16,14,-14,12,-12]: - name = pdg.GetParticle(idnu).GetName() - idhnu=1000+idnu - if idnu < 0: idhnu=2000+abs(idnu) - ut.bookHist(h,str(idhnu),name+' momentum (GeV)',400,0.,400.) - ut.bookHist(h,str(idhnu+100),name+' log10(ptot) vs log10(pt+0.01)',100,-0.3,1.7,100,-2.,1.) - ut.bookHist(h,str(idhnu+200),name+' log10(ptot) vs log10(pt+0.01)',25,-0.3,1.7,100,-2.,1.) - leaves = t.GetListOfLeaves() - for l in leaves: - if tuples == '': tuples += l.GetName() - else: tuples += ":"+l.GetName() - for opt in cuts: - fxx = fName.replace('-ram.root',opt+'.root') - N = ROOT.TFile(fxx, 'RECREATE') - ntuple = ROOT.TNtuple("pythia8-Geant4",opt.replace("_only","")+" flux mbias and charm"+opt,tuples) +def runProduction(opts=""): + we = fillWeights() + pot = {} + norm = 5.0e13 + for p in we: + pot[p] = {} + for w in we[p]: + pot[p][we[p][w][0]] = 5.0e13 / w + print("pots:", pot) + # + mergeMinBias(pot, norm=5.0e13, opt=opts) + + +def removeCharm(p): + f = ROOT.TFile.Open(eospath + productions[p]["file"]) + t = f.FindObjectAny("pythia8-Geant4") + first = True + if first: + first = False + tuples = "" + for l in t.GetListOfLeaves(): + if tuples == "": + tuples += l.GetName() + else: + tuples += ":" + l.GetName() + h["N"] = ROOT.TFile(fnew, "RECREATE") + print("new file created", fnew) + h["ntuple"] = ROOT.TNtuple("pythia8-Geant4", t.GetTitle() + " no charm", tuples) ROOT.gROOT.cd() t.SetEventList(0) - t.Draw(">>temp",cuts[opt]) - temp = ROOT.gROOT.FindObjectAny('temp') + t.Draw(">>temp", noOpCharm) + temp = ROOT.gROOT.FindObjectAny("temp") t.SetEventList(temp) - for iev in range(temp.GetN()) : - rc = t.GetEntry(temp.GetEntry(iev)) - vlist = array('f') - for n in range(leaves.GetSize()): - vlist.append(leaves.At(n).GetValue()) - ntuple.Fill(vlist) - if "Neutrinos" in opt: - pt2=t.px**2+t.py**2 - ptot=ROOT.TMath.Sqrt(pt2+t.pz**2) - l10ptot=min(max(ROOT.TMath.Log10(ptot),-0.3),1.69999) - l10pt=min(ROOT.TMath.Log10(ROOT.TMath.Sqrt(pt2)+0.01),0.9999) - idnu = int(t.id) - idhnu=1000+idnu - if idnu < 0: idhnu=2000+abs(idnu) - h[str(idhnu)].Fill(ptot,t.w) - h[str(idhnu+100)].Fill(l10ptot,l10pt,t.w) - h[str(idhnu+200)].Fill(l10ptot,l10pt,t.w) -# - N.cd() - ntuple.Write() - if "Neutrinos" in opt: - for akey in h: - cln = h[akey].Class().GetName() - if not cln.find('TH')<0: h[akey].Write() - N.Close() - print(" progress: splitted "+opt) + nev = temp.GetN() + leaves = t.GetListOfLeaves() + nL = leaves.GetEntries() + for iev in range(nev): + rc = t.GetEntry(temp.GetEntry(iev)) + vlist = array("f") + for x in range(leaves.GetEntries()): + vlist.append(leaves.At(x).GetValue()) + h["ntuple"].Fill(vlist) + h["N"].cd() + h["ntuple"].Write() + h["N"].Close() + + +def mergeWithCharm(splitOnly=False, ramOnly=False): + # Ntup.Fill(par.id(),par.px(),par.py(),par.pz(),par.e(),par.m(),wspill,sTree.id,sTree.px,sTree.py,sTree.pz,sTree.E,sTree.M) + # i.e. the par. is for the neutrino, and the sTree. is for its mother. + # wspill is the weight for this file normalised/5e13. + if not splitOnly: + fcascade = ROOT.TFile.Open( + eospath + "/Charm/Decay-Cascade-parp16-MSTP82-1-MSEL4-76Mpot_1.root" + ) + t = fcascade.Decay + newFile = ROOT.TFile("pythia8_Charm.root", "RECREATE") + nt = ROOT.TNtuple( + "pythia8-Geant4", + "mu/nu flux from charm", + "id:px:py:pz:x:y:z:opx:opy:opz:ox:oy:oz:pythiaid:parentid:w:ecut", + ) + for n in range(t.GetEntries()): + rc = t.GetEntry(n) + ztarget = rnr.Exp(0.16) + startOfTarget + vlist = array("f") + x = ( + t.id, + t.px, + t.py, + t.pz, + 0.0, + 0.0, + ztarget, + t.px, + t.py, + t.pz, + 0.0, + 0.0, + ztarget, + t.id, + t.mid, + t.weight, + 0.0, + ) + for ax in x: + vlist.append(ax) + rc = nt.Fill(vlist) + newFile.cd() + nt.Write() + newFile.Close() + fcascade.Close() + os.system( + "hadd -f pythia8_Geant4-withCharm.root pythia8_Geant4-noOpenCharm.root pythia8_Charm.root" + ) + print(" progress: minbias and charm merged") + ramOnly = True + if ramOnly: + # put all events in memory, otherwise will take years to finish + event = ROOT.std.vector("float") + f = ROOT.TFile("pythia8_Geant4-withCharm.root") + t = f.FindObjectAny("pythia8-Geant4") + leaves = t.GetListOfLeaves() + L = leaves.GetEntries() + m = 0 + allEvents = [] + for n in range(t.GetEntries()): + rc = t.GetEvent(n) + if m % 1000000 == 0: + print("status read", m) + m += 1 + a = event() + for l in range(L): + a.push_back(leaves.At(l).GetValue()) + allEvents.append(a) + # distribute events randomly + evList = [] + for n in range(len(allEvents)): + evList.append(n) + random.shuffle(evList) + leaves = t.GetListOfLeaves() + tuples = "" + for l in leaves: + if tuples == "": + tuples += l.GetName() + else: + tuples += ":" + l.GetName() + newFile = ROOT.TFile("pythia8_Geant4-withCharm-ram.root", "RECREATE") + randomTuple = ROOT.TNtuple(t.GetName(), t.GetTitle(), tuples) + m = 0 + for n in evList: + a = allEvents[n] + if m % 1000000 == 0: + print("status write", m) + m += 1 + vlist = array("f") + for x in a: + vlist.append(x) + randomTuple.Fill(vlist) + newFile.cd() + randomTuple.Write() + newFile.Close() + f.Close() + allEvents = [] + print(" progress: order of events randomized") + if 1 > 0: + # split in muons and neutrinos + cuts = { + "_onlyNeutrinos": "abs(id)==12||abs(id)==14||abs(id)==16", + "_onlyMuons": "abs(id)==13", + } + fName = "pythia8_Geant4-withCharm-ram.root" + f = ROOT.TFile(fName) + t = f.FindObjectAny("pythia8-Geant4") + tuples = "" + # add histograms + for idnu in [16, -16, 14, -14, 12, -12]: + name = pdg.GetParticle(idnu).GetName() + idhnu = 1000 + idnu + if idnu < 0: + idhnu = 2000 + abs(idnu) + ut.bookHist(h, str(idhnu), name + " momentum (GeV)", 400, 0.0, 400.0) + ut.bookHist( + h, + str(idhnu + 100), + name + " log10(ptot) vs log10(pt+0.01)", + 100, + -0.3, + 1.7, + 100, + -2.0, + 1.0, + ) + ut.bookHist( + h, + str(idhnu + 200), + name + " log10(ptot) vs log10(pt+0.01)", + 25, + -0.3, + 1.7, + 100, + -2.0, + 1.0, + ) + leaves = t.GetListOfLeaves() + for l in leaves: + if tuples == "": + tuples += l.GetName() + else: + tuples += ":" + l.GetName() + for opt in cuts: + fxx = fName.replace("-ram.root", opt + ".root") + N = ROOT.TFile(fxx, "RECREATE") + ntuple = ROOT.TNtuple( + "pythia8-Geant4", + opt.replace("_only", "") + " flux mbias and charm" + opt, + tuples, + ) + ROOT.gROOT.cd() + t.SetEventList(0) + t.Draw(">>temp", cuts[opt]) + temp = ROOT.gROOT.FindObjectAny("temp") + t.SetEventList(temp) + for iev in range(temp.GetN()): + rc = t.GetEntry(temp.GetEntry(iev)) + vlist = array("f") + for n in range(leaves.GetSize()): + vlist.append(leaves.At(n).GetValue()) + ntuple.Fill(vlist) + if "Neutrinos" in opt: + pt2 = t.px**2 + t.py**2 + ptot = ROOT.TMath.Sqrt(pt2 + t.pz**2) + l10ptot = min(max(ROOT.TMath.Log10(ptot), -0.3), 1.69999) + l10pt = min(ROOT.TMath.Log10(ROOT.TMath.Sqrt(pt2) + 0.01), 0.9999) + idnu = int(t.id) + idhnu = 1000 + idnu + if idnu < 0: + idhnu = 2000 + abs(idnu) + h[str(idhnu)].Fill(ptot, t.w) + h[str(idhnu + 100)].Fill(l10ptot, l10pt, t.w) + h[str(idhnu + 200)].Fill(l10ptot, l10pt, t.w) + # + N.cd() + ntuple.Write() + if "Neutrinos" in opt: + for akey in h: + cln = h[akey].Class().GetName() + if not cln.find("TH") < 0: + h[akey].Write() + N.Close() + print(" progress: splitted " + opt) + + def test(fname): - h['f'] = ROOT.TFile.Open(fname) - sTree = h['f'].FindObjectAny('pythia8-Geant4') - TplotP(sTree) + h["f"] = ROOT.TFile.Open(fname) + sTree = h["f"].FindObjectAny("pythia8-Geant4") + TplotP(sTree) + + def compare(): - test(eospath+'pythia8_Geant4_onlyMuons.root') - for x in ['','_>E']: - for z in ['p','pt']: - for ahist in ['mu-','mu+','mu','mu-charm','mu+charm','mucharm']: - h['TP'+z+ahist+x]=h['T'+z+ahist+x].Clone('CT'+ahist+x) - test(eospath+'pythia8_Geant4_Yandex_onlyNeutrinos.root') - for x in ['','_>E']: - for z in ['p','pt']: - for ahist in ['numusum','nuesum','numusumcharm','nuesumcharm','numu','numubar','nue','nuebar','numucharm','numubarcharm','nuecharm','nuebarcharm']: - h['TP'+z+ahist+x]=h['T'+z+ahist+x].Clone('CT'+ahist+x) - test(eospath+'Mbias/pythia8_Geant4-withCharm-ram.root') - for x in ['','_>E']: - for z in ['p','pt']: - t = z.upper() - if x != '' : t='>'+t - t1=h[t].cd(1) - p = z+'mu' - h['T'+p+x].SetTitle('musum') - h['T'+p+x].Draw() - h['T'+p+'charm'+x].Draw('same') - h['TP'+p+x].Draw('same') - h['TP'+p+x].SetLineColor(6) - h['TP'+p+'charm'+x].Draw('same') - h['TP'+p+'charm'+x].SetLineColor(3) - h['T'+p+'charm'+x].SetLineColor(2) - h['T'+p+x].SetLineColor(4) - h['L'+p+x] = ROOT.TLegend(0.33,0.69,0.99,0.94) - h['L'+p+x].AddEntry(h['T'+p+x],'muon new with charm, cascade, k-fac','PL') - h['L'+p+x].AddEntry(h['T'+p+'charm'+x],'muon from charm new with charm, cascade, k-fac','PL') - h['L'+p+x].AddEntry(h['TP'+p+x],'muon old CERN-Cracow prod','PL') - h['L'+p+x].AddEntry(h['TP'+p+'charm'+x],'muon from charm old CERN-Cracow prod','PL') - h['L'+p+x].Draw() - h[t].cd(2) - p = z+'numusum' - h['T'+p+x].Draw() - h['T'+p+'charm'+x].Draw('same') - h['TP'+p+x].Draw('same') - h['TP'+p+x].SetLineColor(6) - h['TP'+p+'charm'+x].Draw('same') - h['TP'+p+'charm'+x].SetLineColor(3) - h['T'+p+'charm'+x].SetLineColor(2) - h['T'+p+x].SetLineColor(4) - h['L'+p+x] = ROOT.TLegend(0.33,0.69,0.99,0.94) - h['L'+p+x].AddEntry(h['T'+p+x],'nu_mu new with charm, cascade, k-fac','PL') - h['L'+p+x].AddEntry(h['T'+p+'charm'+x],'nu_mu from charm new with charm, cascade, k-fac','PL') - h['L'+p+x].AddEntry(h['TP'+p+x],'nu_mu old CERN-Cracow prod','PL') - h['L'+p+x].AddEntry(h['TP'+p+'charm'+x],'nu_mu from charm old CERN-Cracow prod','PL') - h['L'+p+x].Draw() - t3=h[t].cd(3) - t3.SetLogy(1) - p = z+'nuesum' - h['T'+p+x].Draw() - h['T'+p+'charm'+x].Draw('same') - h['TP'+p+x].Draw('same') - h['TP'+p+x].SetLineColor(6) - h['TP'+p+'charm'+x].Draw('same') - h['TP'+p+'charm'+x].SetLineColor(3) - h['T'+p+'charm'+x].SetLineColor(2) - h['T'+p+x].SetLineColor(4) - h['L'+p+x] = ROOT.TLegend(0.33,0.69,0.99,0.94) - h['L'+p+x].AddEntry(h['T'+p+x],'nu_e new with charm, cascade, k-fac','PL') - h['L'+p+x].AddEntry(h['T'+p+'charm'+x],'nu_e from charm new with charm, cascade, k-fac','PL') - h['L'+p+x].AddEntry(h['TP'+p+x],'nu_e old CERN-Cracow prod','PL') - h['L'+p+x].AddEntry(h['TP'+p+'charm'+x],'nu_e from charm old CERN-Cracow prod','PL') - h['L'+p+x].Draw() -# - t4 = h[t].cd(4) - t4.SetLogy(1) - h['Lmuc'+z+x] = ROOT.TLegend(0.33,0.73,0.99,0.94) - p = z+'mu-' - h['T'+p+x].SetTitle('mu-/mu+') - h['T'+p+x].Draw() - h['TP'+p+x].Draw('same') - h['TP'+p+x].SetLineColor(6) - h['T'+p+x].SetLineColor(4) - h['Lmuc'+z+x].AddEntry(h['T'+p+x],'mu- new with charm, cascade, k-fac','PL') - h['Lmuc'+z+x].AddEntry(h['TP'+p+x],'mu- old Yandex prod','PL') - p = z+'mu+' - h['T'+p+x].Draw('same') - h['TP'+p+x].Draw('same') - h['TP'+p+x].SetLineColor(3) - h['T'+p+x].SetLineColor(2) - h['Lmuc'+z+x].AddEntry(h['T'+p+x],'mu+ new with charm, cascade, k-fac','PL') - h['Lmuc'+z+x].AddEntry(h['TP'+p+x],'mu+ old Yandex prod','PL') - h['Lmuc'+z+x].Draw() -# - t5 = h[t].cd(5) - t5.SetLogy(1) - h['Lnumu'+z+x] = ROOT.TLegend(0.33,0.73,0.99,0.94) - p = z+'numu' - h['T'+p+x].SetTitle('numu/numubar') - h['T'+p+x].Draw() - h['TP'+p+x].Draw('same') - h['TP'+p+x].SetLineColor(6) - h['T'+p+x].SetLineColor(4) - h['Lnumu'+z+x].AddEntry(h['T'+p+x],'nu_mu new with charm, cascade, k-fac','PL') - h['Lnumu'+z+x].AddEntry(h['TP'+p+x],'nu_mu old Yandex prod','PL') - p = z+'numubar' - h['T'+p+x].Draw('same') - h['TP'+p+x].Draw('same') - h['TP'+p+x].SetLineColor(3) - h['T'+p+x].SetLineColor(2) - h['Lnumu'+z+x].AddEntry(h['T'+p+x],'anti nu_mu new with charm, cascade, k-fac','PL') - h['Lnumu'+z+x].AddEntry(h['TP'+p+x],'anti nu_mu old Yandex prod','PL') - h['Lnumu'+z+x].Draw() - t6 = h[t].cd(6) - t6.SetLogy(1) - p = z+'nue' - h['Lnue'+z+x] = ROOT.TLegend(0.33,0.73,0.99,0.94) - h['T'+p+x].SetTitle('nue/nuebar') - h['T'+p+x].Draw() - h['TP'+p+x].Draw('same') - h['TP'+p+x].SetLineColor(6) - h['T'+p+x].SetLineColor(4) - h['Lnue'+z+x].AddEntry(h['T'+p+x],'nu_e new with charm, cascade, k-fac','PL') - h['Lnue'+z+x].AddEntry(h['TP'+p+x],'nu_e old Yandex prod','PL') - p = z+'nuebar' - h['T'+p+x].Draw('same') - h['TP'+p+x].Draw('same') - h['TP'+p+x].SetLineColor(3) - h['T'+p+x].SetLineColor(2) - h['Lnue'+z+x].AddEntry(h['T'+p+x],'anti nu_e new with charm, cascade, k-fac','PL') - h['Lnue'+z+x].AddEntry(h['TP'+p+x],'anti nu_e old Yandex prod','PL') - h['Lnue'+z+x].Draw() -# - h[t].Print('comparison'+z+x.replace('_>','')+'.png') - h[t].Print('comparison'+z+x.replace('_>','')+'.pdf') -# make ratio plots - x = '_>E' - for z in ['p','pt']: - h[z+'muRatio'+x]=h['T'+z+'mu'+x].Clone(z+'muRatio'+x) - h[z+'muRatio'+x].Divide(h['TP'+z+'mu'+x]) - h[z+'numuRatio'+x]=h['T'+z+'numusum'+x].Clone(z+'numuRatio'+x) - h[z+'numuRatio'+x].Divide(h['TP'+z+'numusum'+x]) - h[z+'nueRatio'+x]=h['T'+z+'nuesum'+x].Clone(z+'nueRatio'+x) - h[z+'nueRatio'+x].Divide(h['TP'+z+'nuesum'+x]) - ut.bookCanvas(h,key='ratios',title='ratios',nx=1800,ny=600,cx=2,cy=1) - n = 1 - for z in ['p','pt']: - h['Lratio'+z+x] = ROOT.TLegend(0.21,0.74,0.71,0.85) - tc = h['ratios'].cd(n) - n+=1 - h[z+'muRatio'+x].SetLineColor(2) - h[z+'muRatio'+x].SetMaximum(max(h[z+'muRatio'+x].GetMaximum(),h[z+'numuRatio'+x].GetMaximum())) - h[z+'muRatio'+x].SetMinimum(0) - h[z+'muRatio'+x].SetStats(0) - h[z+'muRatio'+x].Draw() - h[z+'numuRatio'+x].SetLineColor(3) - h[z+'numuRatio'+x].SetStats(0) - h[z+'numuRatio'+x].Draw('same') - #h[z+'nueRatio'+x].SetLineColor(4) - #h[z+'nueRatio'+x].Draw('same') - h['Lratio'+z+x].AddEntry(h[z+'muRatio'+x],'muon flux new / old ','PL') - h['Lratio'+z+x].AddEntry(h[z+'numuRatio'+x],'nu_mu flux new / old ','PL') - #h['Lratio'+z+x].AddEntry(h[z+'nueRatio'+x],'nu_e flux new / old ','PL') - h['Lratio'+z+x].Draw() - h['ratios'].Print('comparisonRatios.png') - h['ratios'].Print('comparisonRatios.pdf') + test(eospath + "pythia8_Geant4_onlyMuons.root") + for x in ["", "_>E"]: + for z in ["p", "pt"]: + for ahist in ["mu-", "mu+", "mu", "mu-charm", "mu+charm", "mucharm"]: + h["TP" + z + ahist + x] = h["T" + z + ahist + x].Clone("CT" + ahist + x) + test(eospath + "pythia8_Geant4_Yandex_onlyNeutrinos.root") + for x in ["", "_>E"]: + for z in ["p", "pt"]: + for ahist in [ + "numusum", + "nuesum", + "numusumcharm", + "nuesumcharm", + "numu", + "numubar", + "nue", + "nuebar", + "numucharm", + "numubarcharm", + "nuecharm", + "nuebarcharm", + ]: + h["TP" + z + ahist + x] = h["T" + z + ahist + x].Clone("CT" + ahist + x) + test(eospath + "Mbias/pythia8_Geant4-withCharm-ram.root") + for x in ["", "_>E"]: + for z in ["p", "pt"]: + t = z.upper() + if x != "": + t = ">" + t + t1 = h[t].cd(1) + p = z + "mu" + h["T" + p + x].SetTitle("musum") + h["T" + p + x].Draw() + h["T" + p + "charm" + x].Draw("same") + h["TP" + p + x].Draw("same") + h["TP" + p + x].SetLineColor(6) + h["TP" + p + "charm" + x].Draw("same") + h["TP" + p + "charm" + x].SetLineColor(3) + h["T" + p + "charm" + x].SetLineColor(2) + h["T" + p + x].SetLineColor(4) + h["L" + p + x] = ROOT.TLegend(0.33, 0.69, 0.99, 0.94) + h["L" + p + x].AddEntry( + h["T" + p + x], "muon new with charm, cascade, k-fac", "PL" + ) + h["L" + p + x].AddEntry( + h["T" + p + "charm" + x], + "muon from charm new with charm, cascade, k-fac", + "PL", + ) + h["L" + p + x].AddEntry(h["TP" + p + x], "muon old CERN-Cracow prod", "PL") + h["L" + p + x].AddEntry( + h["TP" + p + "charm" + x], "muon from charm old CERN-Cracow prod", "PL" + ) + h["L" + p + x].Draw() + h[t].cd(2) + p = z + "numusum" + h["T" + p + x].Draw() + h["T" + p + "charm" + x].Draw("same") + h["TP" + p + x].Draw("same") + h["TP" + p + x].SetLineColor(6) + h["TP" + p + "charm" + x].Draw("same") + h["TP" + p + "charm" + x].SetLineColor(3) + h["T" + p + "charm" + x].SetLineColor(2) + h["T" + p + x].SetLineColor(4) + h["L" + p + x] = ROOT.TLegend(0.33, 0.69, 0.99, 0.94) + h["L" + p + x].AddEntry( + h["T" + p + x], "nu_mu new with charm, cascade, k-fac", "PL" + ) + h["L" + p + x].AddEntry( + h["T" + p + "charm" + x], + "nu_mu from charm new with charm, cascade, k-fac", + "PL", + ) + h["L" + p + x].AddEntry(h["TP" + p + x], "nu_mu old CERN-Cracow prod", "PL") + h["L" + p + x].AddEntry( + h["TP" + p + "charm" + x], "nu_mu from charm old CERN-Cracow prod", "PL" + ) + h["L" + p + x].Draw() + t3 = h[t].cd(3) + t3.SetLogy(1) + p = z + "nuesum" + h["T" + p + x].Draw() + h["T" + p + "charm" + x].Draw("same") + h["TP" + p + x].Draw("same") + h["TP" + p + x].SetLineColor(6) + h["TP" + p + "charm" + x].Draw("same") + h["TP" + p + "charm" + x].SetLineColor(3) + h["T" + p + "charm" + x].SetLineColor(2) + h["T" + p + x].SetLineColor(4) + h["L" + p + x] = ROOT.TLegend(0.33, 0.69, 0.99, 0.94) + h["L" + p + x].AddEntry( + h["T" + p + x], "nu_e new with charm, cascade, k-fac", "PL" + ) + h["L" + p + x].AddEntry( + h["T" + p + "charm" + x], + "nu_e from charm new with charm, cascade, k-fac", + "PL", + ) + h["L" + p + x].AddEntry(h["TP" + p + x], "nu_e old CERN-Cracow prod", "PL") + h["L" + p + x].AddEntry( + h["TP" + p + "charm" + x], "nu_e from charm old CERN-Cracow prod", "PL" + ) + h["L" + p + x].Draw() + # + t4 = h[t].cd(4) + t4.SetLogy(1) + h["Lmuc" + z + x] = ROOT.TLegend(0.33, 0.73, 0.99, 0.94) + p = z + "mu-" + h["T" + p + x].SetTitle("mu-/mu+") + h["T" + p + x].Draw() + h["TP" + p + x].Draw("same") + h["TP" + p + x].SetLineColor(6) + h["T" + p + x].SetLineColor(4) + h["Lmuc" + z + x].AddEntry( + h["T" + p + x], "mu- new with charm, cascade, k-fac", "PL" + ) + h["Lmuc" + z + x].AddEntry(h["TP" + p + x], "mu- old Yandex prod", "PL") + p = z + "mu+" + h["T" + p + x].Draw("same") + h["TP" + p + x].Draw("same") + h["TP" + p + x].SetLineColor(3) + h["T" + p + x].SetLineColor(2) + h["Lmuc" + z + x].AddEntry( + h["T" + p + x], "mu+ new with charm, cascade, k-fac", "PL" + ) + h["Lmuc" + z + x].AddEntry(h["TP" + p + x], "mu+ old Yandex prod", "PL") + h["Lmuc" + z + x].Draw() + # + t5 = h[t].cd(5) + t5.SetLogy(1) + h["Lnumu" + z + x] = ROOT.TLegend(0.33, 0.73, 0.99, 0.94) + p = z + "numu" + h["T" + p + x].SetTitle("numu/numubar") + h["T" + p + x].Draw() + h["TP" + p + x].Draw("same") + h["TP" + p + x].SetLineColor(6) + h["T" + p + x].SetLineColor(4) + h["Lnumu" + z + x].AddEntry( + h["T" + p + x], "nu_mu new with charm, cascade, k-fac", "PL" + ) + h["Lnumu" + z + x].AddEntry(h["TP" + p + x], "nu_mu old Yandex prod", "PL") + p = z + "numubar" + h["T" + p + x].Draw("same") + h["TP" + p + x].Draw("same") + h["TP" + p + x].SetLineColor(3) + h["T" + p + x].SetLineColor(2) + h["Lnumu" + z + x].AddEntry( + h["T" + p + x], "anti nu_mu new with charm, cascade, k-fac", "PL" + ) + h["Lnumu" + z + x].AddEntry( + h["TP" + p + x], "anti nu_mu old Yandex prod", "PL" + ) + h["Lnumu" + z + x].Draw() + t6 = h[t].cd(6) + t6.SetLogy(1) + p = z + "nue" + h["Lnue" + z + x] = ROOT.TLegend(0.33, 0.73, 0.99, 0.94) + h["T" + p + x].SetTitle("nue/nuebar") + h["T" + p + x].Draw() + h["TP" + p + x].Draw("same") + h["TP" + p + x].SetLineColor(6) + h["T" + p + x].SetLineColor(4) + h["Lnue" + z + x].AddEntry( + h["T" + p + x], "nu_e new with charm, cascade, k-fac", "PL" + ) + h["Lnue" + z + x].AddEntry(h["TP" + p + x], "nu_e old Yandex prod", "PL") + p = z + "nuebar" + h["T" + p + x].Draw("same") + h["TP" + p + x].Draw("same") + h["TP" + p + x].SetLineColor(3) + h["T" + p + x].SetLineColor(2) + h["Lnue" + z + x].AddEntry( + h["T" + p + x], "anti nu_e new with charm, cascade, k-fac", "PL" + ) + h["Lnue" + z + x].AddEntry( + h["TP" + p + x], "anti nu_e old Yandex prod", "PL" + ) + h["Lnue" + z + x].Draw() + # + h[t].Print("comparison" + z + x.replace("_>", "") + ".png") + h[t].Print("comparison" + z + x.replace("_>", "") + ".pdf") + # make ratio plots + x = "_>E" + for z in ["p", "pt"]: + h[z + "muRatio" + x] = h["T" + z + "mu" + x].Clone(z + "muRatio" + x) + h[z + "muRatio" + x].Divide(h["TP" + z + "mu" + x]) + h[z + "numuRatio" + x] = h["T" + z + "numusum" + x].Clone(z + "numuRatio" + x) + h[z + "numuRatio" + x].Divide(h["TP" + z + "numusum" + x]) + h[z + "nueRatio" + x] = h["T" + z + "nuesum" + x].Clone(z + "nueRatio" + x) + h[z + "nueRatio" + x].Divide(h["TP" + z + "nuesum" + x]) + ut.bookCanvas(h, key="ratios", title="ratios", nx=1800, ny=600, cx=2, cy=1) + n = 1 + for z in ["p", "pt"]: + h["Lratio" + z + x] = ROOT.TLegend(0.21, 0.74, 0.71, 0.85) + tc = h["ratios"].cd(n) + n += 1 + h[z + "muRatio" + x].SetLineColor(2) + h[z + "muRatio" + x].SetMaximum( + max(h[z + "muRatio" + x].GetMaximum(), h[z + "numuRatio" + x].GetMaximum()) + ) + h[z + "muRatio" + x].SetMinimum(0) + h[z + "muRatio" + x].SetStats(0) + h[z + "muRatio" + x].Draw() + h[z + "numuRatio" + x].SetLineColor(3) + h[z + "numuRatio" + x].SetStats(0) + h[z + "numuRatio" + x].Draw("same") + # h[z+'nueRatio'+x].SetLineColor(4) + # h[z+'nueRatio'+x].Draw('same') + h["Lratio" + z + x].AddEntry(h[z + "muRatio" + x], "muon flux new / old ", "PL") + h["Lratio" + z + x].AddEntry( + h[z + "numuRatio" + x], "nu_mu flux new / old ", "PL" + ) + # h['Lratio'+z+x].AddEntry(h[z+'nueRatio'+x],'nu_e flux new / old ','PL') + h["Lratio" + z + x].Draw() + h["ratios"].Print("comparisonRatios.png") + h["ratios"].Print("comparisonRatios.pdf") + -print("+ merging with charm events using existing charmless Mbias file: mergeWithCharm()") +print( + "+ merging with charm events using existing charmless Mbias file: mergeWithCharm()" +) print("+ removeCharm(p) from mbias file made with g4Ex_gap_mergeFiles.py") print("+ testing output: test('pythia8_Geant4-noOpenCharm.root')") -print("+ not used anymore: to start the full production, including merging of Mbias files: runProduction()") +print( + "+ not used anymore: to start the full production, including merging of Mbias files: runProduction()" +) diff --git a/macro/runPythia8.py b/macro/runPythia8.py index c4d5b2a64f..98b4b7fee8 100644 --- a/macro/runPythia8.py +++ b/macro/runPythia8.py @@ -1,225 +1,381 @@ +from array import array + import ROOT import rootUtils as ut -from array import array -theSeed = 0 + +theSeed = 0 h = {} ROOT.gRandom.SetSeed(theSeed) ROOT.gSystem.Load("libpythia8") from argparse import ArgumentParser + parser = ArgumentParser() -parser.add_argument("-b", "--heartbeat", dest="heartbeat", type=int, help="progress report", default=10000) -parser.add_argument("-n", "--pot", dest="NPoT", type=int, help="protons on target", default=1000000) -parser.add_argument("-r", "--run", dest="run", type=int, help="production sequence number", default=0) -parser.add_argument('-M', '--Emin', dest='Emin', type=float,help="cutOff", default=1.0) -parser.add_argument('-E', '--Beam', dest='fMom', type=float,help="beam momentum", default=400.) -parser.add_argument('-J', '--Jpsi-mainly', action='store_true', dest='JpsiMainly', default=False) -parser.add_argument('-Y', '--DrellYan', action='store_true', dest='DrellYan', default=False) -parser.add_argument('-P', '--PhotonCollision', action='store_true', dest='PhotonCollision', default=False) -parser.add_argument('-C', '--charm', action='store_true', dest='charm', default=False) -parser.add_argument('-X', '--PDFpSet',dest="PDFpSet", type=str, help="PDF pSet to use", default="13") -parser.add_argument('-u', '--uOnly', action='store_true', dest='uOnly', default=False) +parser.add_argument( + "-b", + "--heartbeat", + dest="heartbeat", + type=int, + help="progress report", + default=10000, +) +parser.add_argument( + "-n", "--pot", dest="NPoT", type=int, help="protons on target", default=1000000 +) +parser.add_argument( + "-r", "--run", dest="run", type=int, help="production sequence number", default=0 +) +parser.add_argument("-M", "--Emin", dest="Emin", type=float, help="cutOff", default=1.0) +parser.add_argument( + "-E", "--Beam", dest="fMom", type=float, help="beam momentum", default=400.0 +) +parser.add_argument( + "-J", "--Jpsi-mainly", action="store_true", dest="JpsiMainly", default=False +) +parser.add_argument( + "-Y", "--DrellYan", action="store_true", dest="DrellYan", default=False +) +parser.add_argument( + "-P", + "--PhotonCollision", + action="store_true", + dest="PhotonCollision", + default=False, +) +parser.add_argument("-C", "--charm", action="store_true", dest="charm", default=False) +parser.add_argument( + "-X", "--PDFpSet", dest="PDFpSet", type=str, help="PDF pSet to use", default="13" +) +parser.add_argument("-u", "--uOnly", action="store_true", dest="uOnly", default=False) # for lhapdf, -X LHAPDF6:cteq6 options = parser.parse_args() print("start IGNOREIGNOREIGNOREIGNOREIGNOREIGNOREIGNOREIGNOREIGNORE") -X=ROOT.FixedTargetGenerator() +X = ROOT.FixedTargetGenerator() print("end IGNOREIGNOREIGNOREIGNOREIGNOREIGNOREIGNOREIGNOREIGNORE") -def yBeam(Mproton = 0.938272081, pbeam = 400.): - Ebeam = ROOT.TMath.Sqrt(pbeam**2+Mproton**2) - betaCM = pbeam / (Ebeam + Mproton) - y_beam = 0.5*ROOT.TMath.Log( (1+betaCM)/(1-betaCM)) # https://arxiv.org/pdf/1604.02651.pdf + +def yBeam(Mproton=0.938272081, pbeam=400.0): + Ebeam = ROOT.TMath.Sqrt(pbeam**2 + Mproton**2) + betaCM = pbeam / (Ebeam + Mproton) + y_beam = 0.5 * ROOT.TMath.Log( + (1 + betaCM) / (1 - betaCM) + ) # https://arxiv.org/pdf/1604.02651.pdf return y_beam -generators = {'p':ROOT.Pythia8.Pythia(),'n':ROOT.Pythia8.Pythia()} -generators['p'].settings.mode("Beams:idB", 2212) -generators['n'].settings.mode("Beams:idB", 2112) + +generators = {"p": ROOT.Pythia8.Pythia(), "n": ROOT.Pythia8.Pythia()} +generators["p"].settings.mode("Beams:idB", 2212) +generators["n"].settings.mode("Beams:idB", 2112) for g in generators: - ut.bookHist(h, 'xsec_'+g, ' total cross section',1,0.,1.) - ut.bookHist(h, 'M_'+g, ' N mu+mu-;M [GeV/c^{2}];y_{CM}',500,0.,10.,120,-3.,3.,100,0.,5.) - ut.bookHist(h, 'cosCS_'+g, ' N cosCS;cosCS;y_{CM}',100,-1.,1.,120,-3.,3.,100,0.,5.) - ut.bookHist(h, 'cosCSJpsi_'+g, ' N cosCS 2.9','to') -hname = hname.replace('/','') - -f = ROOT.TFile("ntuple-"+hname+".root","RECREATE") -signal = ROOT.TNtuple("ntuple","ntuple","M:P:Pt:y:p1x:p1y:p1z:p2x:p2y:p2z:cosCS") + ut.bookHist(h, "xsec_" + g, " total cross section", 1, 0.0, 1.0) + ut.bookHist( + h, + "M_" + g, + " N mu+mu-;M [GeV/c^{2}];y_{CM}", + 500, + 0.0, + 10.0, + 120, + -3.0, + 3.0, + 100, + 0.0, + 5.0, + ) + ut.bookHist( + h, + "cosCS_" + g, + " N cosCS;cosCS;y_{CM}", + 100, + -1.0, + 1.0, + 120, + -3.0, + 3.0, + 100, + 0.0, + 5.0, + ) + ut.bookHist( + h, + "cosCSJpsi_" + g, + " N cosCS 2.9", "to") +hname = hname.replace("/", "") + +f = ROOT.TFile("ntuple-" + hname + ".root", "RECREATE") +signal = ROOT.TNtuple("ntuple", "ntuple", "M:P:Pt:y:p1x:p1y:p1z:p2x:p2y:p2z:cosCS") timer = ROOT.TStopwatch() timer.Start() -ntagged = {'p':0,'n':0} -ybeam = yBeam(pbeam = options.fMom) +ntagged = {"p": 0, "n": 0} +ybeam = yBeam(pbeam=options.fMom) for n in range(int(options.NPoT)): - for g in generators: - py = generators[g] - rc = py.next() - nmu = {} - for ii in range(1,py.event.size()): - if options.DrellYan and py.event[ii].id()!=23: continue - if options.PhotonCollision and py.event[ii].id()!=22: continue - for m in py.event.daughterList(ii): - if abs(py.event[m].id())==13: nmu[m]=ii - if len(nmu) == 2: - ntagged[g]+=1 - ks = list(nmu) - if options.DrellYan: - Zstar = py.event[nmu[ks[0]]] - rc=h['M_'+g].Fill(Zstar.m(),py.event[nmu[ks[0]]].y()-ybeam,py.event[nmu[ks[0]]].pT()) -# what about polarization? - ii = nmu[ks[0]] - d0 = py.event.daughterList(ii)[0] - d1 = py.event.daughterList(ii)[1] - if py.event[d0].id() < 0: - nlep = py.event[d0] - nantilep = py.event[d1] - else: - nlep = py.event[d1] - nantilep = py.event[d0] - P1pl = nlep.e()+nlep.pz() - P2pl = nantilep.e()+nantilep.pz() - P1mi = nlep.e()-nlep.pz() - P2mi = nantilep.e()-nantilep.pz() - A = P1pl*P2mi-P2pl*P1mi - cosCS = Zstar.pz()/abs(Zstar.pz()) * 1./Zstar.m()/ROOT.TMath.Sqrt(Zstar.m2()+Zstar.pT()**2)*A - rc=h['cosCS_'+g].Fill(cosCS,Zstar.y()-ybeam,py.event[nmu[ks[0]]].pT()) - if Zstar.m()>2.9 and Zstar.m()<4.5: rc=h['cosCSJpsi_'+g].Fill(cosCS,py.event[nmu[ks[0]]].y()-ybeam,py.event[nmu[ks[0]]].pT()) - rc = signal.Fill(Zstar.m(),Zstar.pAbs(),Zstar.pT(),Zstar.y(),nlep.px(),nlep.py(),nlep.pz(),nantilep.px(),nantilep.py(),nantilep.pz(),cosCS) - if options.PhotonCollision: - M={} - k=0 - for m in ks: - M[k]=ROOT.TLorentzVector(py.event[m].px(),py.event[m].py(),py.event[m].pz(),py.event[m].e()) - k+=1 - G = M[0]+M[1] - rc=h['M_'+g].Fill(G.M(),G.Rapidity()-ybeam,G.Pt()) - - -print(">>>> proton statistics, ntagged=",ntagged['p']) -generators['p'].stat() -print( ">>>> neutron statistics, ntagged=",ntagged['n']) -generators['n'].stat() + for g in generators: + py = generators[g] + rc = py.next() + nmu = {} + for ii in range(1, py.event.size()): + if options.DrellYan and py.event[ii].id() != 23: + continue + if options.PhotonCollision and py.event[ii].id() != 22: + continue + for m in py.event.daughterList(ii): + if abs(py.event[m].id()) == 13: + nmu[m] = ii + if len(nmu) == 2: + ntagged[g] += 1 + ks = list(nmu) + if options.DrellYan: + Zstar = py.event[nmu[ks[0]]] + rc = h["M_" + g].Fill( + Zstar.m(), + py.event[nmu[ks[0]]].y() - ybeam, + py.event[nmu[ks[0]]].pT(), + ) + # what about polarization? + ii = nmu[ks[0]] + d0 = py.event.daughterList(ii)[0] + d1 = py.event.daughterList(ii)[1] + if py.event[d0].id() < 0: + nlep = py.event[d0] + nantilep = py.event[d1] + else: + nlep = py.event[d1] + nantilep = py.event[d0] + P1pl = nlep.e() + nlep.pz() + P2pl = nantilep.e() + nantilep.pz() + P1mi = nlep.e() - nlep.pz() + P2mi = nantilep.e() - nantilep.pz() + A = P1pl * P2mi - P2pl * P1mi + cosCS = ( + Zstar.pz() + / abs(Zstar.pz()) + * 1.0 + / Zstar.m() + / ROOT.TMath.Sqrt(Zstar.m2() + Zstar.pT() ** 2) + * A + ) + rc = h["cosCS_" + g].Fill( + cosCS, Zstar.y() - ybeam, py.event[nmu[ks[0]]].pT() + ) + if Zstar.m() > 2.9 and Zstar.m() < 4.5: + rc = h["cosCSJpsi_" + g].Fill( + cosCS, + py.event[nmu[ks[0]]].y() - ybeam, + py.event[nmu[ks[0]]].pT(), + ) + rc = signal.Fill( + Zstar.m(), + Zstar.pAbs(), + Zstar.pT(), + Zstar.y(), + nlep.px(), + nlep.py(), + nlep.pz(), + nantilep.px(), + nantilep.py(), + nantilep.pz(), + cosCS, + ) + if options.PhotonCollision: + M = {} + k = 0 + for m in ks: + M[k] = ROOT.TLorentzVector( + py.event[m].px(), + py.event[m].py(), + py.event[m].pz(), + py.event[m].e(), + ) + k += 1 + G = M[0] + M[1] + rc = h["M_" + g].Fill(G.M(), G.Rapidity() - ybeam, G.Pt()) + + +print(">>>> proton statistics, ntagged=", ntagged["p"]) +generators["p"].stat() +print(">>>> neutron statistics, ntagged=", ntagged["n"]) +generators["n"].stat() timer.Stop() rtime = timer.RealTime() ctime = timer.CpuTime() -print("run ",options.run," PoT ",options.NPoT," Real time ",rtime, " s, CPU time ",ctime,"s") +print( + "run ", + options.run, + " PoT ", + options.NPoT, + " Real time ", + rtime, + " s, CPU time ", + ctime, + "s", +) signal.Write() for g in generators: - sigma = generators[g].info.sigmaGen(processes[0]) - h['xsec_'+g].SetBinContent(1,sigma) -ut.writeHists(h,hname+'.root') + sigma = generators[g].info.sigmaGen(processes[0]) + h["xsec_" + g].SetBinContent(1, sigma) +ut.writeHists(h, hname + ".root") + def na50(online=True): - for g in generators: - if online: - processes = generators[g].info.codesHard() - name = generators[g].info.nameProc(processes[0]) - sigma = generators[g].info.sigmaGen(processes[0]) - else: - name = '' - sigma = h['xsec_'+g].GetBinContent(1) - yax = h['M_'+g].GetYaxis() - xax = h['M_'+g].GetXaxis() - Mmin = xax.FindBin(2.9) - Mmax = xax.FindBin(4.5) - Ymin = yax.FindBin(-0.425) - Ymax = yax.FindBin(0.575) - h['MA'] = h['M_'+g].ProjectionX('MA') - h['M'] = h['M_'+g].ProjectionX('M',Ymin,Ymax) - print("generator sigma mumu-ratio in-mass-range in-y-range") - print("%s %s %6.2F nbarn, %5.2F, %5.2G, %5.2F "%(g,name,sigma*1E6,\ - float(h['MA'].GetEntries())/options.NPoT,\ - h['MA'].Integral(Mmin,Mmax)/float(h['MA'].GetEntries()),\ - h['M'].GetEntries()/float(h['MA'].GetEntries()))) - fraction = h['M'].Integral(Mmin,Mmax)/options.NPoT - # multiply with 0.5 assuming no polarization -0.5 < cosCS < 0.5 - print("cross section a la NA50 for : %s %5.2F pb"%(g,0.5*fraction*sigma*1E9)) - # via cosCS - for g in generators: - if online: + for g in generators: + if online: + processes = generators[g].info.codesHard() + name = generators[g].info.nameProc(processes[0]) + sigma = generators[g].info.sigmaGen(processes[0]) + else: + name = "" + sigma = h["xsec_" + g].GetBinContent(1) + yax = h["M_" + g].GetYaxis() + xax = h["M_" + g].GetXaxis() + Mmin = xax.FindBin(2.9) + Mmax = xax.FindBin(4.5) + Ymin = yax.FindBin(-0.425) + Ymax = yax.FindBin(0.575) + h["MA"] = h["M_" + g].ProjectionX("MA") + h["M"] = h["M_" + g].ProjectionX("M", Ymin, Ymax) + print("generator sigma mumu-ratio in-mass-range in-y-range") + print( + "%s %s %6.2F nbarn, %5.2F, %5.2G, %5.2F " + % ( + g, + name, + sigma * 1e6, + float(h["MA"].GetEntries()) / options.NPoT, + h["MA"].Integral(Mmin, Mmax) / float(h["MA"].GetEntries()), + h["M"].GetEntries() / float(h["MA"].GetEntries()), + ) + ) + fraction = h["M"].Integral(Mmin, Mmax) / options.NPoT + # multiply with 0.5 assuming no polarization -0.5 < cosCS < 0.5 + print( + "cross section a la NA50 for : %s %5.2F pb" + % (g, 0.5 * fraction * sigma * 1e9) + ) + # via cosCS + for g in generators: + if online: + processes = generators[g].info.codesHard() + name = generators[g].info.nameProc(processes[0]) + sigma = generators[g].info.sigmaGen(processes[0]) + else: + name = "" + sigma = h["xsec_" + g].GetBinContent(1) + yax = h["cosCSJpsi_" + g].GetYaxis() + xax = h["cosCSJpsi_" + g].GetXaxis() + Mmin = xax.FindBin(-0.5) + Mmax = xax.FindBin(0.5) + Ymin = yax.FindBin(-0.425) + Ymax = yax.FindBin(0.575) + h["MA"] = h["cosCSJpsi_" + g].ProjectionX("MA") + h["M"] = h["cosCSJpsi_" + g].ProjectionX("M", Ymin, Ymax) + print("generator sigma mumu-in-mass-range% cosCS in-y-range") + print( + "%s %s %6.2F nbarn, %5.2F, %5.2F, %5.2F " + % ( + g, + name, + sigma * 1e6, + float(h["MA"].GetEntries()) / options.NPoT * 100.0, + h["MA"].Integral(Mmin, Mmax) / float(h["MA"].GetEntries()), + h["M"].GetEntries() / float(h["MA"].GetEntries()), + ) + ) + fraction = h["M"].Integral(Mmin, Mmax) / options.NPoT + # taking polarization into account. + print( + "cross section a la NA50, -0.5 HNL -deepCopy = False # False = copy only stable particles to stack, except for HNL events +mcEngine = "TGeant3" +simEngine = "Pythia8" # "Genie" # Ntuple +nEvents = 2000 +inclusive = False # True = all processes if False only ccbar -> HNL +deepCopy = False # False = copy only stable particles to stack, except for HNL events eventDisplay = False -inputFile = None -theSeed = int(10000 * time.time() % 10000000) +inputFile = None +theSeed = int(10000 * time.time() % 10000000) -if momentum>5 : nEvents=1000 -if momentum>20 : nEvents=500 +if momentum > 5: + nEvents = 1000 +if momentum > 20: + nEvents = 500 -print("FairShip setup for",simEngine,"to produce",nEvents,"events") -if simEngine == "Ntuple" and not inputFile : - print('input file required if simEngine = Ntuple') -if simEngine == "Pythia6" and not inputFile : - print('pythia6 requires inputfile') -ROOT.gRandom.SetSeed(theSeed) # this should be propagated via ROOT to Pythia8 and Geant4VMC +print("FairShip setup for", simEngine, "to produce", nEvents, "events") +if simEngine == "Ntuple" and not inputFile: + print("input file required if simEngine = Ntuple") +if simEngine == "Pythia6" and not inputFile: + print("pythia6 requires inputfile") +ROOT.gRandom.SetSeed( + theSeed +) # this should be propagated via ROOT to Pythia8 and Geant4VMC shipRoot_conf.configure() ship_geo = ShipGeoConfig.Config().loadpy("$FAIRSHIP/geometry/geometry_config.py") # Output file name -outFile ="geant.root" +outFile = "geant.root" # rm older files !!! os.system("rm params.root") # Parameter file name -parFile="params.root" +parFile = "params.root" # In general, the following parts need not be touched # ======================================================================== @@ -49,37 +57,40 @@ rtdb = run.GetRuntimeDb() # -----Create geometry---------------------------------------------- import shipDet_conf + shipDet_conf.configure(run) # -----Create PrimaryGenerator-------------------------------------- -primGen=ROOT.FairPrimaryGenerator() -boxGen=ROOT.FairBoxGenerator(22,1); +primGen = ROOT.FairPrimaryGenerator() +boxGen = ROOT.FairBoxGenerator(22, 1) boxGen.SetPRange(momentum, momentum) -boxGen.SetPhiRange(0,0) -boxGen.SetThetaRange(0,0) -#boxGen.SetXYZ(0,0,-9900) -boxGen.SetXYZ(0,0,2400) +boxGen.SetPhiRange(0, 0) +boxGen.SetThetaRange(0, 0) +# boxGen.SetXYZ(0,0,-9900) +boxGen.SetXYZ(0, 0, 2400) primGen.AddGenerator(boxGen) run.SetGenerator(primGen) # ------------------------------------------------------------------------ -#---Store the visualiztion info of the tracks, this make the output file very large!! -#--- Use it only to display but not for production! -if eventDisplay: run.SetStoreTraj(ROOT.kTRUE) -else: run.SetStoreTraj(ROOT.kFALSE) +# ---Store the visualiztion info of the tracks, this make the output file very large!! +# --- Use it only to display but not for production! +if eventDisplay: + run.SetStoreTraj(ROOT.kTRUE) +else: + run.SetStoreTraj(ROOT.kFALSE) # -----Initialize simulation run------------------------------------ run.Init() fStack = ROOT.gMC.GetStack() -#fStack.SetEnergyCut(.3*u.MeV) +# fStack.SetEnergyCut(.3*u.MeV) # ------------------------------------------------------------------------ if simEngine != "Genie" and simEngine != "Ntuple": -# -----Runtime database--------------------------------------------- - kParameterMerged = ROOT.kTRUE - parOut = ROOT.FairParRootFileIo(kParameterMerged) - parOut.open(parFile) - rtdb.setOutput(parOut) - rtdb.saveOutput() # for the moment, it blocks when using Genie, no idea why - rtdb.printParamContexts() + # -----Runtime database--------------------------------------------- + kParameterMerged = ROOT.kTRUE + parOut = ROOT.FairParRootFileIo(kParameterMerged) + parOut.open(parFile) + rtdb.setOutput(parOut) + rtdb.saveOutput() # for the moment, it blocks when using Genie, no idea why + rtdb.printParamContexts() # -----Start run---------------------------------------------------- run.Run(nEvents) # ------------------------------------------------------------------------ @@ -88,10 +99,10 @@ timer.Stop() rtime = timer.RealTime() ctime = timer.CpuTime() -print(' ') +print(" ") print("Macro finished succesfully.") -print("Output file is ", outFile) -print("Parameter file is ",parFile) -print("Real time ",rtime, " s, CPU time ",ctime,"s") +print("Output file is ", outFile) +print("Parameter file is ", parFile) +print("Real time ", rtime, " s, CPU time ", ctime, "s") # ------------------------------------------------------------------------ diff --git a/macro/run_simPgun.py b/macro/run_simPgun.py index 86aad5834c..3b4713286a 100644 --- a/macro/run_simPgun.py +++ b/macro/run_simPgun.py @@ -1,28 +1,35 @@ -mcEngine = "TGeant4" +mcEngine = "TGeant4" simEngine = "Pgun" nEvents = 5 -import ROOT,os +import os + +import ROOT + ROOT.gROOT.LoadMacro("$VMCWORKDIR/gconfig/basiclibs.C") ROOT.basiclibs() -#-----prepare python exit----------------------------------------------- + +# -----prepare python exit----------------------------------------------- def pyExit(): - global run - del run + global run + del run + + import atexit + atexit.register(pyExit) # -muShieldLength = 7000 # m +muShieldLength = 7000 # m targetHadronAbsorber = 350 # m -decayVolumeLength = 5000 # m +decayVolumeLength = 5000 # m # Output file name -tag = simEngine+"-"+mcEngine -outFile = "ship."+tag+".root" -os.system("rm *."+tag+".root") +tag = simEngine + "-" + mcEngine +outFile = "ship." + tag + ".root" +os.system("rm *." + tag + ".root") # Parameter file name -parFile="ship.params."+tag+".root" +parFile = "ship.params." + tag + ".root" # In general, the following parts need not be touched # ======================================================================== @@ -34,8 +41,8 @@ def pyExit(): # -----Create simulation run---------------------------------------- run = ROOT.FairRunSim() -run.SetName(mcEngine)# Transport engine -run.SetOutputFile(outFile) # Output file +run.SetName(mcEngine) # Transport engine +run.SetOutputFile(outFile) # Output file rtdb = run.GetRuntimeDb() # ------------------------------------------------------------------------ @@ -45,13 +52,13 @@ def pyExit(): # -----Create geometry---------------------------------------------- -cave= ROOT.ShipCave("CAVE") +cave = ROOT.ShipCave("CAVE") cave.SetGeometryFileName("cave.geo") run.AddModule(cave) -TargetStation = ROOT.ShipTargetStation("TargetStation",muShieldLength) +TargetStation = ROOT.ShipTargetStation("TargetStation", muShieldLength) run.AddModule(TargetStation) -MuonShield = ROOT.ShipMuonShield("MuonShield",1) +MuonShield = ROOT.ShipMuonShield("MuonShield", 1) run.AddModule(MuonShield) magnet = ROOT.ShipMagnet("Magnet") @@ -69,27 +76,29 @@ def pyExit(): Muon = ROOT.muon("Muon", ROOT.kTRUE) run.AddModule(Muon) -#----- Magnetic field ------------------------------------------- - # Constant Field +# ----- Magnetic field ------------------------------------------- +# Constant Field fMagField = ROOT.ShipConstField() -fMagField.SetField(0., 2. ,0. ) # values are in kG -fMagField.SetFieldRegion(-160, 160,-160, 160, 1940, 125); # values are in cm (xmin,xmax,ymin,ymax,zmin,zmax) +fMagField.SetField(0.0, 2.0, 0.0) # values are in kG +fMagField.SetFieldRegion( + -160, 160, -160, 160, 1940, 125 +) # values are in cm (xmin,xmax,ymin,ymax,zmin,zmax) run.SetField(fMagField) # -----Create PrimaryGenerator-------------------------------------- primGen = ROOT.FairPrimaryGenerator() -pointZero = -decayVolumeLength/2. - targetHadronAbsorber - muShieldLength - 200. +pointZero = -decayVolumeLength / 2.0 - targetHadronAbsorber - muShieldLength - 200.0 -mom = ROOT.TVector3(0.,0.,100.) -pos = ROOT.TVector3(0.,0.,pointZero) -myPgun = ROOT.FairParticleGenerator(2212,1,0.,0.,100.,0.,0.,pointZero) +mom = ROOT.TVector3(0.0, 0.0, 100.0) +pos = ROOT.TVector3(0.0, 0.0, pointZero) +myPgun = ROOT.FairParticleGenerator(2212, 1, 0.0, 0.0, 100.0, 0.0, 0.0, pointZero) primGen.AddGenerator(myPgun) run.SetGenerator(primGen) # ------------------------------------------------------------------------ -#---Store the visualiztion info of the tracks, this make the output file very large!! -#--- Use it only to display but not for production! +# ---Store the visualiztion info of the tracks, this make the output file very large!! +# --- Use it only to display but not for production! run.SetStoreTraj(ROOT.kTRUE) # -----Initialize simulation run------------------------------------ @@ -102,51 +111,56 @@ def pyExit(): parOut.open(parFile) rtdb.setOutput(parOut) rtdb.saveOutput() -#rtdb.print() does not work in python ?? +# rtdb.print() does not work in python ?? rtdb.printParamContexts() # -----Start run---------------------------------------------------- run.Run(nEvents) -run.CreateGeometryFile("geofile_full."+tag+".root") +run.CreateGeometryFile("geofile_full." + tag + ".root") # ------------------------------------------------------------------------ # -----Finish------------------------------------------------------- timer.Stop() rtime = timer.RealTime() ctime = timer.CpuTime() -print(' ') +print(" ") print("Macro finished succesfully.") -print("Output file is ", outFile) -print("Parameter file is ",parFile) -print("Real time ",rtime, " s, CPU time ",ctime,"s") +print("Output file is ", outFile) +print("Parameter file is ", parFile) +print("Real time ", rtime, " s, CPU time ", ctime, "s") # ------------------------------------------------------------------------ + def someDebug(): - g = ROOT.gROOT - lm = run.GetListOfModules() - for x in lm: print(x.GetName()) - fGeo = ROOT.gGeoManager - cave = fGeo.GetTopVolume() - cave.Draw('ogl') -# - tf = g.FindObjectAny('cbmroot') - for l in tf.GetListOfFolders(): print(l.GetName()) - l = tf.FindObject('MCGeoTrack') - trs = l.FindObject('GeoTracks') - for x in trs: print(x) - l = tf.FindObject('Stack') - trs = l.FindObject('MCTrack') - for x in trs: print(x) -# - gMC = ROOT.gMC # - fStack = gMC.GetStack() - gMC.ProcessRun(1) # 1 event -# - gMC.GetMC() # + fStack = gMC.GetStack() + gMC.ProcessRun(1) # 1 event + # + gMC.GetMC() # HNL, if "b" only bbar -> HNL, if "bc" only Bc+/Bc- -> HNL, and for darkphotons: if meson = production through meson decays, pbrem = proton bremstrahlung, qcd = ffbar -> DP. +inclusive = "c" # True = all processes if "c" only ccbar -> HNL, if "b" only bbar -> HNL, if "bc" only Bc+/Bc- -> HNL, and for darkphotons: if meson = production through meson decays, pbrem = proton bremstrahlung, qcd = ffbar -> DP. -MCTracksWithHitsOnly = False # copy particles which produced a hit and their history -MCTracksWithEnergyCutOnly = True # copy particles above a certain kin energy cut -MCTracksWithHitsOrEnergyCut = False # or of above, factor 2 file size increase compared to MCTracksWithEnergyCutOnly +MCTracksWithHitsOnly = False # copy particles which produced a hit and their history +MCTracksWithEnergyCutOnly = True # copy particles above a certain kin energy cut +MCTracksWithHitsOrEnergyCut = False # or of above, factor 2 file size increase compared to MCTracksWithEnergyCutOnly -charmonly = False # option to be set with -A to enable only charm decays, charm x-sec measurement -HNL = True +charmonly = False # option to be set with -A to enable only charm decays, charm x-sec measurement +HNL = True -inputFile = "/eos/experiment/ship/data/Charm/Cascade-parp16-MSTP82-1-MSEL4-978Bpot.root" +inputFile = "/eos/experiment/ship/data/Charm/Cascade-parp16-MSTP82-1-MSEL4-978Bpot.root" defaultInputFile = True globalDesigns = { - '2016' : { - 'dy' : 10., - 'dv' : 5, - 'ds' : 7, - 'nud' : 1, - 'caloDesign' : 0, - 'strawDesign' : 4 - }, '2018' : { - 'dy' : 10., - 'dv' : 6, - 'ds' : 9, - 'nud' : 3, - 'caloDesign' : 3, - 'strawDesign' : 10 - }, '2022' : { - 'dy' : 8., - 'dv' : 6, - 'ds' : 9, - 'nud' : 3, - 'caloDesign' : 3, - 'strawDesign' : 10 - }, '2023' : { - 'dy' : 6., - 'dv' : 6, - 'ds' : 8, - 'nud' : 4, - 'caloDesign' : 3, - 'strawDesign' : 10 - } + "2016": {"dy": 10.0, "dv": 5, "ds": 7, "nud": 1, "caloDesign": 0, "strawDesign": 4}, + "2018": { + "dy": 10.0, + "dv": 6, + "ds": 9, + "nud": 3, + "caloDesign": 3, + "strawDesign": 10, + }, + "2022": {"dy": 8.0, "dv": 6, "ds": 9, "nud": 3, "caloDesign": 3, "strawDesign": 10}, + "2023": {"dy": 6.0, "dv": 6, "ds": 8, "nud": 4, "caloDesign": 3, "strawDesign": 10}, } -default = '2023' +default = "2023" -inactivateMuonProcesses = False # provisionally for making studies of various muon background sources +inactivateMuonProcesses = ( + False # provisionally for making studies of various muon background sources +) parser = ArgumentParser() group = parser.add_mutually_exclusive_group() parser.add_argument("--evtcalc", help="Use EventCalc", action="store_true") -parser.add_argument("--Pythia6", dest="pythia6", help="Use Pythia6", required=False, action="store_true") -parser.add_argument("--Pythia8", dest="pythia8", help="Use Pythia8", required=False, action="store_true") -parser.add_argument("--PG", dest="pg", help="Use Particle Gun", required=False, action="store_true") -parser.add_argument("--pID", dest="pID", help="id of particle used by the gun (default=22)", required=False, default=22, type=int) -parser.add_argument("--Estart", help="start of energy range of particle gun (default=10 GeV)", default=10, type=float) -parser.add_argument("--Eend", help="end of energy range of particle gun (default=10 GeV)", default=10, type=float) -parser.add_argument("-A", dest="A", help="b: signal from b, c: from c (default), bc: from Bc, or inclusive", required=False, default='c') -parser.add_argument("--Genie", dest="genie", help="Genie for reading and processing neutrino interactions", required=False, action="store_true") -parser.add_argument("--NuRadio", dest="nuradio", help="misuse GenieGenerator for neutrino radiography and geometry timing test", required=False, action="store_true") -parser.add_argument("--Ntuple", dest="ntuple", help="Use ntuple as input", required=False, action="store_true") -parser.add_argument("--MuonBack",dest="muonback", help="Generate events from muon background file, --Cosmics=0 for cosmic generator data", required=False, action="store_true") -parser.add_argument("--FollowMuon",dest="followMuon", help="Make muonshield active to follow muons", required=False, action="store_true") -parser.add_argument("--FastMuon", dest="fastMuon", help="Only transport muons for a fast muon only background estimate", required=False, action="store_true") -parser.add_argument("--Nuage", dest="nuage", help="Use Nuage, neutrino generator of OPERA", required=False, action="store_true") -parser.add_argument("--phiRandom", dest="phiRandom", help="only relevant for muon background generator, random phi", required=False, action="store_true") -parser.add_argument("--Cosmics", dest="cosmics", help="Use cosmic generator, argument switch for cosmic generator 0 or 1", required=False, default=None) -parser.add_argument("--MuDIS", dest="mudis", help="Use muon deep inelastic scattering generator", required=False, action="store_true") -parser.add_argument("--RpvSusy", dest="RPVSUSY", help="Generate events based on RPV neutralino", required=False, action="store_true") -parser.add_argument("--DarkPhoton", dest="DarkPhoton", help="Generate dark photons", required=False, action="store_true") -parser.add_argument("--SusyBench", dest="RPVSUSYbench", help="Generate HP Susy", required=False, default=2) -parser.add_argument("-m", "--mass", dest="theMass", help="Mass of hidden particle, default "+str(theHNLMass)+"GeV for HNL, "+str(theDPmass)+"GeV for DP", required=False, default=None, type=float) -parser.add_argument("-c", "--couplings", "--coupling", dest="thecouplings", help="couplings \'U2e,U2mu,U2tau\' or -c \'U2e,U2mu,U2tau\' to set list of HNL couplings.\ - TP default for HNL, ctau=53.3km", required=False,default="0.447e-9,7.15e-9,1.88e-9") -parser.add_argument("-cp", "--production-couplings", dest="theprodcouplings", help="production couplings \'U2e,U2mu,U2tau\' to set the couplings for HNL production only"\ - ,required=False,default=None) -parser.add_argument("-cd", "--decay-couplings", dest="thedeccouplings", help="decay couplings \'U2e,U2mu,U2tau\' to set the couplings for HNL decay only", required=False,default=None) -parser.add_argument("-e", "--epsilon", dest="theDPepsilon", help="to set mixing parameter epsilon", required=False,default=0.00000008, type=float) -parser.add_argument("-n", "--nEvents",dest="nEvents", help="Number of events to generate", required=False, default=100, type=int) -parser.add_argument("-i", "--firstEvent",dest="firstEvent", help="First event of input file to use", required=False, default=0, type=int) -parser.add_argument("-s", "--seed",dest="theSeed", help="Seed for random number. Only for experts, see TRrandom::SetSeed documentation", required=False, default=0, type=int) -parser.add_argument("-S", "--sameSeed",dest="sameSeed", help="can be set to an integer for the muonBackground simulation with specific seed for each muon, only for experts!"\ - ,required=False, default=False, type=int) -group.add_argument("-f", dest="inputFile", help="Input file if not default file", required=False, default=False) -parser.add_argument("-g", dest="geofile", help="geofile for muon shield geometry, for experts only", required=False, default=None) -parser.add_argument("-o", "--output",dest="outputDir", help="Output directory", required=False, default=".") -parser.add_argument("-Y", dest="dy", help="max height of vacuum tank", required=False, default=globalDesigns[default]['dy']) -parser.add_argument("--tankDesign", dest="dv", help="4=TP elliptical tank design, 5 = optimized conical rectangular design, 6=5 without segment-1"\ - ,required=False, default=globalDesigns[default]['dv'], type=int) -parser.add_argument("--muShieldDesign", dest="ds", help="7=short magnet design, 9=optimised with T4 as constraint, 8=requires config file\ - ,10=with field map for hadron absorber", required=False, choices=range(7,11), default=globalDesigns[default]['ds'], type=int) -parser.add_argument("--nuTauTargetDesign", dest="nud"\ - ,help="0=TP, 1=new magnet option for short muon shield, 2= no magnet surrounding neutrino detector, 3= emulsion spectrometer and muon filter as in CDS, 4= not magnetized target and muon spectrometer for ECN3",required=False, default=globalDesigns[default]['nud'], type=int) -parser.add_argument("--caloDesign", - help="0=ECAL/HCAL TP 2=splitCal 3=ECAL/ passive HCAL", - default=globalDesigns[default]['caloDesign'], - type=int, - choices=[0,2,3]) -parser.add_argument("--strawDesign", dest="strawDesign", help="simplistic tracker design, 4=sophisticated straw tube design, horizontal wires (default), 10=2cm straw" - ,required=False, default=globalDesigns[default]['strawDesign'], type=int) -parser.add_argument("-F", dest="deepCopy", help="default = False: copy only stable particles to stack, except for HNL events", required=False, action="store_true") -parser.add_argument("-t", "--test", dest="testFlag", help="quick test", required=False,action="store_true") -parser.add_argument("--dry-run", dest="dryrun", help="stop after initialize", required=False,action="store_true") -parser.add_argument("-D", "--display", dest="eventDisplay", help="store trajectories", required=False, action="store_true") -parser.add_argument("--stepMuonShield", dest="muShieldStepGeo", help="activate steps geometry for the muon shield", required=False, action="store_true", default=False) -parser.add_argument("--coMuonShield", dest="muShieldWithCobaltMagnet", help="replace one of the magnets in the shield with 2.2T cobalt one, downscales other fields, works only for muShieldDesign >2", required=False, type=int, default=0) -parser.add_argument("--noSC", dest="SC_mag", help="Deactivate SC muon shield. Configuration: 1 SC magnet (3*B_warm) + 3 warm magnets with inverted fields", action='store_false') -parser.add_argument("--scName", help="The name of the SC shield in the database", default="sc_v6") -parser.add_argument("--MesonMother", dest="MM", help="Choose DP production meson source", required=False, default=True) -parser.add_argument("--debug", help="1: print weights and field 2: make overlap check", required=False, default=0, type=int, choices=range(0,3)) +parser.add_argument( + "--Pythia6", dest="pythia6", help="Use Pythia6", required=False, action="store_true" +) +parser.add_argument( + "--Pythia8", dest="pythia8", help="Use Pythia8", required=False, action="store_true" +) +parser.add_argument( + "--PG", dest="pg", help="Use Particle Gun", required=False, action="store_true" +) +parser.add_argument( + "--pID", + dest="pID", + help="id of particle used by the gun (default=22)", + required=False, + default=22, + type=int, +) +parser.add_argument( + "--Estart", + help="start of energy range of particle gun (default=10 GeV)", + default=10, + type=float, +) +parser.add_argument( + "--Eend", + help="end of energy range of particle gun (default=10 GeV)", + default=10, + type=float, +) +parser.add_argument( + "-A", + dest="A", + help="b: signal from b, c: from c (default), bc: from Bc, or inclusive", + required=False, + default="c", +) +parser.add_argument( + "--Genie", + dest="genie", + help="Genie for reading and processing neutrino interactions", + required=False, + action="store_true", +) +parser.add_argument( + "--NuRadio", + dest="nuradio", + help="misuse GenieGenerator for neutrino radiography and geometry timing test", + required=False, + action="store_true", +) +parser.add_argument( + "--Ntuple", + dest="ntuple", + help="Use ntuple as input", + required=False, + action="store_true", +) +parser.add_argument( + "--MuonBack", + dest="muonback", + help="Generate events from muon background file, --Cosmics=0 for cosmic generator data", + required=False, + action="store_true", +) +parser.add_argument( + "--FollowMuon", + dest="followMuon", + help="Make muonshield active to follow muons", + required=False, + action="store_true", +) +parser.add_argument( + "--FastMuon", + dest="fastMuon", + help="Only transport muons for a fast muon only background estimate", + required=False, + action="store_true", +) +parser.add_argument( + "--Nuage", + dest="nuage", + help="Use Nuage, neutrino generator of OPERA", + required=False, + action="store_true", +) +parser.add_argument( + "--phiRandom", + dest="phiRandom", + help="only relevant for muon background generator, random phi", + required=False, + action="store_true", +) +parser.add_argument( + "--Cosmics", + dest="cosmics", + help="Use cosmic generator, argument switch for cosmic generator 0 or 1", + required=False, + default=None, +) +parser.add_argument( + "--MuDIS", + dest="mudis", + help="Use muon deep inelastic scattering generator", + required=False, + action="store_true", +) +parser.add_argument( + "--RpvSusy", + dest="RPVSUSY", + help="Generate events based on RPV neutralino", + required=False, + action="store_true", +) +parser.add_argument( + "--DarkPhoton", + dest="DarkPhoton", + help="Generate dark photons", + required=False, + action="store_true", +) +parser.add_argument( + "--SusyBench", + dest="RPVSUSYbench", + help="Generate HP Susy", + required=False, + default=2, +) +parser.add_argument( + "-m", + "--mass", + dest="theMass", + help="Mass of hidden particle, default " + + str(theHNLMass) + + "GeV for HNL, " + + str(theDPmass) + + "GeV for DP", + required=False, + default=None, + type=float, +) +parser.add_argument( + "-c", + "--couplings", + "--coupling", + dest="thecouplings", + help="couplings 'U2e,U2mu,U2tau' or -c 'U2e,U2mu,U2tau' to set list of HNL couplings.\ + TP default for HNL, ctau=53.3km", + required=False, + default="0.447e-9,7.15e-9,1.88e-9", +) +parser.add_argument( + "-cp", + "--production-couplings", + dest="theprodcouplings", + help="production couplings 'U2e,U2mu,U2tau' to set the couplings for HNL production only", + required=False, + default=None, +) +parser.add_argument( + "-cd", + "--decay-couplings", + dest="thedeccouplings", + help="decay couplings 'U2e,U2mu,U2tau' to set the couplings for HNL decay only", + required=False, + default=None, +) +parser.add_argument( + "-e", + "--epsilon", + dest="theDPepsilon", + help="to set mixing parameter epsilon", + required=False, + default=0.00000008, + type=float, +) +parser.add_argument( + "-n", + "--nEvents", + dest="nEvents", + help="Number of events to generate", + required=False, + default=100, + type=int, +) +parser.add_argument( + "-i", + "--firstEvent", + dest="firstEvent", + help="First event of input file to use", + required=False, + default=0, + type=int, +) +parser.add_argument( + "-s", + "--seed", + dest="theSeed", + help="Seed for random number. Only for experts, see TRrandom::SetSeed documentation", + required=False, + default=0, + type=int, +) +parser.add_argument( + "-S", + "--sameSeed", + dest="sameSeed", + help="can be set to an integer for the muonBackground simulation with specific seed for each muon, only for experts!", + required=False, + default=False, + type=int, +) +group.add_argument( + "-f", + dest="inputFile", + help="Input file if not default file", + required=False, + default=False, +) +parser.add_argument( + "-g", + dest="geofile", + help="geofile for muon shield geometry, for experts only", + required=False, + default=None, +) +parser.add_argument( + "-o", + "--output", + dest="outputDir", + help="Output directory", + required=False, + default=".", +) +parser.add_argument( + "-Y", + dest="dy", + help="max height of vacuum tank", + required=False, + default=globalDesigns[default]["dy"], +) +parser.add_argument( + "--tankDesign", + dest="dv", + help="4=TP elliptical tank design, 5 = optimized conical rectangular design, 6=5 without segment-1", + required=False, + default=globalDesigns[default]["dv"], + type=int, +) +parser.add_argument( + "--muShieldDesign", + dest="ds", + help="7=short magnet design, 9=optimised with T4 as constraint, 8=requires config file\ + ,10=with field map for hadron absorber", + required=False, + choices=range(7, 11), + default=globalDesigns[default]["ds"], + type=int, +) +parser.add_argument( + "--nuTauTargetDesign", + dest="nud", + help="0=TP, 1=new magnet option for short muon shield, 2= no magnet surrounding neutrino detector, 3= emulsion spectrometer and muon filter as in CDS, 4= not magnetized target and muon spectrometer for ECN3", + required=False, + default=globalDesigns[default]["nud"], + type=int, +) +parser.add_argument( + "--caloDesign", + help="0=ECAL/HCAL TP 2=splitCal 3=ECAL/ passive HCAL", + default=globalDesigns[default]["caloDesign"], + type=int, + choices=[0, 2, 3], +) +parser.add_argument( + "--strawDesign", + dest="strawDesign", + help="simplistic tracker design, 4=sophisticated straw tube design, horizontal wires (default), 10=2cm straw", + required=False, + default=globalDesigns[default]["strawDesign"], + type=int, +) +parser.add_argument( + "-F", + dest="deepCopy", + help="default = False: copy only stable particles to stack, except for HNL events", + required=False, + action="store_true", +) +parser.add_argument( + "-t", + "--test", + dest="testFlag", + help="quick test", + required=False, + action="store_true", +) +parser.add_argument( + "--dry-run", + dest="dryrun", + help="stop after initialize", + required=False, + action="store_true", +) +parser.add_argument( + "-D", + "--display", + dest="eventDisplay", + help="store trajectories", + required=False, + action="store_true", +) +parser.add_argument( + "--stepMuonShield", + dest="muShieldStepGeo", + help="activate steps geometry for the muon shield", + required=False, + action="store_true", + default=False, +) +parser.add_argument( + "--coMuonShield", + dest="muShieldWithCobaltMagnet", + help="replace one of the magnets in the shield with 2.2T cobalt one, downscales other fields, works only for muShieldDesign >2", + required=False, + type=int, + default=0, +) +parser.add_argument( + "--noSC", + dest="SC_mag", + help="Deactivate SC muon shield. Configuration: 1 SC magnet (3*B_warm) + 3 warm magnets with inverted fields", + action="store_false", +) +parser.add_argument( + "--scName", help="The name of the SC shield in the database", default="sc_v6" +) +parser.add_argument( + "--MesonMother", + dest="MM", + help="Choose DP production meson source", + required=False, + default=True, +) +parser.add_argument( + "--debug", + help="1: print weights and field 2: make overlap check", + required=False, + default=0, + type=int, + choices=range(0, 3), +) parser.add_argument( "--helium", - dest="decayVolMed", + dest="decayVolMed", help="Set Decay Volume medium to helium. NOOP, as default is helium", action="store_const", const="helium", - default="helium" + default="helium", ) parser.add_argument( "--vacuums", @@ -148,111 +427,147 @@ help="Set Decay Volume medium to vacuum(vessel structure changes)", action="store_const", const="vacuums", - default="helium" + default="helium", +) +parser.add_argument("--SND", dest="SND", help="Activate SND.", action="store_true") +parser.add_argument( + "--noSND", + dest="SND", + help="Deactivate SND. NOOP, as it currently defaults to off.", + action="store_false", ) -parser.add_argument("--SND", dest="SND", help="Activate SND.", action='store_true') -parser.add_argument("--noSND", dest="SND", help="Deactivate SND. NOOP, as it currently defaults to off.", action='store_false') options = parser.parse_args() -if options.evtcalc: simEngine = "EvtCalc" -if options.pythia6: simEngine = "Pythia6" -if options.pythia8: simEngine = "Pythia8" -if options.pg: simEngine = "PG" -if options.genie: simEngine = "Genie" -if options.nuradio: simEngine = "nuRadiography" -if options.ntuple: simEngine = "Ntuple" -if options.muonback: simEngine = "MuonBack" -if options.nuage: simEngine = "Nuage" -if options.mudis: simEngine = "muonDIS" -if options.A != 'c': - inclusive = options.A - if options.A =='b': inputFile = "/eos/experiment/ship/data/Beauty/Cascade-run0-19-parp16-MSTP82-1-MSEL5-5338Bpot.root" - if options.A.lower() == 'charmonly': - charmonly = True - HNL = False - if options.A not in ['b','c','bc','meson','pbrem','qcd']: inclusive = True +if options.evtcalc: + simEngine = "EvtCalc" +if options.pythia6: + simEngine = "Pythia6" +if options.pythia8: + simEngine = "Pythia8" +if options.pg: + simEngine = "PG" +if options.genie: + simEngine = "Genie" +if options.nuradio: + simEngine = "nuRadiography" +if options.ntuple: + simEngine = "Ntuple" +if options.muonback: + simEngine = "MuonBack" +if options.nuage: + simEngine = "Nuage" +if options.mudis: + simEngine = "muonDIS" +if options.A != "c": + inclusive = options.A + if options.A == "b": + inputFile = "/eos/experiment/ship/data/Beauty/Cascade-run0-19-parp16-MSTP82-1-MSEL5-5338Bpot.root" + if options.A.lower() == "charmonly": + charmonly = True + HNL = False + if options.A not in ["b", "c", "bc", "meson", "pbrem", "qcd"]: + inclusive = True if options.MM: - motherMode=options.MM + motherMode = options.MM if options.cosmics: - simEngine = "Cosmics" - Opt_high = int(options.cosmics) + simEngine = "Cosmics" + Opt_high = int(options.cosmics) if options.inputFile: - if options.inputFile == "none": options.inputFile = None - inputFile = options.inputFile - defaultInputFile = False -if options.RPVSUSY: HNL = False -if options.DarkPhoton: HNL = False + if options.inputFile == "none": + options.inputFile = None + inputFile = options.inputFile + defaultInputFile = False +if options.RPVSUSY: + HNL = False +if options.DarkPhoton: + HNL = False if not options.theMass: - if options.DarkPhoton: options.theMass = theDPmass - else: options.theMass = theHNLMass + if options.DarkPhoton: + options.theMass = theDPmass + else: + options.theMass = theHNLMass if options.thecouplings: - theCouplings = [float(c) for c in options.thecouplings.split(",")] + theCouplings = [float(c) for c in options.thecouplings.split(",")] if options.theprodcouplings: - theProductionCouplings = [float(c) for c in options.theprodcouplings.split(",")] + theProductionCouplings = [float(c) for c in options.theprodcouplings.split(",")] if options.thedeccouplings: - theDecayCouplings = [float(c) for c in options.thedeccouplings.split(",")] + theDecayCouplings = [float(c) for c in options.thedeccouplings.split(",")] if options.testFlag: - inputFile = "$FAIRSHIP/files/Cascade-parp16-MSTP82-1-MSEL4-76Mpot_1_5000.root" + inputFile = "$FAIRSHIP/files/Cascade-parp16-MSTP82-1-MSEL4-76Mpot_1_5000.root" -#sanity check -if (HNL and options.RPVSUSY) or (HNL and options.DarkPhoton) or (options.DarkPhoton and options.RPVSUSY): - print("cannot have HNL and SUSY or DP at the same time, abort") - sys.exit(2) +# sanity check +if ( + (HNL and options.RPVSUSY) + or (HNL and options.DarkPhoton) + or (options.DarkPhoton and options.RPVSUSY) +): + print("cannot have HNL and SUSY or DP at the same time, abort") + sys.exit(2) if (simEngine == "Genie" or simEngine == "nuRadiography") and defaultInputFile: - inputFile = "/eos/experiment/ship/data/GenieEvents/genie-nu_mu.root" - # "/eos/experiment/ship/data/GenieEvents/genie-nu_mu_bar.root" + inputFile = "/eos/experiment/ship/data/GenieEvents/genie-nu_mu.root" + # "/eos/experiment/ship/data/GenieEvents/genie-nu_mu_bar.root" if simEngine == "muonDIS" and defaultInputFile: - print('input file required if simEngine = muonDIS') - print(" for example -f /eos/experiment/ship/data/muonDIS/muonDis_1.root") - sys.exit() + print("input file required if simEngine = muonDIS") + print(" for example -f /eos/experiment/ship/data/muonDIS/muonDis_1.root") + sys.exit() if simEngine == "Nuage" and not inputFile: - inputFile = 'Numucc.root' - -print("FairShip setup for",simEngine,"to produce",options.nEvents,"events") -if (simEngine == "Ntuple" or simEngine == "MuonBack") and defaultInputFile : - print('input file required if simEngine = Ntuple or MuonBack') - print(" for example -f /eos/experiment/ship/data/Mbias/pythia8_Geant4-withCharm_onlyMuons_4magTarget.root") - sys.exit() -ROOT.gRandom.SetSeed(options.theSeed) # this should be propagated via ROOT to Pythia8 and Geant4VMC -shipRoot_conf.configure(0) # load basic libraries, prepare atexit for python + inputFile = "Numucc.root" + +print("FairShip setup for", simEngine, "to produce", options.nEvents, "events") +if (simEngine == "Ntuple" or simEngine == "MuonBack") and defaultInputFile: + print("input file required if simEngine = Ntuple or MuonBack") + print( + " for example -f /eos/experiment/ship/data/Mbias/pythia8_Geant4-withCharm_onlyMuons_4magTarget.root" + ) + sys.exit() +ROOT.gRandom.SetSeed( + options.theSeed +) # this should be propagated via ROOT to Pythia8 and Geant4VMC +shipRoot_conf.configure(0) # load basic libraries, prepare atexit for python # - muShieldDesign = 7 # 7 = short design+magnetized hadron absorber # - targetOpt = 5 # 0=solid >0 sliced, 5: 5 pieces of tungsten, 4 H20 slits, 17: Mo + W +H2O (default) # nuTauTargetDesign = 0 # 0 = TP, 1 = NEW with magnet, 2 = NEW without magnet, 3 = 2018 design ship_geo = ConfigRegistry.loadpy( - "$FAIRSHIP/geometry/geometry_config.py", - Yheight=options.dy, - tankDesign=options.dv, - muShieldDesign=options.ds, - nuTauTargetDesign=options.nud, - CaloDesign=options.caloDesign, - strawDesign=options.strawDesign, - muShieldGeo=options.geofile, - muShieldStepGeo=options.muShieldStepGeo, - muShieldWithCobaltMagnet=options.muShieldWithCobaltMagnet, - SC_mag=options.SC_mag, - scName=options.scName, - DecayVolumeMedium=options.decayVolMed, - SND=options.SND, + "$FAIRSHIP/geometry/geometry_config.py", + Yheight=options.dy, + tankDesign=options.dv, + muShieldDesign=options.ds, + nuTauTargetDesign=options.nud, + CaloDesign=options.caloDesign, + strawDesign=options.strawDesign, + muShieldGeo=options.geofile, + muShieldStepGeo=options.muShieldStepGeo, + muShieldWithCobaltMagnet=options.muShieldWithCobaltMagnet, + SC_mag=options.SC_mag, + scName=options.scName, + DecayVolumeMedium=options.decayVolMed, + SND=options.SND, ) # Output file name, add dy to be able to setup geometry with ambiguities. -if simEngine == "PG": tag = simEngine + "_"+str(options.pID)+"-"+mcEngine -else: tag = simEngine+"-"+mcEngine -if charmonly: tag = simEngine+"CharmOnly-"+mcEngine -if options.eventDisplay: tag = tag+'_D' -if options.dv > 4 : tag = 'conical.'+tag +if simEngine == "PG": + tag = simEngine + "_" + str(options.pID) + "-" + mcEngine +else: + tag = simEngine + "-" + mcEngine +if charmonly: + tag = simEngine + "CharmOnly-" + mcEngine +if options.eventDisplay: + tag = tag + "_D" +if options.dv > 4: + tag = "conical." + tag if not os.path.exists(options.outputDir): - os.makedirs(options.outputDir) + os.makedirs(options.outputDir) outFile = "%s/ship.%s.root" % (options.outputDir, tag) # rm older files !!! for x in os.listdir(options.outputDir): - if not x.find(tag)<0: os.system("rm %s/%s" % (options.outputDir, x) ) + if not x.find(tag) < 0: + os.system("rm %s/%s" % (options.outputDir, x)) # Parameter file name -parFile="%s/ship.params.%s.root" % (options.outputDir, tag) +parFile = "%s/ship.params.%s.root" % (options.outputDir, tag) # In general, the following parts need not be touched # ======================================================================== @@ -265,91 +580,125 @@ run = ROOT.FairRunSim() run.SetName(mcEngine) # Transport engine run.SetSink(ROOT.FairRootFileSink(outFile)) # Output file -run.SetUserConfig("g4Config.C") # user configuration file default g4Config.C +run.SetUserConfig("g4Config.C") # user configuration file default g4Config.C rtdb = run.GetRuntimeDb() # -----Create geometry---------------------------------------------- # import shipMuShield_only as shipDet_conf # special use case for an attempt to convert active shielding geometry for use with FLUKA # import shipTarget_only as shipDet_conf import shipDet_conf -modules = shipDet_conf.configure(run,ship_geo) +modules = shipDet_conf.configure(run, ship_geo) # -----Create PrimaryGenerator-------------------------------------- primGen = ROOT.FairPrimaryGenerator() if simEngine == "Pythia8": - primGen.SetTarget(ship_geo.target.z0, 0.) -# -----Pythia8-------------------------------------- - if HNL or options.RPVSUSY: - P8gen = ROOT.HNLPythia8Generator() - import pythia8_conf - if HNL: - print('Generating HNL events of mass %.3f GeV'%options.theMass) - if theProductionCouplings is None and theDecayCouplings is None: - print('and with couplings=',theCouplings) - theProductionCouplings = theDecayCouplings = theCouplings - elif theProductionCouplings is not None and theDecayCouplings is not None: - print('and with couplings',theProductionCouplings,'at production') - print('and',theDecayCouplings,'at decay') - else: - raise ValueError('Either both production and decay couplings must be specified, or neither.') - pythia8_conf.configure(P8gen,options.theMass,theProductionCouplings,theDecayCouplings,inclusive,options.deepCopy) - if options.RPVSUSY: - print('Generating RPVSUSY events of mass %.3f GeV'%theHNLMass) - print('and with couplings=[%.3f,%.3f]'%(theCouplings[0],theCouplings[1])) - print('and with stop mass=%.3f GeV\n'%theCouplings[2]) - pythia8_conf.configurerpvsusy(P8gen,options.theMass,[theCouplings[0],theCouplings[1]], - theCouplings[2],options.RPVSUSYbench,inclusive,options.deepCopy) - P8gen.SetParameters("ProcessLevel:all = off") - if inputFile: - ut.checkFileExists(inputFile) -# read from external file - P8gen.UseExternalFile(inputFile, options.firstEvent) - if options.DarkPhoton: - P8gen = ROOT.DPPythia8Generator() - if inclusive=='qcd': - P8gen.SetDPId(4900023) - else: - P8gen.SetDPId(9900015) - import pythia8darkphoton_conf - passDPconf = pythia8darkphoton_conf.configure(P8gen,options.theMass,options.theDPepsilon,inclusive, motherMode, options.deepCopy) - if (passDPconf!=1): sys.exit() - if HNL or options.RPVSUSY or options.DarkPhoton: - P8gen.SetSmearBeam(1*u.cm) # finite beam size - P8gen.SetLmin((ship_geo.Chamber1.z - ship_geo.chambers.Tub1length) - ship_geo.target.z0 ) - P8gen.SetLmax(ship_geo.TrackStation1.z - ship_geo.target.z0 ) - if charmonly: - primGen.SetTarget(0., 0.) #vertex is setted in pythia8Generator - ut.checkFileExists(inputFile) - if ship_geo.Box.gausbeam: - primGen.SetBeam(0.,0., 0.5, 0.5) #more central beam, for hits in downstream detectors - primGen.SmearGausVertexXY(True) #sigma = x - else: - primGen.SetBeam(0.,0., ship_geo.Box.TX-1., ship_geo.Box.TY-1.) #Uniform distribution in x/y on the target (0.5 cm of margin at both sides) - primGen.SmearVertexXY(True) - P8gen = ROOT.Pythia8Generator() - P8gen.UseExternalFile(inputFile, options.firstEvent) - P8gen.SetTarget("volTarget_1",0.,0.) # will distribute PV inside target, beam offset x=y=0. -# pion on proton 500GeV -# P8gen.SetMom(500.*u.GeV) -# P8gen.SetId(-211) - primGen.AddGenerator(P8gen) + primGen.SetTarget(ship_geo.target.z0, 0.0) + # -----Pythia8-------------------------------------- + if HNL or options.RPVSUSY: + P8gen = ROOT.HNLPythia8Generator() + import pythia8_conf + + if HNL: + print("Generating HNL events of mass %.3f GeV" % options.theMass) + if theProductionCouplings is None and theDecayCouplings is None: + print("and with couplings=", theCouplings) + theProductionCouplings = theDecayCouplings = theCouplings + elif theProductionCouplings is not None and theDecayCouplings is not None: + print("and with couplings", theProductionCouplings, "at production") + print("and", theDecayCouplings, "at decay") + else: + raise ValueError( + "Either both production and decay couplings must be specified, or neither." + ) + pythia8_conf.configure( + P8gen, + options.theMass, + theProductionCouplings, + theDecayCouplings, + inclusive, + options.deepCopy, + ) + if options.RPVSUSY: + print("Generating RPVSUSY events of mass %.3f GeV" % theHNLMass) + print("and with couplings=[%.3f,%.3f]" % (theCouplings[0], theCouplings[1])) + print("and with stop mass=%.3f GeV\n" % theCouplings[2]) + pythia8_conf.configurerpvsusy( + P8gen, + options.theMass, + [theCouplings[0], theCouplings[1]], + theCouplings[2], + options.RPVSUSYbench, + inclusive, + options.deepCopy, + ) + P8gen.SetParameters("ProcessLevel:all = off") + if inputFile: + ut.checkFileExists(inputFile) + # read from external file + P8gen.UseExternalFile(inputFile, options.firstEvent) + if options.DarkPhoton: + P8gen = ROOT.DPPythia8Generator() + if inclusive == "qcd": + P8gen.SetDPId(4900023) + else: + P8gen.SetDPId(9900015) + import pythia8darkphoton_conf + + passDPconf = pythia8darkphoton_conf.configure( + P8gen, + options.theMass, + options.theDPepsilon, + inclusive, + motherMode, + options.deepCopy, + ) + if passDPconf != 1: + sys.exit() + if HNL or options.RPVSUSY or options.DarkPhoton: + P8gen.SetSmearBeam(1 * u.cm) # finite beam size + P8gen.SetLmin( + (ship_geo.Chamber1.z - ship_geo.chambers.Tub1length) - ship_geo.target.z0 + ) + P8gen.SetLmax(ship_geo.TrackStation1.z - ship_geo.target.z0) + if charmonly: + primGen.SetTarget(0.0, 0.0) # vertex is setted in pythia8Generator + ut.checkFileExists(inputFile) + if ship_geo.Box.gausbeam: + primGen.SetBeam( + 0.0, 0.0, 0.5, 0.5 + ) # more central beam, for hits in downstream detectors + primGen.SmearGausVertexXY(True) # sigma = x + else: + primGen.SetBeam( + 0.0, 0.0, ship_geo.Box.TX - 1.0, ship_geo.Box.TY - 1.0 + ) # Uniform distribution in x/y on the target (0.5 cm of margin at both sides) + primGen.SmearVertexXY(True) + P8gen = ROOT.Pythia8Generator() + P8gen.UseExternalFile(inputFile, options.firstEvent) + P8gen.SetTarget( + "volTarget_1", 0.0, 0.0 + ) # will distribute PV inside target, beam offset x=y=0. + # pion on proton 500GeV + # P8gen.SetMom(500.*u.GeV) + # P8gen.SetId(-211) + primGen.AddGenerator(P8gen) if simEngine == "FixedTarget": - P8gen = ROOT.FixedTargetGenerator() - P8gen.SetTarget("volTarget_1",0.,0.) - P8gen.SetMom(400.*u.GeV) - P8gen.SetEnergyCut(0.) - P8gen.SetHeartBeat(100000) - P8gen.SetG4only() - primGen.AddGenerator(P8gen) + P8gen = ROOT.FixedTargetGenerator() + P8gen.SetTarget("volTarget_1", 0.0, 0.0) + P8gen.SetMom(400.0 * u.GeV) + P8gen.SetEnergyCut(0.0) + P8gen.SetHeartBeat(100000) + P8gen.SetG4only() + primGen.AddGenerator(P8gen) if simEngine == "Pythia6": -# set muon interaction close to decay volume - primGen.SetTarget(ship_geo.target.z0+ship_geo.muShield.length, 0.) -# -----Pythia6------------------------- - test = ROOT.TPythia6() # don't know any other way of forcing to load lib - P6gen = ROOT.tPythia6Generator() - P6gen.SetMom(50.*u.GeV) - P6gen.SetTarget("gamma/mu+","n0") # default "gamma/mu-","p+" - primGen.AddGenerator(P6gen) + # set muon interaction close to decay volume + primGen.SetTarget(ship_geo.target.z0 + ship_geo.muShield.length, 0.0) + # -----Pythia6------------------------- + test = ROOT.TPythia6() # don't know any other way of forcing to load lib + P6gen = ROOT.tPythia6Generator() + P6gen.SetMom(50.0 * u.GeV) + P6gen.SetTarget("gamma/mu+", "n0") # default "gamma/mu-","p+" + primGen.AddGenerator(P6gen) # -----EvtCalc-------------------------------------- if simEngine == "EvtCalc": @@ -367,211 +716,298 @@ # -----Particle Gun----------------------- if simEngine == "PG": - myPgun = ROOT.FairBoxGenerator(options.pID,1) - myPgun.SetPRange(options.Estart,options.Eend) - myPgun.SetPhiRange(0, 360) # // Azimuth angle range [degree] - myPgun.SetXYZ(0.*u.cm, 0.*u.cm, 0.*u.cm) - myPgun.SetThetaRange(0,0) # // Polar angle in lab system range [degree] - primGen.AddGenerator(myPgun) + myPgun = ROOT.FairBoxGenerator(options.pID, 1) + myPgun.SetPRange(options.Estart, options.Eend) + myPgun.SetPhiRange(0, 360) # // Azimuth angle range [degree] + myPgun.SetXYZ(0.0 * u.cm, 0.0 * u.cm, 0.0 * u.cm) + myPgun.SetThetaRange(0, 0) # // Polar angle in lab system range [degree] + primGen.AddGenerator(myPgun) # -----muon DIS Background------------------------ if simEngine == "muonDIS": - ut.checkFileExists(inputFile) - primGen.SetTarget(0., 0.) - DISgen = ROOT.MuDISGenerator() - # from nu_tau detector to tracking station 2 - # mu_start, mu_end = ship_geo.tauMudet.zMudetC,ship_geo.TrackStation2.z - # - # in front of UVT up to tracking station 1 - mu_start, mu_end = ship_geo.Chamber1.z-ship_geo.chambers.Tub1length-10.*u.cm,ship_geo.TrackStation1.z - print('MuDIS position info input=',mu_start, mu_end) - DISgen.SetPositions(mu_start, mu_end) - DISgen.Init(inputFile,options.firstEvent) - primGen.AddGenerator(DISgen) - options.nEvents = min(options.nEvents,DISgen.GetNevents()) - inactivateMuonProcesses = True # avoid unwanted hadronic events of "incoming" muon flying backward - print('Generate ',options.nEvents,' with DIS input', ' first event',options.firstEvent) + ut.checkFileExists(inputFile) + primGen.SetTarget(0.0, 0.0) + DISgen = ROOT.MuDISGenerator() + # from nu_tau detector to tracking station 2 + # mu_start, mu_end = ship_geo.tauMudet.zMudetC,ship_geo.TrackStation2.z + # + # in front of UVT up to tracking station 1 + mu_start, mu_end = ( + ship_geo.Chamber1.z - ship_geo.chambers.Tub1length - 10.0 * u.cm, + ship_geo.TrackStation1.z, + ) + print("MuDIS position info input=", mu_start, mu_end) + DISgen.SetPositions(mu_start, mu_end) + DISgen.Init(inputFile, options.firstEvent) + primGen.AddGenerator(DISgen) + options.nEvents = min(options.nEvents, DISgen.GetNevents()) + inactivateMuonProcesses = ( + True # avoid unwanted hadronic events of "incoming" muon flying backward + ) + print( + "Generate ", + options.nEvents, + " with DIS input", + " first event", + options.firstEvent, + ) # -----neutrino interactions from nuage------------------------ if simEngine == "Nuage": - primGen.SetTarget(0., 0.) - Nuagegen = ROOT.NuageGenerator() - Nuagegen.EnableExternalDecayer(1) #with 0 external decayer is disable, 1 is enabled - print('Nuage position info input=',ship_geo.EmuMagnet.zC-ship_geo.NuTauTarget.zdim, ship_geo.EmuMagnet.zC+ship_geo.NuTauTarget.zdim) - #-------------------------------- - #to Generate neutrino interactions in the whole neutrino target -# Nuagegen.SetPositions(ship_geo.EmuMagnet.zC, ship_geo.NuTauTarget.zC-ship_geo.NuTauTarget.zdim/2, ship_geo.NuTauTarget.zC+ship_geo.NuTauTarget.zdim/2, -ship_geo.NuTauTarget.xdim/2, ship_geo.NuTauTarget.xdim/2, -ship_geo.NuTauTarget.ydim/2, ship_geo.NuTauTarget.ydim/2) - #-------------------------------- - #to Generate neutrino interactions ONLY in ONE brick - ntt = 6 - nXcells = 7 - nYcells = 3 - nZcells = ntt -1 - startx = -ship_geo.NuTauTarget.xdim/2. + nXcells*ship_geo.NuTauTarget.BrX - endx = -ship_geo.NuTauTarget.xdim/2. + (nXcells+1)*ship_geo.NuTauTarget.BrX - starty = -ship_geo.NuTauTarget.ydim/2. + nYcells*ship_geo.NuTauTarget.BrY - endy = - ship_geo.NuTauTarget.ydim/2. + (nYcells+1)*ship_geo.NuTauTarget.BrY - startz = ship_geo.EmuMagnet.zC - ship_geo.NuTauTarget.zdim/2. + ntt *ship_geo.NuTauTT.TTZ + nZcells * ship_geo.NuTauTarget.CellW - endz = ship_geo.EmuMagnet.zC - ship_geo.NuTauTarget.zdim/2. + ntt *ship_geo.NuTauTT.TTZ + nZcells * ship_geo.NuTauTarget.CellW + ship_geo.NuTauTarget.BrZ - Nuagegen.SetPositions(ship_geo.target.z0, startz, endz, startx, endx, starty, endy) - #-------------------------------- - ut.checkFileExists(inputFile) - Nuagegen.Init(inputFile,options.firstEvent) - primGen.AddGenerator(Nuagegen) - options.nEvents = min(options.nEvents,Nuagegen.GetNevents()) - run.SetPythiaDecayer("DecayConfigNuAge.C") - print('Generate ',options.nEvents,' with Nuage input', ' first event',options.firstEvent) + primGen.SetTarget(0.0, 0.0) + Nuagegen = ROOT.NuageGenerator() + Nuagegen.EnableExternalDecayer( + 1 + ) # with 0 external decayer is disable, 1 is enabled + print( + "Nuage position info input=", + ship_geo.EmuMagnet.zC - ship_geo.NuTauTarget.zdim, + ship_geo.EmuMagnet.zC + ship_geo.NuTauTarget.zdim, + ) + # -------------------------------- + # to Generate neutrino interactions in the whole neutrino target + # Nuagegen.SetPositions(ship_geo.EmuMagnet.zC, ship_geo.NuTauTarget.zC-ship_geo.NuTauTarget.zdim/2, ship_geo.NuTauTarget.zC+ship_geo.NuTauTarget.zdim/2, -ship_geo.NuTauTarget.xdim/2, ship_geo.NuTauTarget.xdim/2, -ship_geo.NuTauTarget.ydim/2, ship_geo.NuTauTarget.ydim/2) + # -------------------------------- + # to Generate neutrino interactions ONLY in ONE brick + ntt = 6 + nXcells = 7 + nYcells = 3 + nZcells = ntt - 1 + startx = -ship_geo.NuTauTarget.xdim / 2.0 + nXcells * ship_geo.NuTauTarget.BrX + endx = -ship_geo.NuTauTarget.xdim / 2.0 + (nXcells + 1) * ship_geo.NuTauTarget.BrX + starty = -ship_geo.NuTauTarget.ydim / 2.0 + nYcells * ship_geo.NuTauTarget.BrY + endy = -ship_geo.NuTauTarget.ydim / 2.0 + (nYcells + 1) * ship_geo.NuTauTarget.BrY + startz = ( + ship_geo.EmuMagnet.zC + - ship_geo.NuTauTarget.zdim / 2.0 + + ntt * ship_geo.NuTauTT.TTZ + + nZcells * ship_geo.NuTauTarget.CellW + ) + endz = ( + ship_geo.EmuMagnet.zC + - ship_geo.NuTauTarget.zdim / 2.0 + + ntt * ship_geo.NuTauTT.TTZ + + nZcells * ship_geo.NuTauTarget.CellW + + ship_geo.NuTauTarget.BrZ + ) + Nuagegen.SetPositions(ship_geo.target.z0, startz, endz, startx, endx, starty, endy) + # -------------------------------- + ut.checkFileExists(inputFile) + Nuagegen.Init(inputFile, options.firstEvent) + primGen.AddGenerator(Nuagegen) + options.nEvents = min(options.nEvents, Nuagegen.GetNevents()) + run.SetPythiaDecayer("DecayConfigNuAge.C") + print( + "Generate ", + options.nEvents, + " with Nuage input", + " first event", + options.firstEvent, + ) # -----Neutrino Background------------------------ if simEngine == "Genie": -# Genie - ut.checkFileExists(inputFile) - primGen.SetTarget(0., 0.) # do not interfere with GenieGenerator - Geniegen = ROOT.GenieGenerator() - Geniegen.Init(inputFile,options.firstEvent) - Geniegen.SetPositions(ship_geo.target.z0, ship_geo.tauMudet.zMudetC-5*u.m, ship_geo.TrackStation2.z) - primGen.AddGenerator(Geniegen) - options.nEvents = min(options.nEvents,Geniegen.GetNevents()) - run.SetPythiaDecayer("DecayConfigNuAge.C") - print('Generate ',options.nEvents,' with Genie input', ' first event',options.firstEvent) + # Genie + ut.checkFileExists(inputFile) + primGen.SetTarget(0.0, 0.0) # do not interfere with GenieGenerator + Geniegen = ROOT.GenieGenerator() + Geniegen.Init(inputFile, options.firstEvent) + Geniegen.SetPositions( + ship_geo.target.z0, + ship_geo.tauMudet.zMudetC - 5 * u.m, + ship_geo.TrackStation2.z, + ) + primGen.AddGenerator(Geniegen) + options.nEvents = min(options.nEvents, Geniegen.GetNevents()) + run.SetPythiaDecayer("DecayConfigNuAge.C") + print( + "Generate ", + options.nEvents, + " with Genie input", + " first event", + options.firstEvent, + ) if simEngine == "nuRadiography": - ut.checkFileExists(inputFile) - primGen.SetTarget(0., 0.) # do not interfere with GenieGenerator - Geniegen = ROOT.GenieGenerator() - Geniegen.Init(inputFile,options.firstEvent) - # Geniegen.SetPositions(ship_geo.target.z0, ship_geo.target.z0, ship_geo.MuonStation3.z) - Geniegen.SetPositions(ship_geo.target.z0, ship_geo.tauMudet.zMudetC, ship_geo.MuonStation3.z) - Geniegen.NuOnly() - primGen.AddGenerator(Geniegen) - print('Generate ',options.nEvents,' for nuRadiography', ' first event',options.firstEvent) -# add tungsten to PDG - pdg = ROOT.TDatabasePDG.Instance() - pdg.AddParticle('W','Ion', 1.71350e+02, True, 0., 74, 'XXX', 1000741840) -# - run.SetPythiaDecayer('DecayConfigPy8.C') - # this requires writing a C macro, would have been easier to do directly in python! - # for i in [431,421,411,-431,-421,-411]: - # ROOT.gMC.SetUserDecay(i) # Force the decay to be done w/external decayer + ut.checkFileExists(inputFile) + primGen.SetTarget(0.0, 0.0) # do not interfere with GenieGenerator + Geniegen = ROOT.GenieGenerator() + Geniegen.Init(inputFile, options.firstEvent) + # Geniegen.SetPositions(ship_geo.target.z0, ship_geo.target.z0, ship_geo.MuonStation3.z) + Geniegen.SetPositions( + ship_geo.target.z0, ship_geo.tauMudet.zMudetC, ship_geo.MuonStation3.z + ) + Geniegen.NuOnly() + primGen.AddGenerator(Geniegen) + print( + "Generate ", + options.nEvents, + " for nuRadiography", + " first event", + options.firstEvent, + ) + # add tungsten to PDG + pdg = ROOT.TDatabasePDG.Instance() + pdg.AddParticle("W", "Ion", 1.71350e02, True, 0.0, 74, "XXX", 1000741840) + # + run.SetPythiaDecayer("DecayConfigPy8.C") + # this requires writing a C macro, would have been easier to do directly in python! + # for i in [431,421,411,-431,-421,-411]: + # ROOT.gMC.SetUserDecay(i) # Force the decay to be done w/external decayer if simEngine == "Ntuple": -# reading previously processed muon events, [-50m - 50m] - ut.checkFileExists(inputFile) - primGen.SetTarget(ship_geo.target.z0+50*u.m,0.) - Ntuplegen = ROOT.NtupleGenerator() - Ntuplegen.Init(inputFile,options.firstEvent) - primGen.AddGenerator(Ntuplegen) - options.nEvents = min(options.nEvents,Ntuplegen.GetNevents()) - print('Process ',options.nEvents,' from input file') + # reading previously processed muon events, [-50m - 50m] + ut.checkFileExists(inputFile) + primGen.SetTarget(ship_geo.target.z0 + 50 * u.m, 0.0) + Ntuplegen = ROOT.NtupleGenerator() + Ntuplegen.Init(inputFile, options.firstEvent) + primGen.AddGenerator(Ntuplegen) + options.nEvents = min(options.nEvents, Ntuplegen.GetNevents()) + print("Process ", options.nEvents, " from input file") # if simEngine == "MuonBack": -# reading muon tracks from previous Pythia8/Geant4 simulation with charm replaced by cascade production - fileType = ut.checkFileExists(inputFile) - if fileType == 'tree': - # 2018 background production - primGen.SetTarget(ship_geo.target.z0+70.845*u.m,0.) - else: - primGen.SetTarget(ship_geo.target.z0+50*u.m,0.) - # - MuonBackgen = ROOT.MuonBackGenerator() - # MuonBackgen.FollowAllParticles() # will follow all particles after hadron absorber, not only muons - MuonBackgen.Init(inputFile,options.firstEvent,options.phiRandom) - MuonBackgen.SetSmearBeam(5 * u.cm) # radius of ring, thickness 8mm - if DownScaleDiMuon: - if inputFile[0:4] == "/eos": test = os.environ["EOSSHIP"]+inputFile - else: test = inputFile - testf = ROOT.TFile.Open(test) - if not testf.FileHeader.GetTitle().find('diMu100.0')<0: - MuonBackgen.SetDownScaleDiMuon() # avoid interference with boosted channels - print("MuonBackgenerator: set downscale for dimuon on") - testf.Close() - if options.sameSeed: MuonBackgen.SetSameSeed(options.sameSeed) - primGen.AddGenerator(MuonBackgen) - options.nEvents = min(options.nEvents,MuonBackgen.GetNevents()) - MCTracksWithHitsOnly = True # otherwise, output file becomes too big - print('Process ',options.nEvents,' from input file, with Phi random=',options.phiRandom, ' with MCTracksWithHitsOnly',MCTracksWithHitsOnly) - if options.followMuon : - options.fastMuon = True - modules['Veto'].SetFollowMuon() - if options.fastMuon : modules['Veto'].SetFastMuon() - - # optional, boost gamma2muon conversion - # ROOT.kShipMuonsCrossSectionFactor = 100. + # reading muon tracks from previous Pythia8/Geant4 simulation with charm replaced by cascade production + fileType = ut.checkFileExists(inputFile) + if fileType == "tree": + # 2018 background production + primGen.SetTarget(ship_geo.target.z0 + 70.845 * u.m, 0.0) + else: + primGen.SetTarget(ship_geo.target.z0 + 50 * u.m, 0.0) + # + MuonBackgen = ROOT.MuonBackGenerator() + # MuonBackgen.FollowAllParticles() # will follow all particles after hadron absorber, not only muons + MuonBackgen.Init(inputFile, options.firstEvent, options.phiRandom) + MuonBackgen.SetSmearBeam(5 * u.cm) # radius of ring, thickness 8mm + if DownScaleDiMuon: + if inputFile[0:4] == "/eos": + test = os.environ["EOSSHIP"] + inputFile + else: + test = inputFile + testf = ROOT.TFile.Open(test) + if not testf.FileHeader.GetTitle().find("diMu100.0") < 0: + MuonBackgen.SetDownScaleDiMuon() # avoid interference with boosted channels + print("MuonBackgenerator: set downscale for dimuon on") + testf.Close() + if options.sameSeed: + MuonBackgen.SetSameSeed(options.sameSeed) + primGen.AddGenerator(MuonBackgen) + options.nEvents = min(options.nEvents, MuonBackgen.GetNevents()) + MCTracksWithHitsOnly = True # otherwise, output file becomes too big + print( + "Process ", + options.nEvents, + " from input file, with Phi random=", + options.phiRandom, + " with MCTracksWithHitsOnly", + MCTracksWithHitsOnly, + ) + if options.followMuon: + options.fastMuon = True + modules["Veto"].SetFollowMuon() + if options.fastMuon: + modules["Veto"].SetFastMuon() + + # optional, boost gamma2muon conversion + # ROOT.kShipMuonsCrossSectionFactor = 100. # if simEngine == "Cosmics": - primGen.SetTarget(0., 0.) - Cosmicsgen = ROOT.CosmicsGenerator() - import CMBG_conf - CMBG_conf.configure(Cosmicsgen, ship_geo) - if not Cosmicsgen.Init(Opt_high): - print("initialization of cosmic background generator failed ",Opt_high) - sys.exit(0) - Cosmicsgen.n_EVENTS = options.nEvents - primGen.AddGenerator(Cosmicsgen) - print('Process ',options.nEvents,' Cosmic events with option ',Opt_high) + primGen.SetTarget(0.0, 0.0) + Cosmicsgen = ROOT.CosmicsGenerator() + import CMBG_conf + + CMBG_conf.configure(Cosmicsgen, ship_geo) + if not Cosmicsgen.Init(Opt_high): + print("initialization of cosmic background generator failed ", Opt_high) + sys.exit(0) + Cosmicsgen.n_EVENTS = options.nEvents + primGen.AddGenerator(Cosmicsgen) + print("Process ", options.nEvents, " Cosmic events with option ", Opt_high) # run.SetGenerator(primGen) # ------------------------------------------------------------------------ -#---Store the visualiztion info of the tracks, this make the output file very large!! -#--- Use it only to display but not for production! -if options.eventDisplay: run.SetStoreTraj(ROOT.kTRUE) -else: run.SetStoreTraj(ROOT.kFALSE) +# ---Store the visualiztion info of the tracks, this make the output file very large!! +# --- Use it only to display but not for production! +if options.eventDisplay: + run.SetStoreTraj(ROOT.kTRUE) +else: + run.SetStoreTraj(ROOT.kFALSE) # -----Initialize simulation run------------------------------------ run.Init() -if options.dryrun: # Early stop after setting up Pythia 8 - sys.exit(0) +if options.dryrun: # Early stop after setting up Pythia 8 + sys.exit(0) gMC = ROOT.TVirtualMC.GetMC() fStack = gMC.GetStack() if MCTracksWithHitsOnly: - fStack.SetMinPoints(1) - fStack.SetEnergyCut(-100.*u.MeV) + fStack.SetMinPoints(1) + fStack.SetEnergyCut(-100.0 * u.MeV) elif MCTracksWithEnergyCutOnly: - fStack.SetMinPoints(-1) - fStack.SetEnergyCut(100.*u.MeV) + fStack.SetMinPoints(-1) + fStack.SetEnergyCut(100.0 * u.MeV) elif MCTracksWithHitsOrEnergyCut: - fStack.SetMinPoints(1) - fStack.SetEnergyCut(100.*u.MeV) + fStack.SetMinPoints(1) + fStack.SetEnergyCut(100.0 * u.MeV) elif options.deepCopy: - fStack.SetMinPoints(0) - fStack.SetEnergyCut(0.*u.MeV) + fStack.SetMinPoints(0) + fStack.SetEnergyCut(0.0 * u.MeV) if options.eventDisplay: - # Set cuts for storing the trajectories, can only be done after initialization of run (?!) - trajFilter = ROOT.FairTrajFilter.Instance() - trajFilter.SetStepSizeCut(1*u.mm) - trajFilter.SetVertexCut(-20*u.m, -20*u.m,ship_geo.target.z0-1*u.m, 20*u.m, 20*u.m, 200.*u.m) - trajFilter.SetMomentumCutP(0.1*u.GeV) - trajFilter.SetEnergyCut(0., 400.*u.GeV) - trajFilter.SetStorePrimaries(ROOT.kTRUE) - trajFilter.SetStoreSecondaries(ROOT.kTRUE) + # Set cuts for storing the trajectories, can only be done after initialization of run (?!) + trajFilter = ROOT.FairTrajFilter.Instance() + trajFilter.SetStepSizeCut(1 * u.mm) + trajFilter.SetVertexCut( + -20 * u.m, + -20 * u.m, + ship_geo.target.z0 - 1 * u.m, + 20 * u.m, + 20 * u.m, + 200.0 * u.m, + ) + trajFilter.SetMomentumCutP(0.1 * u.GeV) + trajFilter.SetEnergyCut(0.0, 400.0 * u.GeV) + trajFilter.SetStorePrimaries(ROOT.kTRUE) + trajFilter.SetStoreSecondaries(ROOT.kTRUE) # The VMC sets the fields using the "/mcDet/setIsLocalMagField true" option in "gconfig/g4config.in" import geomGeant4 + # geomGeant4.setMagnetField() # replaced by VMC, only has effect if /mcDet/setIsLocalMagField false # Define extra VMC B fields not already set by the geometry definitions, e.g. a global field, # any field maps, or defining if any volumes feel only the local or local+global field. # For now, just keep the fields already defined by the C++ code, i.e comment out the fieldMaker -if hasattr(ship_geo.Bfield,"fieldMap"): - fieldMaker = geomGeant4.addVMCFields(ship_geo, '', True) +if hasattr(ship_geo.Bfield, "fieldMap"): + fieldMaker = geomGeant4.addVMCFields(ship_geo, "", True) # Print VMC fields and associated geometry objects if options.debug == 1: - geomGeant4.printVMCFields() - geomGeant4.printWeightsandFields(onlyWithField = True,\ - exclude=['DecayVolume','Tr1','Tr2','Tr3','Tr4','Veto','Ecal','Hcal','MuonDetector','SplitCal']) + geomGeant4.printVMCFields() + geomGeant4.printWeightsandFields( + onlyWithField=True, + exclude=[ + "DecayVolume", + "Tr1", + "Tr2", + "Tr3", + "Tr4", + "Veto", + "Ecal", + "Hcal", + "MuonDetector", + "SplitCal", + ], + ) # Plot the field example -#fieldMaker.plotField(1, ROOT.TVector3(-9000.0, 6000.0, 50.0), ROOT.TVector3(-300.0, 300.0, 6.0), 'Bzx.png') -#fieldMaker.plotField(2, ROOT.TVector3(-9000.0, 6000.0, 50.0), ROOT.TVector3(-400.0, 400.0, 6.0), 'Bzy.png') - -if inactivateMuonProcesses : - ROOT.gROOT.ProcessLine('#include "Geant4/G4ProcessTable.hh"') - mygMC = ROOT.TGeant4.GetMC() - mygMC.ProcessGeantCommand("/process/inactivate muPairProd") - mygMC.ProcessGeantCommand("/process/inactivate muBrems") - mygMC.ProcessGeantCommand("/process/inactivate muIoni") - mygMC.ProcessGeantCommand("/process/inactivate muonNuclear") - mygMC.ProcessGeantCommand("/particle/select mu+") - mygMC.ProcessGeantCommand("/particle/process/dump") - gProcessTable = ROOT.G4ProcessTable.GetProcessTable() - procmu = gProcessTable.FindProcess(ROOT.G4String('muIoni'),ROOT.G4String('mu+')) - procmu.SetVerboseLevel(2) +# fieldMaker.plotField(1, ROOT.TVector3(-9000.0, 6000.0, 50.0), ROOT.TVector3(-300.0, 300.0, 6.0), 'Bzx.png') +# fieldMaker.plotField(2, ROOT.TVector3(-9000.0, 6000.0, 50.0), ROOT.TVector3(-400.0, 400.0, 6.0), 'Bzy.png') + +if inactivateMuonProcesses: + ROOT.gROOT.ProcessLine('#include "Geant4/G4ProcessTable.hh"') + mygMC = ROOT.TGeant4.GetMC() + mygMC.ProcessGeantCommand("/process/inactivate muPairProd") + mygMC.ProcessGeantCommand("/process/inactivate muBrems") + mygMC.ProcessGeantCommand("/process/inactivate muIoni") + mygMC.ProcessGeantCommand("/process/inactivate muonNuclear") + mygMC.ProcessGeantCommand("/particle/select mu+") + mygMC.ProcessGeantCommand("/particle/process/dump") + gProcessTable = ROOT.G4ProcessTable.GetProcessTable() + procmu = gProcessTable.FindProcess(ROOT.G4String("muIoni"), ROOT.G4String("mu+")) + procmu.SetVerboseLevel(2) # -----Start run---------------------------------------------------- run.Run(options.nEvents) # -----Runtime database--------------------------------------------- @@ -581,100 +1017,117 @@ rtdb.setOutput(parOut) rtdb.saveOutput() rtdb.printParamContexts() -getattr(rtdb,"print")() +getattr(rtdb, "print")() # ------------------------------------------------------------------------ run.CreateGeometryFile("%s/geofile_full.%s.root" % (options.outputDir, tag)) # save ShipGeo dictionary in geofile import saveBasicParameters -saveBasicParameters.execute("%s/geofile_full.%s.root" % (options.outputDir, tag),ship_geo) + +saveBasicParameters.execute( + "%s/geofile_full.%s.root" % (options.outputDir, tag), ship_geo +) # checking for overlaps if options.debug == 2: - fGeo = ROOT.gGeoManager - fGeo.SetNmeshPoints(10000) - fGeo.CheckOverlaps(0.1) # 1 micron takes 5minutes - fGeo.PrintOverlaps() - # check subsystems in more detail - for x in fGeo.GetTopNode().GetNodes(): - x.CheckOverlaps(0.0001) - fGeo.PrintOverlaps() + fGeo = ROOT.gGeoManager + fGeo.SetNmeshPoints(10000) + fGeo.CheckOverlaps(0.1) # 1 micron takes 5minutes + fGeo.PrintOverlaps() + # check subsystems in more detail + for x in fGeo.GetTopNode().GetNodes(): + x.CheckOverlaps(0.0001) + fGeo.PrintOverlaps() # -----Finish------------------------------------------------------- timer.Stop() rtime = timer.RealTime() ctime = timer.CpuTime() -print(' ') +print(" ") print("Macro finished succesfully.") -if "P8gen" in globals() : - if (HNL): print("number of retries, events without HNL ",P8gen.nrOfRetries()) - elif (options.DarkPhoton): - print("number of retries, events without Dark Photons ",P8gen.nrOfRetries()) - print("total number of dark photons (including multiple meson decays per single collision) ",P8gen.nrOfDP()) +if "P8gen" in globals(): + if HNL: + print("number of retries, events without HNL ", P8gen.nrOfRetries()) + elif options.DarkPhoton: + print("number of retries, events without Dark Photons ", P8gen.nrOfRetries()) + print( + "total number of dark photons (including multiple meson decays per single collision) ", + P8gen.nrOfDP(), + ) -print("Output file is ", outFile) -print("Parameter file is ",parFile) -print("Real time ",rtime, " s, CPU time ",ctime,"s") +print("Output file is ", outFile) +print("Parameter file is ", parFile) +print("Real time ", rtime, " s, CPU time ", ctime, "s") # remove empty events if simEngine == "MuonBack": - tmpFile = outFile+"tmp" - xxx = outFile.split('/') - check = xxx[len(xxx)-1] - fin = False - for ff in ROOT.gROOT.GetListOfFiles(): - nm = ff.GetName().split('/') - if nm[len(nm)-1] == check: fin = ff - if not fin: fin = ROOT.TFile.Open(outFile) - t = fin.cbmsim - fout = ROOT.TFile(tmpFile,'recreate') - fSink = ROOT.FairRootFileSink(fout) - - sTree = t.CloneTree(0) - nEvents = 0 - pointContainers = [] - for x in sTree.GetListOfBranches(): - name = x.GetName() - if not name.find('Point')<0: pointContainers.append('sTree.'+name+'.GetEntries()') # makes use of convention that all sensitive detectors fill XXXPoint containers - for n in range(t.GetEntries()): - rc = t.GetEvent(n) - empty = True - for x in pointContainers: - if eval(x)>0: empty = False - if not empty: - rc = sTree.Fill() - nEvents+=1 - - branches = ROOT.TList() - branches.SetName('BranchList') - branches.Add(ROOT.TObjString('MCTrack')) - branches.Add(ROOT.TObjString('vetoPoint')) - branches.Add(ROOT.TObjString('ShipRpcPoint')) - branches.Add(ROOT.TObjString('TargetPoint')) - branches.Add(ROOT.TObjString('TTPoint')) - branches.Add(ROOT.TObjString('ScoringPoint')) - branches.Add(ROOT.TObjString('strawtubesPoint')) - branches.Add(ROOT.TObjString('EcalPoint')) - branches.Add(ROOT.TObjString('sEcalPointLite')) - branches.Add(ROOT.TObjString('smuonPoint')) - branches.Add(ROOT.TObjString('TimeDetPoint')) - branches.Add(ROOT.TObjString('MCEventHeader')) - branches.Add(ROOT.TObjString('sGeoTracks')) - - sTree.AutoSave() - fSink.WriteObject(branches, "BranchList", ROOT.TObject.kSingleKey) - fSink.SetOutTree(sTree) - - fout.Close() - print("removed empty events, left with:", nEvents) - rc1 = os.system("rm "+outFile) - rc2 = os.system("mv "+tmpFile+" "+outFile) - fin.SetWritable(False) # bpyass flush error + tmpFile = outFile + "tmp" + xxx = outFile.split("/") + check = xxx[len(xxx) - 1] + fin = False + for ff in ROOT.gROOT.GetListOfFiles(): + nm = ff.GetName().split("/") + if nm[len(nm) - 1] == check: + fin = ff + if not fin: + fin = ROOT.TFile.Open(outFile) + t = fin.cbmsim + fout = ROOT.TFile(tmpFile, "recreate") + fSink = ROOT.FairRootFileSink(fout) + + sTree = t.CloneTree(0) + nEvents = 0 + pointContainers = [] + for x in sTree.GetListOfBranches(): + name = x.GetName() + if not name.find("Point") < 0: + pointContainers.append( + "sTree." + name + ".GetEntries()" + ) # makes use of convention that all sensitive detectors fill XXXPoint containers + for n in range(t.GetEntries()): + rc = t.GetEvent(n) + empty = True + for x in pointContainers: + if eval(x) > 0: + empty = False + if not empty: + rc = sTree.Fill() + nEvents += 1 + + branches = ROOT.TList() + branches.SetName("BranchList") + branches.Add(ROOT.TObjString("MCTrack")) + branches.Add(ROOT.TObjString("vetoPoint")) + branches.Add(ROOT.TObjString("ShipRpcPoint")) + branches.Add(ROOT.TObjString("TargetPoint")) + branches.Add(ROOT.TObjString("TTPoint")) + branches.Add(ROOT.TObjString("ScoringPoint")) + branches.Add(ROOT.TObjString("strawtubesPoint")) + branches.Add(ROOT.TObjString("EcalPoint")) + branches.Add(ROOT.TObjString("sEcalPointLite")) + branches.Add(ROOT.TObjString("smuonPoint")) + branches.Add(ROOT.TObjString("TimeDetPoint")) + branches.Add(ROOT.TObjString("MCEventHeader")) + branches.Add(ROOT.TObjString("sGeoTracks")) + + sTree.AutoSave() + fSink.WriteObject(branches, "BranchList", ROOT.TObject.kSingleKey) + fSink.SetOutTree(sTree) + + fout.Close() + print("removed empty events, left with:", nEvents) + rc1 = os.system("rm " + outFile) + rc2 = os.system("mv " + tmpFile + " " + outFile) + fin.SetWritable(False) # bpyass flush error # ------------------------------------------------------------------------ import checkMagFields + + def visualizeMagFields(): - checkMagFields.run() + checkMagFields.run() + + def checkOverlapsWithGeant4(): - # after /run/initialize, but prints warning messages, problems with TGeo volume - mygMC = ROOT.TGeant4.GetMC() - mygMC.ProcessGeantCommand("/geometry/test/recursion_start 0") - mygMC.ProcessGeantCommand("/geometry/test/recursion_depth 2") - mygMC.ProcessGeantCommand("/geometry/test/run") + # after /run/initialize, but prints warning messages, problems with TGeo volume + mygMC = ROOT.TGeant4.GetMC() + mygMC.ProcessGeantCommand("/geometry/test/recursion_start 0") + mygMC.ProcessGeantCommand("/geometry/test/recursion_depth 2") + mygMC.ProcessGeantCommand("/geometry/test/run") diff --git a/muon/CMakeLists.txt b/muon/CMakeLists.txt index 139f151e2a..cccadba721 100644 --- a/muon/CMakeLists.txt +++ b/muon/CMakeLists.txt @@ -1,37 +1,23 @@ -# Create a library called "libmuon" which includes the source files given in -# the array . -# The extension is already found. Any number of sources could be listed here. +# Create a library called "libmuon" which includes the source files given in the +# array . The extension is already found. Any number of sources could be listed +# here. -set(INCLUDE_DIRECTORIES -${CMAKE_SOURCE_DIR}/shipdata -${CMAKE_SOURCE_DIR}/muon -${genfit2_INCDIR} -${VMC_INCLUDE_DIRS} -) +set(INCLUDE_DIRECTORIES ${CMAKE_SOURCE_DIR}/shipdata ${CMAKE_SOURCE_DIR}/muon + ${genfit2_INCDIR} ${VMC_INCLUDE_DIRS}) include_directories(${INCLUDE_DIRECTORIES} ${FAIRROOT_INCLUDE_DIR}) include_directories(SYSTEM ${SYSTEM_INCLUDE_DIRECTORIES}) -set(LINK_DIRECTORIES -${ROOT_LIBRARY_DIR} -${genfit2_LIBDIR} -${FAIRROOT_LIBRARY_DIR} -) +set(LINK_DIRECTORIES ${ROOT_LIBRARY_DIR} ${genfit2_LIBDIR} + ${FAIRROOT_LIBRARY_DIR}) -link_directories( ${LINK_DIRECTORIES}) +link_directories(${LINK_DIRECTORIES}) -set(SRCS -#Put here your sourcefiles -muon.cxx -muonContFact.cxx -muonPoint.cxx -muonHit.cxx -) +set(SRCS # Put here your sourcefiles + muon.cxx muonContFact.cxx muonPoint.cxx muonHit.cxx) -Set(LINKDEF muonLinkDef.h) -Set(LIBRARY_NAME muon) -Set(DEPENDENCIES - Base ShipData FairLogger::FairLogger -) +set(LINKDEF muonLinkDef.h) +set(LIBRARY_NAME muon) +set(DEPENDENCIES Base ShipData FairLogger::FairLogger) -GENERATE_LIBRARY() +generate_library() diff --git a/muon/muon.cxx b/muon/muon.cxx index 7b2583cd4e..02ced57543 100644 --- a/muon/muon.cxx +++ b/muon/muon.cxx @@ -1,231 +1,225 @@ #include "muon.h" -#include "muonPoint.h" - - -#include "FairVolume.h" -#include "FairGeoVolume.h" -#include "FairGeoNode.h" -#include "FairRootManager.h" -#include "FairGeoLoader.h" +#include "FairGeoBuilder.h" #include "FairGeoInterface.h" +#include "FairGeoLoader.h" #include "FairGeoMedia.h" -#include "FairGeoBuilder.h" +#include "FairGeoNode.h" +#include "FairGeoVolume.h" +#include "FairRootManager.h" #include "FairRun.h" #include "FairRuntimeDb.h" +#include "FairVolume.h" #include "ShipDetectorList.h" #include "ShipStack.h" - #include "TClonesArray.h" -#include "TVirtualMC.h" -#include "TGeoManager.h" #include "TGeoBBox.h" #include "TGeoCompositeShape.h" -#include "TGeoShapeAssembly.h" -#include "TGeoTube.h" +#include "TGeoManager.h" #include "TGeoMaterial.h" #include "TGeoMedium.h" +#include "TGeoShapeAssembly.h" +#include "TGeoTube.h" #include "TParticle.h" - - +#include "TVirtualMC.h" +#include "muonPoint.h" #include using std::cout; using std::endl; muon::muon() - : FairDetector("muon", kTRUE, kMuon), - fTrackID(-1), - fVolumeID(-1), - fPos(), - fMom(), - fTime(-1.), - fLength(-1.), - fELoss(-1), - fmuonPointCollection(new TClonesArray("muonPoint")) -{ -} + : FairDetector("muon", kTRUE, kMuon) + , fTrackID(-1) + , fVolumeID(-1) + , fPos() + , fMom() + , fTime(-1.) + , fLength(-1.) + , fELoss(-1) + , fmuonPointCollection(new TClonesArray("muonPoint")) +{} muon::muon(const char* name, Bool_t active) - : FairDetector(name, active, kMuon), - fTrackID(-1), - fVolumeID(-1), - fPos(), - fMom(), - fTime(-1.), - fLength(-1.), - fELoss(-1), - fmuonPointCollection(new TClonesArray("muonPoint")) -{ -} + : FairDetector(name, active, kMuon) + , fTrackID(-1) + , fVolumeID(-1) + , fPos() + , fMom() + , fTime(-1.) + , fLength(-1.) + , fELoss(-1) + , fmuonPointCollection(new TClonesArray("muonPoint")) +{} muon::~muon() { - if (fmuonPointCollection) { - fmuonPointCollection->Delete(); - delete fmuonPointCollection; - } + if (fmuonPointCollection) { + fmuonPointCollection->Delete(); + delete fmuonPointCollection; + } } void muon::Initialize() { - FairDetector::Initialize(); -// FairRuntimeDb* rtdb= FairRun::Instance()->GetRuntimeDb(); -// muonGeoPar* par=(muonGeoPar*)(rtdb->getContainer("muonGeoPar")); + FairDetector::Initialize(); + // FairRuntimeDb* rtdb= FairRun::Instance()->GetRuntimeDb(); + // muonGeoPar* par=(muonGeoPar*)(rtdb->getContainer("muonGeoPar")); } // ----- Private method InitMedium Int_t muon::InitMedium(const char* name) { - static FairGeoLoader *geoLoad=FairGeoLoader::Instance(); - static FairGeoInterface *geoFace=geoLoad->getGeoInterface(); - static FairGeoMedia *media=geoFace->getMedia(); - static FairGeoBuilder *geoBuild=geoLoad->getGeoBuilder(); - - FairGeoMedium *ShipMedium=media->getMedium(name); - - if (!ShipMedium) - { - Fatal("InitMedium","Material %s not defined in media file.", name); - return -1111; - } - TGeoMedium* medium=gGeoManager->GetMedium(name); - if (medium!=NULL) - return ShipMedium->getMediumIndex(); - - return geoBuild->createMedium(ShipMedium); + static FairGeoLoader* geoLoad = FairGeoLoader::Instance(); + static FairGeoInterface* geoFace = geoLoad->getGeoInterface(); + static FairGeoMedia* media = geoFace->getMedia(); + static FairGeoBuilder* geoBuild = geoLoad->getGeoBuilder(); + + FairGeoMedium* ShipMedium = media->getMedium(name); + + if (!ShipMedium) { + Fatal("InitMedium", "Material %s not defined in media file.", name); + return -1111; + } + TGeoMedium* medium = gGeoManager->GetMedium(name); + if (medium != NULL) + return ShipMedium->getMediumIndex(); + + return geoBuild->createMedium(ShipMedium); } -Bool_t muon::ProcessHits(FairVolume* vol) +Bool_t muon::ProcessHits(FairVolume* vol) { - /** This method is called from the MC stepping */ - //Set parameters at entrance of volume. Reset ELoss. - if ( gMC->IsTrackEntering() ) { - fELoss = 0.; - fTime = gMC->TrackTime() * 1.0e09; - fLength = gMC->TrackLength(); - gMC->TrackPosition(fPos); - gMC->TrackMomentum(fMom); - } - - // Sum energy loss for all steps in the active volume - fELoss += gMC->Edep(); - - // Create muonPoint at exit of active volume - if ( gMC->IsTrackExiting() || - gMC->IsTrackStop() || - gMC->IsTrackDisappeared() ) { - fTrackID = gMC->GetStack()->GetCurrentTrackNumber(); - //fVolumeID = vol->getMCid(); - //cout << "muon proc "<< fVolumeID<<" "<GetName()<<" "<getVolumeId() <FindVolumeFast(vol->GetName())->GetNumber()<FindVolumeFast(vol->GetName())->GetNumber(); - if (fELoss == 0. ) { return kFALSE; } - TParticle* p=gMC->GetStack()->GetCurrentTrack(); - Int_t pdgCode = p->GetPdgCode(); - AddHit(fTrackID, fVolumeID, TVector3(fPos.X(), fPos.Y(), fPos.Z()), - TVector3(fMom.Px(), fMom.Py(), fMom.Pz()), fTime, fLength, - fELoss,pdgCode); - - // Increment number of muon det points in TParticle - ShipStack* stack = (ShipStack*) gMC->GetStack(); - stack->AddPoint(kMuon); - } - - return kTRUE; + /** This method is called from the MC stepping */ + // Set parameters at entrance of volume. Reset ELoss. + if (gMC->IsTrackEntering()) { + fELoss = 0.; + fTime = gMC->TrackTime() * 1.0e09; + fLength = gMC->TrackLength(); + gMC->TrackPosition(fPos); + gMC->TrackMomentum(fMom); + } + + // Sum energy loss for all steps in the active volume + fELoss += gMC->Edep(); + + // Create muonPoint at exit of active volume + if (gMC->IsTrackExiting() || gMC->IsTrackStop() || gMC->IsTrackDisappeared()) { + fTrackID = gMC->GetStack()->GetCurrentTrackNumber(); + // fVolumeID = vol->getMCid(); + // cout << "muon proc "<< fVolumeID<<" "<GetName()<<" "<getVolumeId() <FindVolumeFast(vol->GetName())->GetNumber()<FindVolumeFast(vol->GetName())->GetNumber(); + if (fELoss == 0.) { + return kFALSE; + } + TParticle* p = gMC->GetStack()->GetCurrentTrack(); + Int_t pdgCode = p->GetPdgCode(); + AddHit(fTrackID, + fVolumeID, + TVector3(fPos.X(), fPos.Y(), fPos.Z()), + TVector3(fMom.Px(), fMom.Py(), fMom.Pz()), + fTime, + fLength, + fELoss, + pdgCode); + + // Increment number of muon det points in TParticle + ShipStack* stack = (ShipStack*)gMC->GetStack(); + stack->AddPoint(kMuon); + } + + return kTRUE; } void muon::EndOfEvent() { - fmuonPointCollection->Clear(); - + fmuonPointCollection->Clear(); } - - void muon::Register() { - /** This will create a branch in the output tree called - muonPoint, setting the last parameter to kFALSE means: - this collection will not be written to the file, it will exist - only during the simulation. - */ - - FairRootManager::Instance()->Register("muonPoint", "muon", - fmuonPointCollection, kTRUE); + /** This will create a branch in the output tree called + muonPoint, setting the last parameter to kFALSE means: + this collection will not be written to the file, it will exist + only during the simulation. + */ + FairRootManager::Instance()->Register("muonPoint", "muon", fmuonPointCollection, kTRUE); } - TClonesArray* muon::GetCollection(Int_t iColl) const { - if (iColl == 0) { return fmuonPointCollection; } - else { return NULL; } + if (iColl == 0) { + return fmuonPointCollection; + } else { + return NULL; + } } void muon::Reset() { - fmuonPointCollection->Clear(); + fmuonPointCollection->Clear(); } -void muon::SetZStationPositions(Double_t z0, Double_t z1,Double_t z2,Double_t z3) +void muon::SetZStationPositions(Double_t z0, Double_t z1, Double_t z2, Double_t z3) { - fM0z=z0; - fM1z=z1; - fM2z=z2; - fM3z=z3; + fM0z = z0; + fM1z = z1; + fM2z = z2; + fM3z = z3; } -void muon::SetZFilterPositions(Double_t z0, Double_t z1,Double_t z2) +void muon::SetZFilterPositions(Double_t z0, Double_t z1, Double_t z2) { - fF0z=z0; - fF1z=z1; - fF2z=z2; + fF0z = z0; + fF1z = z1; + fF2z = z2; } void muon::SetActiveThickness(Double_t activeThickness) { - fActiveThickness=activeThickness; + fActiveThickness = activeThickness; } void muon::SetFilterThickness(Double_t filterThickness) { - fFilterThickness=filterThickness; + fFilterThickness = filterThickness; } void muon::SetXMax(Double_t xMax) { - fXMax=xMax; + fXMax = xMax; } void muon::SetYMax(Double_t yMax) { - fYMax=yMax; + fYMax = yMax; } void muon::ConstructGeometry() { - /** If you are using the standard ASCII input for the geometry - just copy this and use it for your detector, otherwise you can - implement here you own way of constructing the geometry. */ + /** If you are using the standard ASCII input for the geometry + just copy this and use it for your detector, otherwise you can + implement here you own way of constructing the geometry. */ - TGeoVolume *top=gGeoManager->GetTopVolume(); - TGeoVolume *tMuon = new TGeoVolumeAssembly("MuonDetector"); + TGeoVolume* top = gGeoManager->GetTopVolume(); + TGeoVolume* tMuon = new TGeoVolumeAssembly("MuonDetector"); InitMedium("iron"); InitMedium("Scintillator"); - TGeoMedium *Al =gGeoManager->GetMedium("Scintillator"); - TGeoMedium *A2 =gGeoManager->GetMedium("iron"); + TGeoMedium* Al = gGeoManager->GetMedium("Scintillator"); + TGeoMedium* A2 = gGeoManager->GetMedium("iron"); -// TGeoBBox *detbox1 = new TGeoBBox("detbox1", 250, 250, 10); -// TGeoBBox *detbox2 = new TGeoBBox("detbox2", 245, 245, 10); + // TGeoBBox *detbox1 = new TGeoBBox("detbox1", 250, 250, 10); + // TGeoBBox *detbox2 = new TGeoBBox("detbox2", 245, 245, 10); -// TGeoCompositeShape *detcomp1 = new TGeoCompositeShape("detcomp1", "detbox1-detbox2"); + // TGeoCompositeShape *detcomp1 = new TGeoCompositeShape("detcomp1", "detbox1-detbox2"); -// TGeoVolume *detmu1 = new TGeoVolume("MuX", detcomp1, Al); - TGeoVolume *muondet0 = gGeoManager->MakeBox("muondet0", Al, fXMax, fYMax, fActiveThickness); - TGeoVolume *muondet1 = gGeoManager->MakeBox("muondet1", Al, fXMax, fYMax, fActiveThickness); - TGeoVolume *muondet2 = gGeoManager->MakeBox("muondet2", Al, fXMax, fYMax, fActiveThickness); - TGeoVolume *muondet3 = gGeoManager->MakeBox("muondet3", Al, fXMax, fYMax, fActiveThickness); + // TGeoVolume *detmu1 = new TGeoVolume("MuX", detcomp1, Al); + TGeoVolume* muondet0 = gGeoManager->MakeBox("muondet0", Al, fXMax, fYMax, fActiveThickness); + TGeoVolume* muondet1 = gGeoManager->MakeBox("muondet1", Al, fXMax, fYMax, fActiveThickness); + TGeoVolume* muondet2 = gGeoManager->MakeBox("muondet2", Al, fXMax, fYMax, fActiveThickness); + TGeoVolume* muondet3 = gGeoManager->MakeBox("muondet3", Al, fXMax, fYMax, fActiveThickness); - TGeoVolume *muonfilter = gGeoManager->MakeBox("muonfilter", A2, fXMax, fYMax, fFilterThickness); -// 10cm iron to shield against backsplash from cavern - TGeoVolume *muonshield = gGeoManager->MakeBox("muonshield", A2, fXMax, fYMax, 5.); + TGeoVolume* muonfilter = gGeoManager->MakeBox("muonfilter", A2, fXMax, fYMax, fFilterThickness); + // 10cm iron to shield against backsplash from cavern + TGeoVolume* muonshield = gGeoManager->MakeBox("muonshield", A2, fXMax, fYMax, 5.); AddSensitiveVolume(muondet0); AddSensitiveVolume(muondet1); @@ -237,28 +231,31 @@ void muon::ConstructGeometry() muondet3->SetLineColor(kGreen); muonfilter->SetLineColor(kBlue); Double_t zStartMuon = fM0z; - Double_t totLength = fM3z-fM0z+2*fActiveThickness+15.; - Double_t relPos = zStartMuon-fActiveThickness+totLength/2.; - tMuon->AddNode(muondet0, 1, new TGeoTranslation(0, 0, fM0z-relPos)); - tMuon->AddNode(muonfilter, 0, new TGeoTranslation(0, 0, fF0z-relPos)); - tMuon->AddNode(muondet1, 1, new TGeoTranslation(0, 0, fM1z-relPos)); - tMuon->AddNode(muonfilter, 1, new TGeoTranslation(0, 0, fF1z-relPos)); - tMuon->AddNode(muondet2, 1, new TGeoTranslation(0, 0, fM2z-relPos)); - tMuon->AddNode(muonfilter, 2, new TGeoTranslation(0, 0, fF2z-relPos)); - tMuon->AddNode(muondet3, 1, new TGeoTranslation(0, 0, fM3z-relPos)); - tMuon->AddNode(muonshield, 1, new TGeoTranslation(0, 0, fM3z+fActiveThickness+10.-relPos)); - //finish assembly and position - top->AddNode(tMuon, 1, new TGeoTranslation(0, 0,relPos)); + Double_t totLength = fM3z - fM0z + 2 * fActiveThickness + 15.; + Double_t relPos = zStartMuon - fActiveThickness + totLength / 2.; + tMuon->AddNode(muondet0, 1, new TGeoTranslation(0, 0, fM0z - relPos)); + tMuon->AddNode(muonfilter, 0, new TGeoTranslation(0, 0, fF0z - relPos)); + tMuon->AddNode(muondet1, 1, new TGeoTranslation(0, 0, fM1z - relPos)); + tMuon->AddNode(muonfilter, 1, new TGeoTranslation(0, 0, fF1z - relPos)); + tMuon->AddNode(muondet2, 1, new TGeoTranslation(0, 0, fM2z - relPos)); + tMuon->AddNode(muonfilter, 2, new TGeoTranslation(0, 0, fF2z - relPos)); + tMuon->AddNode(muondet3, 1, new TGeoTranslation(0, 0, fM3z - relPos)); + tMuon->AddNode(muonshield, 1, new TGeoTranslation(0, 0, fM3z + fActiveThickness + 10. - relPos)); + // finish assembly and position + top->AddNode(tMuon, 1, new TGeoTranslation(0, 0, relPos)); } -muonPoint* muon::AddHit(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t time, Double_t length, - Double_t eLoss, Int_t pdgCode) +muonPoint* muon::AddHit(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t time, + Double_t length, + Double_t eLoss, + Int_t pdgCode) { - TClonesArray& clref = *fmuonPointCollection; - Int_t size = clref.GetEntriesFast(); - // cout << "muon hit called"<< pos.z()< - -//static muonContFact gmuonContFact; +// static muonContFact gmuonContFact; muonContFact::muonContFact() - : FairContFact() + : FairContFact() { - /** Constructor (called when the library is loaded) */ - fName="muonContFact"; - fTitle="Factory for parameter containers in libmuon"; - setAllContainers(); - FairRuntimeDb::instance()->addContFactory(this); + /** Constructor (called when the library is loaded) */ + fName = "muonContFact"; + fTitle = "Factory for parameter containers in libmuon"; + setAllContainers(); + FairRuntimeDb::instance()->addContFactory(this); } void muonContFact::setAllContainers() { - /** Creates the Container objects with all accepted - contexts and adds them to - the list of containers for the muon library. - */ -/* - FairContainer* p= new FairContainer("muonGeoPar", - "muon Geometry Parameters", - "TestDefaultContext"); - p->addContext("TestNonDefaultContext"); + /** Creates the Container objects with all accepted + contexts and adds them to + the list of containers for the muon library. + */ + /* + FairContainer* p= new FairContainer("muonGeoPar", + "muon Geometry Parameters", + "TestDefaultContext"); + p->addContext("TestNonDefaultContext"); - containers->Add(p); -*/ - } + containers->Add(p); + */ +} FairParSet* muonContFact::createContainer(FairContainer* c) { - /** Calls the constructor of the corresponding parameter container. - For an actual context, which is not an empty string and not - the default context - of this container, the name is concatinated with the context. - */ - /* const char* name=c->GetName(); - FairParSet* p=NULL; - if (strcmp(name,"muonGeoPar")==0) { - p=new muonGeoPar(c->getConcatName().Data(), - c->GetTitle(),c->getContext()); - } - return p; -*/ - return 0; + /** Calls the constructor of the corresponding parameter container. + For an actual context, which is not an empty string and not + the default context + of this container, the name is concatinated with the context. + */ + /* const char* name=c->GetName(); + FairParSet* p=NULL; + if (strcmp(name,"muonGeoPar")==0) { + p=new muonGeoPar(c->getConcatName().Data(), + c->GetTitle(),c->getContext()); + } + return p; + */ + return 0; } diff --git a/muon/muonContFact.h b/muon/muonContFact.h index 8e8a9a6a51..3e83d15fe3 100644 --- a/muon/muonContFact.h +++ b/muon/muonContFact.h @@ -9,11 +9,12 @@ class muonContFact : public FairContFact { private: void setAllContainers(); + public: muonContFact(); ~muonContFact() {} FairParSet* createContainer(FairContainer*); - ClassDef( muonContFact,0) // Factory for all muon parameter containers + ClassDef(muonContFact, 0) // Factory for all muon parameter containers }; #endif diff --git a/muon/muonHit.cxx b/muon/muonHit.cxx index 08b188d6f2..25c853cb91 100644 --- a/muon/muonHit.cxx +++ b/muon/muonHit.cxx @@ -1,182 +1,187 @@ #include "muonHit.h" -#include "muonPoint.h" + #include "TVector3.h" +#include "muonPoint.h" // -#include "TGeoManager.h" #include "TGeoBBox.h" +#include "TGeoManager.h" +#include "TRandom3.h" #include -#include #include +#include #include -#include "TRandom3.h" - using std::cout; using std::endl; -bool muonHit::onlyOnce=false; -const Double_t tileXdim = 10., tileYdim = 20.; // single tile dimension -const Double_t muonTimeResSigma = 0.5; // ns -static std::vector tileXn, tileYn; // n. of tile along X and Y dimension -static std::vector muStxMax; // dX of the different stations -static std::vector muStyMax; // dY of the different stations -static std::vector muStzMax; // dZ of the different stations -static std::vector muStZpos; // global Z coord in diff. stations +bool muonHit::onlyOnce = false; +const Double_t tileXdim = 10., tileYdim = 20.; // single tile dimension +const Double_t muonTimeResSigma = 0.5; // ns +static std::vector tileXn, tileYn; // n. of tile along X and Y dimension +static std::vector muStxMax; // dX of the different stations +static std::vector muStyMax; // dY of the different stations +static std::vector muStzMax; // dZ of the different stations +static std::vector muStZpos; // global Z coord in diff. stations -Double_t speedOfLight = TMath::C() *100./1000000000.0 ; // from m/sec to cm/ns +Double_t speedOfLight = TMath::C() * 100. / 1000000000.0; // from m/sec to cm/ns // ----- Default constructor ------------------------------------------- muonHit::muonHit() - : ShipHit() -{ - -} + : ShipHit() +{} // ----- Standard constructor ------------------------------------------ muonHit::muonHit(Int_t detID, Float_t digi, Bool_t isV) - : ShipHit(detID,digi) + : ShipHit(detID, digi) { - // - SetDigi(digi); - setValidity(isV); + // + SetDigi(digi); + setValidity(isV); } // ----- constructor from muonPoint ------------------------------------------ muonHit::muonHit(muonPoint* p, Double_t t0) - : ShipHit() + : ShipHit() { -// - TVector3 truePosition = TVector3( p->GetX(), p->GetY(),p->GetZ()); - fdigi = t0 + p->GetTime(); // + drift time, propagation inside tile + tdc - SetDetectorID(DetIDfromXYZ(truePosition)); - SetDigi(SetMuonTimeRes(fdigi)); + // + TVector3 truePosition = TVector3(p->GetX(), p->GetY(), p->GetZ()); + fdigi = t0 + p->GetTime(); // + drift time, propagation inside tile + tdc + SetDetectorID(DetIDfromXYZ(truePosition)); + SetDigi(SetMuonTimeRes(fdigi)); } // ---- Int_t muonHit::DetIDfromXYZ(TVector3 p) { // needs some code to produce a unique detector ID -// -// tiles numbering example with present tile dimensions (X=10,Y=20cm): -// --------------------------- -// muon station 1 |13540|13541...13598|13599| -// ---------------------------| -// muon station 0 |03540|03541...03598|03599|| -// How tiles numbering works: |03480|03481...03538|03539|. -// in each station tiles are numbered by rows starting | || -// from 0. Numbering begins at bottom of the station ...........................| -// from left to right (looking the muon station from | || -// em calorimeter). At each tile is added the number |00060|00061...00118|00119| -// n * 10ˆ4 where n is the station number (0 <= n <= 3). |00000|00001...00058|00059| -// --------------------------- -// negative detID means ERROR. -// - Int_t detID, nStat; // unique detector ID, station number -// - if (!onlyOnce) { - stInit(); - onlyOnce = true; - } + // + // tiles numbering example with present tile dimensions (X=10,Y=20cm): + // --------------------------- + // muon station 1 |13540|13541...13598|13599| + // ---------------------------| + // muon station 0 |03540|03541...03598|03599|| + // How tiles numbering works: |03480|03481...03538|03539|. + // in each station tiles are numbered by rows starting | || + // from 0. Numbering begins at bottom of the station ...........................| + // from left to right (looking the muon station from | || + // em calorimeter). At each tile is added the number |00060|00061...00118|00119| + // n * 10ˆ4 where n is the station number (0 <= n <= 3). |00000|00001...00058|00059| + // --------------------------- + // negative detID means ERROR. + // + Int_t detID, nStat; // unique detector ID, station number + // + if (!onlyOnce) { + stInit(); + onlyOnce = true; + } nStat = -1; - for(Int_t i=0; iGetCurrentNavigator(); - Double_t loc[3]={0,0,0}, global[3]={0,0,0}; -// + Double_t loc[3] = {0, 0, 0}, global[3] = {0, 0, 0}; + // TString muDet = "cave/MuonDetector_1"; nav->cd(muDet); TGeoNode* node = nav->GetCurrentNode(); - TObjArray* nodes = node->GetVolume()->GetNodes(); -// + TObjArray* nodes = node->GetVolume()->GetNodes(); + // for (Int_t i = 0; i < nodes->GetEntries(); i++) { - node = (TGeoNode*)nodes->At(i); - Int_t muStNs = 0; - if (TString(node->GetName()).Contains("muondet")) { - nav->cd(muDet+"/"+node->GetName()); - TGeoVolume* volu = node->GetVolume(); - muShape = node->GetVolume()->GetShape(); - muonBox = (TGeoBBox*) muShape; - muStxMax.push_back(muonBox->GetDX()); muStyMax.push_back(muonBox->GetDY()); - muStzMax.push_back(muonBox->GetDZ()); - nav->LocalToMaster(loc,global); muStZpos.push_back(global[2]); - tileXn.push_back(2*muStxMax.at(muStNs)/tileXdim); - tileYn.push_back(2*muStyMax.at(muStNs)/tileYdim); - muStNs++; // muon stations increment - } + node = (TGeoNode*)nodes->At(i); + Int_t muStNs = 0; + if (TString(node->GetName()).Contains("muondet")) { + nav->cd(muDet + "/" + node->GetName()); + TGeoVolume* volu = node->GetVolume(); + muShape = node->GetVolume()->GetShape(); + muonBox = (TGeoBBox*)muShape; + muStxMax.push_back(muonBox->GetDX()); + muStyMax.push_back(muonBox->GetDY()); + muStzMax.push_back(muonBox->GetDZ()); + nav->LocalToMaster(loc, global); + muStZpos.push_back(global[2]); + tileXn.push_back(2 * muStxMax.at(muStNs) / tileXdim); + tileYn.push_back(2 * muStyMax.at(muStNs) / tileYdim); + muStNs++; // muon stations increment + } } } // ------------------------------------------------------------------------- -Double_t muonHit::SetMuonTimeRes(Double_t mcTime) { -// - TRandom3 *rand = new TRandom3(0); - Double_t cTime = rand->Gaus(mcTime,muonTimeResSigma); - delete rand; - return cTime; +Double_t muonHit::SetMuonTimeRes(Double_t mcTime) +{ + // + TRandom3* rand = new TRandom3(0); + Double_t cTime = rand->Gaus(mcTime, muonTimeResSigma); + delete rand; + return cTime; } -void muonHit::Print() const { -// - cout << "-I- muonHit: muon hit " << " in detector " << fDetectorID << endl; - cout << " TDC " << fdigi << " ns" << endl; - +void muonHit::Print() const +{ + // + cout << "-I- muonHit: muon hit " << " in detector " << fDetectorID << endl; + cout << " TDC " << fdigi << " ns" << endl; } // -void muonHit::setValidity(Bool_t isV){hisV = isV;} -// ----- Destructor ---------------------------------------------------- -muonHit::~muonHit() { +void muonHit::setValidity(Bool_t isV) +{ + hisV = isV; } +// ----- Destructor ---------------------------------------------------- +muonHit::~muonHit() {} // ------------------------------------------------------------------------- diff --git a/muon/muonHit.h b/muon/muonHit.h index fb9f671336..bb05bf740b 100644 --- a/muon/muonHit.h +++ b/muon/muonHit.h @@ -1,17 +1,14 @@ #ifndef MUONHIT_H #define MUONHIT_H 1 +#include "ShipHit.h" #include "TObject.h" #include "TVector3.h" - -#include "ShipHit.h" #include "muonPoint.h" - class muonHit : public ShipHit { public: - /** Default constructor **/ muonHit(); @@ -23,20 +20,20 @@ class muonHit : public ShipHit muonHit(Int_t detID, Float_t digi, Bool_t isValid); muonHit(muonPoint* p, Double_t t0); - Int_t DetIDfromXYZ(TVector3 p); //provide mapping, true xyz to detectorID - TVector3 XYZfromDetID(Int_t detID); // return centre of muon tile -/** Destructor **/ + Int_t DetIDfromXYZ(TVector3 p); // provide mapping, true xyz to detectorID + TVector3 XYZfromDetID(Int_t detID); // return centre of muon tile + /** Destructor **/ virtual ~muonHit(); /** Output to screen **/ virtual void Print() const; -// - TVector3 getPos() {return XYZfromDetID(fDetectorID);} - Bool_t isValid() const {return hisV;} -// - Double_t SetMuonTimeRes(Double_t mcTime); // return tdc + // + TVector3 getPos() { return XYZfromDetID(fDetectorID); } + Bool_t isValid() const { return hisV; } + // + Double_t SetMuonTimeRes(Double_t mcTime); // return tdc void setValidity(Bool_t isValid); -// + // private: /** Copy constructor **/ muonHit(const muonHit& point); @@ -45,11 +42,11 @@ class muonHit : public ShipHit Float_t flag; ///< flag static bool onlyOnce; - void stInit(); // stations init -// + void stInit(); // stations init + // Bool_t hisV; -// - ClassDef(muonHit,3) + // + ClassDef(muonHit, 3) }; -#endif //MUONHIT.H +#endif // MUONHIT.H diff --git a/muon/muonPoint.cxx b/muon/muonPoint.cxx index 9001a75b6f..2faa001a3b 100644 --- a/muon/muonPoint.cxx +++ b/muon/muonPoint.cxx @@ -4,38 +4,37 @@ using std::cout; using std::endl; - // ----- Default constructor ------------------------------------------- muonPoint::muonPoint() - : FairMCPoint() -{ -} + : FairMCPoint() +{} // ------------------------------------------------------------------------- // ----- Standard constructor ------------------------------------------ -muonPoint::muonPoint(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t tof, Double_t length, - Double_t eLoss, Int_t pdgcode) - : FairMCPoint(trackID, detID, pos, mom, tof, length, eLoss), fPdgCode(pdgcode) -{ -} +muonPoint::muonPoint(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t tof, + Double_t length, + Double_t eLoss, + Int_t pdgcode) + : FairMCPoint(trackID, detID, pos, mom, tof, length, eLoss) + , fPdgCode(pdgcode) +{} // ------------------------------------------------------------------------- // ----- Destructor ---------------------------------------------------- -muonPoint::~muonPoint() { } +muonPoint::~muonPoint() {} // ------------------------------------------------------------------------- // ----- Public method Print ------------------------------------------- void muonPoint::Print(const Option_t* opt) const { - cout << "-I- muonPoint: muon point for track " << fTrackID - << " in detector " << fDetectorID << endl; - cout << " Position (" << fX << ", " << fY << ", " << fZ - << ") cm" << endl; - cout << " Momentum (" << fPx << ", " << fPy << ", " << fPz - << ") GeV" << endl; - cout << " Time " << fTime << " ns, Length " << fLength - << " cm, Energy loss " << fELoss*1.0e06 << " keV" << endl; + cout << "-I- muonPoint: muon point for track " << fTrackID << " in detector " << fDetectorID << endl; + cout << " Position (" << fX << ", " << fY << ", " << fZ << ") cm" << endl; + cout << " Momentum (" << fPx << ", " << fPy << ", " << fPz << ") GeV" << endl; + cout << " Time " << fTime << " ns, Length " << fLength << " cm, Energy loss " << fELoss * 1.0e06 << " keV" + << endl; } // ------------------------------------------------------------------------- diff --git a/muon/muonPoint.h b/muon/muonPoint.h index 917a916f22..d36feb74b3 100644 --- a/muon/muonPoint.h +++ b/muon/muonPoint.h @@ -1,9 +1,7 @@ #ifndef MUONPOINT_H #define MUONPOINT_H 1 - #include "FairMCPoint.h" - #include "TObject.h" #include "TVector3.h" @@ -11,11 +9,9 @@ class muonPoint : public FairMCPoint { public: - /** Default constructor **/ muonPoint(); - /** Constructor with arguments *@param trackID Index of MCTrack *@param detID Detector ID @@ -25,17 +21,21 @@ class muonPoint : public FairMCPoint *@param length Track length since creation [cm] *@param eLoss Energy deposit [GeV] **/ - muonPoint(Int_t trackID, Int_t detID, TVector3 pos, TVector3 mom, - Double_t tof, Double_t length, Double_t eLoss, Int_t pdgCode); - - + muonPoint(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t tof, + Double_t length, + Double_t eLoss, + Int_t pdgCode); /** Destructor **/ virtual ~muonPoint(); /** Output to screen **/ virtual void Print(const Option_t* opt) const; - Int_t PdgCode() const {return fPdgCode;} + Int_t PdgCode() const { return fPdgCode; } private: /** Copy constructor **/ @@ -43,8 +43,7 @@ class muonPoint : public FairMCPoint muonPoint(const muonPoint& point); muonPoint operator=(const muonPoint& point); - ClassDef(muonPoint,2) - + ClassDef(muonPoint, 2) }; #endif diff --git a/muonShieldOptimization/CMakeLists.txt b/muonShieldOptimization/CMakeLists.txt index 4e008b633f..000c05e9a0 100644 --- a/muonShieldOptimization/CMakeLists.txt +++ b/muonShieldOptimization/CMakeLists.txt @@ -1,36 +1,29 @@ -# Create a library called "libMuonShieldBackground" which includes the source files given in -# the array . -# The extension is already found. Any number of sources could be listed here. +# Create a library called "libMuonShieldBackground" which includes the source +# files given in the array . The extension is already found. Any number of +# sources could be listed here. if(EXISTS "$ENV{PYTHON_HOME}") - set(PYTHON_LIBRARY $ENV{PYTHON_HOME}/lib) - set(PYTHON_INCLUDE_DIR $ENV{PYTHON_HOME}/include/python2.7) + set(PYTHON_LIBRARY $ENV{PYTHON_HOME}/lib) + set(PYTHON_INCLUDE_DIR $ENV{PYTHON_HOME}/include/python2.7) endif(EXISTS "$ENV{PYTHON_HOME}") -FIND_PACKAGE(PythonLibs REQUIRED) +find_package(PythonLibs REQUIRED) set(INCLUDE_DIRECTORIES -${CMAKE_SOURCE_DIR}/muonShieldOptimization ${VMC_INCLUDE_DIRS} ${CMAKE_SOURCE_DIR}/veto ${CMAKE_SOURCE_DIR}/shipdata ${PYTHON_INCLUDE_DIRS} -) + ${CMAKE_SOURCE_DIR}/muonShieldOptimization ${VMC_INCLUDE_DIRS} + ${CMAKE_SOURCE_DIR}/veto ${CMAKE_SOURCE_DIR}/shipdata + ${PYTHON_INCLUDE_DIRS}) include_directories(${INCLUDE_DIRECTORIES} ${FAIRROOT_INCLUDE_DIR}) include_directories(SYSTEM ${SYSTEM_INCLUDE_DIRECTORIES}) -set(LINK_DIRECTORIES -${ROOT_LIBRARY_DIR} -${FAIRROOT_LIBRARY_DIR} +set(LINK_DIRECTORIES ${ROOT_LIBRARY_DIR} ${FAIRROOT_LIBRARY_DIR}) -) +link_directories(${LINK_DIRECTORIES}) -link_directories( ${LINK_DIRECTORIES}) +set(SRCS exitHadronAbsorber.cxx pyFairModule.cxx simpleTarget.cxx) -set(SRCS -exitHadronAbsorber.cxx -pyFairModule.cxx -simpleTarget.cxx -) - -Set(HEADERS ) -Set(LINKDEF muonShieldBackgroundLinkDef.h) -Set(LIBRARY_NAME ShipMuonShieldBackground) +set(HEADERS) +set(LINKDEF muonShieldBackgroundLinkDef.h) +set(LIBRARY_NAME ShipMuonShieldBackground) set(DEPENDENCIES Base GeoBase ParBase Geom Core FairLogger::FairLogger) -GENERATE_LIBRARY() +generate_library() diff --git a/muonShieldOptimization/ana_ShipMuon.py b/muonShieldOptimization/ana_ShipMuon.py index 67aea5bc4e..3619f698bd 100644 --- a/muonShieldOptimization/ana_ShipMuon.py +++ b/muonShieldOptimization/ana_ShipMuon.py @@ -1,16 +1,20 @@ # analyze muon background /media/Data/HNL/PythiaGeant4Production/pythia8_Geant4_total.root -import os,ROOT import multiprocessing as mp +import os + +import ROOT from rootpyPickler import Unpickler -ROOT.gInterpreter.ProcessLine('typedef double Double32_t') + +ROOT.gInterpreter.ProcessLine("typedef double Double32_t") local = False -if not os.uname()[1].lower().find('ubuntu')< 0: local = True +if not os.uname()[1].lower().find("ubuntu") < 0: + local = True parallel = True if parallel: -# Define an output queue - output = mp.Queue() - processes = [] + # Define an output queue + output = mp.Queue() + processes = [] # 11-19 with QGSP_BERT_EMV instead of QGSP_BERT_HP_PEN @@ -22,19 +26,19 @@ # 91-99 switch off muBrems, muPair # 101-109 vacuum tube as cone, Al->Steel -#prefix = 'muon4' # default -#prefix = 'muon6' # Al -> vacuum -#prefix = 'muon7' # no field in wings -#prefix = 'muon8' # entry window + additional shielding -#prefix = 'muon9' # switch off muBrems, muPair -#prefix = 'muon10' # vacuum tube as cone, Al->Steel -#prefix = 'muon14' # vacuum tube as cone, Al->Steel, slightly smaller lead shield -#prefix = 'muon12' # switch off muIoni -#prefix = 'muon13' # switch off muBrems, muPair AND muIoni -#prefix = 'muon15' # vacuum tube as cone, Al->Steel, cave with air -#prefix = 'muon 161-169 new geometry -#prefix = 'muon 251-259 passive shielding with concrete walls -#prefix = 'muon 171-179 new increased Bdl, 2.5m clearance from start, 9m space for tau +# prefix = 'muon4' # default +# prefix = 'muon6' # Al -> vacuum +# prefix = 'muon7' # no field in wings +# prefix = 'muon8' # entry window + additional shielding +# prefix = 'muon9' # switch off muBrems, muPair +# prefix = 'muon10' # vacuum tube as cone, Al->Steel +# prefix = 'muon14' # vacuum tube as cone, Al->Steel, slightly smaller lead shield +# prefix = 'muon12' # switch off muIoni +# prefix = 'muon13' # switch off muBrems, muPair AND muIoni +# prefix = 'muon15' # vacuum tube as cone, Al->Steel, cave with air +# prefix = 'muon 161-169 new geometry +# prefix = 'muon 251-259 passive shielding with concrete walls +# prefix = 'muon 171-179 new increased Bdl, 2.5m clearance from start, 9m space for tau # 181-189 narrow tunnel around first magnet, add 2m hadron absorber, fixed problem with B-field -> G4 # 191-199 narrow tunnel bug fix, also bug fix for top/bottom, now with tungsten core in add absorber # 201-209 test with reduced field, 1.5T @@ -71,1182 +75,1604 @@ # 640-649 10m height, change RPC width 4.5->3.6m Yandex # 650-669 6m height, change RPC width 4.5->3.6m # 660-669 6m height, change RPC width 4.5->3.6m Yandex -#makeProd("muon700",10,False,False) # switch off field of active shielding # prefix,DY,y=False,phiRandom=False,X=None -#makeProd("muon710",10,False,False) # start production with beam smeared on r=3cm disk -#makeProd("muon720",10,True,False) -#makeProd("muon711",10,False,True) # start production with beam smeared on r=3cm disk -#makeProd("muon721",10,True,True) -#makeProd("muon712",10,False,True) # start production with beam smeared on r=3cm disk -#makeProd("muon722",10,True,True) -#makeProd("muon713",10,False,True) # start production with beam smeared on r=3cm disk -#makeProd("muon723",10,True,True) -#makeProd("muon714",10,False,True) # start production with beam smeared on r=3cm disk -#makeProd("muon724",10,True,True) -#makeProd("muon715",10,False,True) # start production with beam smeared on r=3cm disk -#makeProd("muon725",10,True,True) -#makeProd("muon716",10,False,True) # start production with beam smeared on r=3cm disk -#makeProd("muon726",10,True,True) -#makeProd("muon717",10,False,True) # start production with beam smeared on r=3cm disk -#makeProd("muon777",10,False,True) # in case the other one does not work 717 -#makeProd("muon727",10,True,True) # ? -#makeProd("muon718",10,False,True) # start production with beam smeared on r=3cm disk -#makeProd("muon728",10,True,True) -#makeProd("muon719",10,False,True) # start production with beam smeared on r=3cm disk -#makeProd("muon729",10,True,True) -#makeProd("muon730",10,'Jpsi',False) -#makeProd("muon731",10,'Jpsi',True) -#makeProd("muon732",10,'Jpsi',True) -#makeProd("muon733",10,'Jpsi',True) # back to pencil beam -#makeProd("muon630",10,False,True) # test with new muonShield code, 3cm smearing -#makeProd("muon631",10,False,True) # run with concrete wall enabled as sensitive -#makeProd("muon632",10,False,True) # run with concrete wall enabled as sensitive, active shielding polarity fixed - # but wrong geometry -#makeProd("muon810",10,False,False) # start production with latest geometry -#makeProd("muon820",10,True,False) -#makeProd("muon811",10,False,True) # -#makeProd("muon821",10,True,True) +# makeProd("muon700",10,False,False) # switch off field of active shielding # prefix,DY,y=False,phiRandom=False,X=None +# makeProd("muon710",10,False,False) # start production with beam smeared on r=3cm disk +# makeProd("muon720",10,True,False) +# makeProd("muon711",10,False,True) # start production with beam smeared on r=3cm disk +# makeProd("muon721",10,True,True) +# makeProd("muon712",10,False,True) # start production with beam smeared on r=3cm disk +# makeProd("muon722",10,True,True) +# makeProd("muon713",10,False,True) # start production with beam smeared on r=3cm disk +# makeProd("muon723",10,True,True) +# makeProd("muon714",10,False,True) # start production with beam smeared on r=3cm disk +# makeProd("muon724",10,True,True) +# makeProd("muon715",10,False,True) # start production with beam smeared on r=3cm disk +# makeProd("muon725",10,True,True) +# makeProd("muon716",10,False,True) # start production with beam smeared on r=3cm disk +# makeProd("muon726",10,True,True) +# makeProd("muon717",10,False,True) # start production with beam smeared on r=3cm disk +# makeProd("muon777",10,False,True) # in case the other one does not work 717 +# makeProd("muon727",10,True,True) # ? +# makeProd("muon718",10,False,True) # start production with beam smeared on r=3cm disk +# makeProd("muon728",10,True,True) +# makeProd("muon719",10,False,True) # start production with beam smeared on r=3cm disk +# makeProd("muon729",10,True,True) +# makeProd("muon730",10,'Jpsi',False) +# makeProd("muon731",10,'Jpsi',True) +# makeProd("muon732",10,'Jpsi',True) +# makeProd("muon733",10,'Jpsi',True) # back to pencil beam +# makeProd("muon630",10,False,True) # test with new muonShield code, 3cm smearing +# makeProd("muon631",10,False,True) # run with concrete wall enabled as sensitive +# makeProd("muon632",10,False,True) # run with concrete wall enabled as sensitive, active shielding polarity fixed +# but wrong geometry +# makeProd("muon810",10,False,False) # start production with latest geometry +# makeProd("muon820",10,True,False) +# makeProd("muon811",10,False,True) # +# makeProd("muon821",10,True,True) ##makeProd("muon812",10,False,True) # --< 831 copied back, done 16.3.2015 -#makeProd("muon822",10,True,True) -#makeProd("muon821",10,True,True) -#makeProd("muon822",10,True,True) +# makeProd("muon822",10,True,True) +# makeProd("muon821",10,True,True) +# makeProd("muon822",10,True,True) # -#makeProd("muon813",10,False,True) # -#makeProd("muon823",10,True,True) - -#makeProd("muon814",10,False,True) # -#makeProd("muon824",10,True,True) -#makeProd("muon815",10,False,True) -#makeProd("muon825",10,True,True) -#makeProd("muon816",10,False,True) -#makeProd("muon826",10,True,True) -#makeProd("muon817",10,False,True) -#makeProd("muon827",10,True,True) -#makeProd("muon818",10,False,True) -#makeProd("muon828",10,True,True) -#makeProd("muon819",10,False,True) -#makeProd("muon829",10,True,True) -#makeProd("muon910",10,False,True) -#makeProd("muon920",10,True,True) -#makeProd("muon911",10,False,True) -#makeProd("muon921",10,True,True) - -#makeProd("muon912",10,False,True) -#makeProd("muon922",10,True,True) - -#makeProd("muon913",10,False,True) -#makeProd("muon923",10,True,True) -#makeProd("muon914",10,False,True) -#makeProd("muon924",10,True,True) -#makeProd("muon915",10,False,True) -#makeProd("muon925",10,True,True) -#makeProd("muon916",10,False,True) -#makeProd("muon926",10,True,True) -#makeProd("muon917",10,False,True) -#makeProd("muon927",10,True,True) -#makeProd("muon927",10,True,True,8) -#makeProd("muon918",10,False,True) -#makeProd("muon928",10,True,True) -#makeProd("muon919",10,False,True) -#makeProd("muon929",10,True,True) -#makeProd("muon1019",10,False,True) -#makeProd("muon1029",10,True,True) -#makeProd("muon1018",10,False,True) -#makeProd("muon1028",10,True,True) -#makeProd("muon1017",10,False,True) -#makeProd("muon1027",10,True,True) -#makeProd("muon1016",10,False,True) -#makeProd("muon1026",10,True,True) -#makeProd("muon1015",10,False,True) -#makeProd("muon1025",10,True,True) -#makeProd("muon1014",10,False,True) -#makeProd("muon1024",10,True,True) -#makeProd("muon1013",10,False,True) -#makeProd("muon1023",10,True,True) -#makeProd("muon1012",10,False,True) -#makeProd("muon1022",10,True,True) -#makeProd("muon633",10,'concrete',False) # run with concrete wall enabled as sensitive -#makeProd("muon1111",10,'False',False) # try iron for first shield -#makeProd("muon1121",10,'True',False) # try iron for first shield -#makeProd("muon1112",10,'False',True) # try iron for first shield -#makeProd("muon1122",10,'True',True) # try iron for first shield +# makeProd("muon813",10,False,True) # +# makeProd("muon823",10,True,True) + +# makeProd("muon814",10,False,True) # +# makeProd("muon824",10,True,True) +# makeProd("muon815",10,False,True) +# makeProd("muon825",10,True,True) +# makeProd("muon816",10,False,True) +# makeProd("muon826",10,True,True) +# makeProd("muon817",10,False,True) +# makeProd("muon827",10,True,True) +# makeProd("muon818",10,False,True) +# makeProd("muon828",10,True,True) +# makeProd("muon819",10,False,True) +# makeProd("muon829",10,True,True) +# makeProd("muon910",10,False,True) +# makeProd("muon920",10,True,True) +# makeProd("muon911",10,False,True) +# makeProd("muon921",10,True,True) + +# makeProd("muon912",10,False,True) +# makeProd("muon922",10,True,True) + +# makeProd("muon913",10,False,True) +# makeProd("muon923",10,True,True) +# makeProd("muon914",10,False,True) +# makeProd("muon924",10,True,True) +# makeProd("muon915",10,False,True) +# makeProd("muon925",10,True,True) +# makeProd("muon916",10,False,True) +# makeProd("muon926",10,True,True) +# makeProd("muon917",10,False,True) +# makeProd("muon927",10,True,True) +# makeProd("muon927",10,True,True,8) +# makeProd("muon918",10,False,True) +# makeProd("muon928",10,True,True) +# makeProd("muon919",10,False,True) +# makeProd("muon929",10,True,True) +# makeProd("muon1019",10,False,True) +# makeProd("muon1029",10,True,True) +# makeProd("muon1018",10,False,True) +# makeProd("muon1028",10,True,True) +# makeProd("muon1017",10,False,True) +# makeProd("muon1027",10,True,True) +# makeProd("muon1016",10,False,True) +# makeProd("muon1026",10,True,True) +# makeProd("muon1015",10,False,True) +# makeProd("muon1025",10,True,True) +# makeProd("muon1014",10,False,True) +# makeProd("muon1024",10,True,True) +# makeProd("muon1013",10,False,True) +# makeProd("muon1023",10,True,True) +# makeProd("muon1012",10,False,True) +# makeProd("muon1022",10,True,True) +# makeProd("muon633",10,'concrete',False) # run with concrete wall enabled as sensitive +# makeProd("muon1111",10,'False',False) # try iron for first shield +# makeProd("muon1121",10,'True',False) # try iron for first shield +# makeProd("muon1112",10,'False',True) # try iron for first shield +# makeProd("muon1122",10,'True',True) # try iron for first shield # restart with also rockS sensitive and &&->|| -#makeProd("muon634",10,'concrete',False) # run with concrete wall enabled as sensitive, and active shield too -#makeProd("muon635",10,'concrete',True) # run with concrete wall enabled as sensitive, and active shield too -#makeProd("muon636",10,'concrete',True) # run with concrete wall enabled as sensitive, and active shield too -#makeProd("muon637",10,'concrete',True) # run with concrete wall enabled as sensitive, and active shield too -#makeProd("muon638",10,'concrete',True) # run with concrete wall enabled as sensitive, and active shield too -#makeProd("muon639",10,'concrete',True) # run with concrete wall enabled as sensitive, and active shield too -#makeProd("muon640",10,'concrete',True) # run with concrete wall enabled as sensitive, and active shield too -#makeProd("muon641",10,'concrete',True) # run with concrete wall enabled as sensitive, and active shield too -#makeProd("muon642",10,'concrete',True) # run with concrete wall enabled as sensitive, and active shield too -#makeProd("muon643",10,'concrete',True) # run with concrete wall enabled as sensitive, and active shield too -#makeProd("muon650",10,'concrete',False) # run with concrete wall enabled as sensitive, first tunnel 10m wide -#makeProd("muon651",10,'concrete',False) # run with concrete wall enabled as sensitive, first tunnel 10m wide -#makeProd("muon652",10,'concrete',True) # run with concrete wall enabled as sensitive, first tunnel 10m wide -#makeProd("muon653",10,'concrete',True) # run with concrete wall enabled as sensitive, first tunnel 10m wide -#makeProd("muon654",10,'concrete',True) # run with concrete wall enabled as sensitive, first tunnel 10m wide -#makeProd("muon655",10,'concrete',True) # run with concrete wall enabled as sensitive, first tunnel 10m wide -#makeProd("muon656",10,'concrete',True) # run with concrete wall enabled as sensitive, first tunnel 10m wide -#makeProd("muon657",10,'concrete',True) # run with concrete wall enabled as sensitive, first tunnel 10m wide -#makeProd("muon658",10,'concrete',True) # run with concrete wall enabled as sensitive, first tunnel 10m wide -#makeProd("muon659",10,'concrete',True) # run with concrete wall enabled as sensitive, first tunnel 10m wide -#makeProd("muon660",10,'concrete',False) # liter magnet -#makeProd("muon661",10,'concrete',True) # liter magnet -#makeProd("muon662",10,'concrete',True) # liter magnet -#makeProd("muon663",10,'concrete',True) # liter magnet -#makeProd("muon664",10,'concrete',True) # liter magnet -#makeProd("muon665",10,'concrete',True) # liter magnet -#makeProd("muon666",10,'concrete',True) # liter magnet -#makeProd("muon667",10,'concrete',True) # liter magnet -#makeProd("muon668",10,'concrete',True) # liter magnet -#makeProd("muon669",10,'concrete',True) # liter magnet -#makeProd("muon670",10,'concrete',False) # even liter magnet -#makeProd("muon671",10,'concrete',True) # even liter magnet -#makeProd("muon672",10,'concrete',True) # even liter magnet -#makeProd("muon673",10,'concrete',True) # even liter magnet -#makeProd("muon674",10,'concrete',True) # even liter magnet -#makeProd("muon675",10,'concrete',True) # even liter magnet -#makeProd("muon676",10,'concrete',True) # even liter magnet -#makeProd("muon677",10,'concrete',True) # even liter magnet -#makeProd("muon678",10,'concrete',True) # even liter magnet -#makeProd("muon679",10,'concrete',True) # even liter magnet +# makeProd("muon634",10,'concrete',False) # run with concrete wall enabled as sensitive, and active shield too +# makeProd("muon635",10,'concrete',True) # run with concrete wall enabled as sensitive, and active shield too +# makeProd("muon636",10,'concrete',True) # run with concrete wall enabled as sensitive, and active shield too +# makeProd("muon637",10,'concrete',True) # run with concrete wall enabled as sensitive, and active shield too +# makeProd("muon638",10,'concrete',True) # run with concrete wall enabled as sensitive, and active shield too +# makeProd("muon639",10,'concrete',True) # run with concrete wall enabled as sensitive, and active shield too +# makeProd("muon640",10,'concrete',True) # run with concrete wall enabled as sensitive, and active shield too +# makeProd("muon641",10,'concrete',True) # run with concrete wall enabled as sensitive, and active shield too +# makeProd("muon642",10,'concrete',True) # run with concrete wall enabled as sensitive, and active shield too +# makeProd("muon643",10,'concrete',True) # run with concrete wall enabled as sensitive, and active shield too +# makeProd("muon650",10,'concrete',False) # run with concrete wall enabled as sensitive, first tunnel 10m wide +# makeProd("muon651",10,'concrete',False) # run with concrete wall enabled as sensitive, first tunnel 10m wide +# makeProd("muon652",10,'concrete',True) # run with concrete wall enabled as sensitive, first tunnel 10m wide +# makeProd("muon653",10,'concrete',True) # run with concrete wall enabled as sensitive, first tunnel 10m wide +# makeProd("muon654",10,'concrete',True) # run with concrete wall enabled as sensitive, first tunnel 10m wide +# makeProd("muon655",10,'concrete',True) # run with concrete wall enabled as sensitive, first tunnel 10m wide +# makeProd("muon656",10,'concrete',True) # run with concrete wall enabled as sensitive, first tunnel 10m wide +# makeProd("muon657",10,'concrete',True) # run with concrete wall enabled as sensitive, first tunnel 10m wide +# makeProd("muon658",10,'concrete',True) # run with concrete wall enabled as sensitive, first tunnel 10m wide +# makeProd("muon659",10,'concrete',True) # run with concrete wall enabled as sensitive, first tunnel 10m wide +# makeProd("muon660",10,'concrete',False) # liter magnet +# makeProd("muon661",10,'concrete',True) # liter magnet +# makeProd("muon662",10,'concrete',True) # liter magnet +# makeProd("muon663",10,'concrete',True) # liter magnet +# makeProd("muon664",10,'concrete',True) # liter magnet +# makeProd("muon665",10,'concrete',True) # liter magnet +# makeProd("muon666",10,'concrete',True) # liter magnet +# makeProd("muon667",10,'concrete',True) # liter magnet +# makeProd("muon668",10,'concrete',True) # liter magnet +# makeProd("muon669",10,'concrete',True) # liter magnet +# makeProd("muon670",10,'concrete',False) # even liter magnet +# makeProd("muon671",10,'concrete',True) # even liter magnet +# makeProd("muon672",10,'concrete',True) # even liter magnet +# makeProd("muon673",10,'concrete',True) # even liter magnet +# makeProd("muon674",10,'concrete',True) # even liter magnet +# makeProd("muon675",10,'concrete',True) # even liter magnet +# makeProd("muon676",10,'concrete',True) # even liter magnet +# makeProd("muon677",10,'concrete',True) # even liter magnet +# makeProd("muon678",10,'concrete',True) # even liter magnet +# makeProd("muon679",10,'concrete',True) # even liter magnet # new attempt, previous did not worked out -#makeProd("muon680",10,'concrete',False) # even liter magnet -#makeProd("muon681",10,'concrete',True) # even liter magnet -#makeProd("muon682",10,'concrete',True) # even liter magnet -#makeProd("muon683",10,'concrete',True) # even liter magnet -#makeProd("muon684",10,'concrete',True) # even liter magnet -#makeProd("muon685",10,'concrete',True) # even liter magnet -#makeProd("muon686",10,'concrete',True) # even liter magnet -#makeProd("muon687",10,'concrete',True) # even liter magnet -#makeProd("muon688",10,'concrete',True) # even liter magnet -#makeProd("muon689",10,'concrete',True) # even liter magnet +# makeProd("muon680",10,'concrete',False) # even liter magnet +# makeProd("muon681",10,'concrete',True) # even liter magnet +# makeProd("muon682",10,'concrete',True) # even liter magnet +# makeProd("muon683",10,'concrete',True) # even liter magnet +# makeProd("muon684",10,'concrete',True) # even liter magnet +# makeProd("muon685",10,'concrete',True) # even liter magnet +# makeProd("muon686",10,'concrete',True) # even liter magnet +# makeProd("muon687",10,'concrete',True) # even liter magnet +# makeProd("muon688",10,'concrete',True) # even liter magnet +# makeProd("muon689",10,'concrete',True) # even liter magnet # new attempt, increase height of first magnet, previous did not worked out either -#makeProd("muon690",10,'concrete',False) # even liter magnet -#makeProd("muon691",10,'concrete',True) # even liter magnet -#makeProd("muon692",10,'concrete',True) # even liter magnet -#makeProd("muon693",10,'concrete',True) # even liter magnet -#makeProd("muon694",10,'concrete',True) # even liter magnet -#makeProd("muon695",10,'concrete',True) # even liter magnet -#makeProd("muon696",10,'concrete',True) # even liter magnet -#makeProd("muon697",10,'concrete',True) # even liter magnet -#makeProd("muon698",10,'concrete',True) # even liter magnet -#makeProd("muon699",10,'concrete',True) # even liter magnet +# makeProd("muon690",10,'concrete',False) # even liter magnet +# makeProd("muon691",10,'concrete',True) # even liter magnet +# makeProd("muon692",10,'concrete',True) # even liter magnet +# makeProd("muon693",10,'concrete',True) # even liter magnet +# makeProd("muon694",10,'concrete',True) # even liter magnet +# makeProd("muon695",10,'concrete',True) # even liter magnet +# makeProd("muon696",10,'concrete',True) # even liter magnet +# makeProd("muon697",10,'concrete',True) # even liter magnet +# makeProd("muon698",10,'concrete',True) # even liter magnet +# makeProd("muon699",10,'concrete',True) # even liter magnet # testing height 4m->2m -#makeProd("muon700",10,'concrete',False) # even liter magnet -#makeProd("muon701",10,'concrete',True) # even liter magnet -#makeProd("muon702",10,'concrete',True) # even liter magnet -#makeProd("muon703",10,'concrete',True) # even liter magnet -#makeProd("muon704",10,'concrete',True) # even liter magnet -#makeProd("muon705",10,'concrete',True) # even liter magnet -#makeProd("muon706",10,'concrete',True) # even liter magnet -#makeProd("muon707",10,'concrete',True) # even liter magnet -#makeProd("muon708",10,'concrete',True) # even liter magnet -#makeProd("muon709",10,'concrete',True) # even liter magnet +# makeProd("muon700",10,'concrete',False) # even liter magnet +# makeProd("muon701",10,'concrete',True) # even liter magnet +# makeProd("muon702",10,'concrete',True) # even liter magnet +# makeProd("muon703",10,'concrete',True) # even liter magnet +# makeProd("muon704",10,'concrete',True) # even liter magnet +# makeProd("muon705",10,'concrete',True) # even liter magnet +# makeProd("muon706",10,'concrete',True) # even liter magnet +# makeProd("muon707",10,'concrete',True) # even liter magnet +# makeProd("muon708",10,'concrete',True) # even liter magnet +# makeProd("muon709",10,'concrete',True) # even liter magnet # testing height 4m->2m + new magnets -#makeProd("muon800",10,'concrete',False) # even liter magnet -#makeProd("muon801",10,'concrete',True) # even liter magnet -#makeProd("muon802",10,'concrete',True) # even liter magnet -#makeProd("muon803",10,'concrete',True) # even liter magnet -#makeProd("muon804",10,'concrete',True) # even liter magnet -#makeProd("muon805",10,'concrete',True) # even liter magnet -#makeProd("muon806",10,'concrete',True) # even liter magnet -#makeProd("muon807",10,'concrete',True) # even liter magnet -#makeProd("muon808",10,'concrete',True) # even liter magnet -#makeProd("muon809",10,'concrete',True) # even liter magnet +# makeProd("muon800",10,'concrete',False) # even liter magnet +# makeProd("muon801",10,'concrete',True) # even liter magnet +# makeProd("muon802",10,'concrete',True) # even liter magnet +# makeProd("muon803",10,'concrete',True) # even liter magnet +# makeProd("muon804",10,'concrete',True) # even liter magnet +# makeProd("muon805",10,'concrete',True) # even liter magnet +# makeProd("muon806",10,'concrete',True) # even liter magnet +# makeProd("muon807",10,'concrete',True) # even liter magnet +# makeProd("muon808",10,'concrete',True) # even liter magnet +# makeProd("muon809",10,'concrete',True) # even liter magnet # new iteration, and ship_geo.Yheight*1./10. -#makeProd("muon710",10,'concrete',False) # even liter magnet -#makeProd("muon711",10,'concrete',True) # even liter magnet -#makeProd("muon712",10,'concrete',True) # even liter magnet -#makeProd("muon713",10,'concrete',True) # even liter magnet -#makeProd("muon714",10,'concrete',True) # even liter magnet -#makeProd("muon715",10,'concrete',True) # even liter magnet -#makeProd("muon716",10,'concrete',True) # even liter magnet -#makeProd("muon717",10,'concrete',True) # even liter magnet -#makeProd("muon718",10,'concrete',True) # even liter magnet -#makeProd("muon719",10,'concrete',True) # even liter magnet +# makeProd("muon710",10,'concrete',False) # even liter magnet +# makeProd("muon711",10,'concrete',True) # even liter magnet +# makeProd("muon712",10,'concrete',True) # even liter magnet +# makeProd("muon713",10,'concrete',True) # even liter magnet +# makeProd("muon714",10,'concrete',True) # even liter magnet +# makeProd("muon715",10,'concrete',True) # even liter magnet +# makeProd("muon716",10,'concrete',True) # even liter magnet +# makeProd("muon717",10,'concrete',True) # even liter magnet +# makeProd("muon718",10,'concrete',True) # even liter magnet +# makeProd("muon719",10,'concrete',True) # even liter magnet # new iteration, and back to ship_geo.Yheight*2./10. -#makeProd("muon720",10,'concrete',False) # even liter magnet -#makeProd("muon721",10,'concrete',True) # even liter magnet -#makeProd("muon722",10,'concrete',True) # even liter magnet -#makeProd("muon723",10,'concrete',True) # even liter magnet -#makeProd("muon724",10,'concrete',True) # even liter magnet -#makeProd("muon725",10,'concrete',True) # even liter magnet -#makeProd("muon726",10,'concrete',True) # even liter magnet -#makeProd("muon727",10,'concrete',True) # even liter magnet -#makeProd("muon728",10,'concrete',True) # even liter magnet -#makeProd("muon729",10,'concrete',True) # even liter magnet +# makeProd("muon720",10,'concrete',False) # even liter magnet +# makeProd("muon721",10,'concrete',True) # even liter magnet +# makeProd("muon722",10,'concrete',True) # even liter magnet +# makeProd("muon723",10,'concrete',True) # even liter magnet +# makeProd("muon724",10,'concrete',True) # even liter magnet +# makeProd("muon725",10,'concrete',True) # even liter magnet +# makeProd("muon726",10,'concrete',True) # even liter magnet +# makeProd("muon727",10,'concrete',True) # even liter magnet +# makeProd("muon728",10,'concrete',True) # even liter magnet +# makeProd("muon729",10,'concrete',True) # even liter magnet # new iteration, and back to ship_geo.Yheight*2./10. but with more info in vetoPoint -#makeProd("muon730",10,'concrete',False) # even liter magnet -#makeProd("muon740",10,'concrete',False) # even liter magnet +# makeProd("muon730",10,'concrete',False) # even liter magnet +# makeProd("muon740",10,'concrete',False) # even liter magnet # new iteration, ship_geo.Yheight*1./10. -#makeProd("muon750",10,'concrete',False) # +# makeProd("muon750",10,'concrete',False) # # new iteration, ship_geo.Yheight*1.5/10. -#makeProd("muon760",10,'concrete',False) # -#makeProd("muon761",10,'concrete',True) # +# makeProd("muon760",10,'concrete',False) # +# makeProd("muon761",10,'concrete',True) # # as before but now with full simulation -#makeProd("muon1710",10,False,False) -#makeProd("muon1720",10,True,False) -#makeProd("muon1711",10,False,True) -#makeProd("muon1721",10,True,True) -#makeProd("muon1712",10,False,True) -#makeProd("muon1722",10,True,True) -#makeProd("muon1713",10,False,True) -#makeProd("muon1723",10,True,True) -#makeProd("muon1714",10,False,True) -#makeProd("muon1724",10,True,True) -#makeProd("muon1715",10,False,True) -#makeProd("muon1725",10,True,True) -#makeProd("muon1716",10,False,True) -#makeProd("muon1726",10,True,True) +# makeProd("muon1710",10,False,False) +# makeProd("muon1720",10,True,False) +# makeProd("muon1711",10,False,True) +# makeProd("muon1721",10,True,True) +# makeProd("muon1712",10,False,True) +# makeProd("muon1722",10,True,True) +# makeProd("muon1713",10,False,True) +# makeProd("muon1723",10,True,True) +# makeProd("muon1714",10,False,True) +# makeProd("muon1724",10,True,True) +# makeProd("muon1715",10,False,True) +# makeProd("muon1725",10,True,True) +# makeProd("muon1716",10,False,True) +# makeProd("muon1726",10,True,True) # another one, hopefully better -#makeProd("muon1717",10,'concrete',False) # +# makeProd("muon1717",10,'concrete',False) # # another one, increasing height to 3m -#makeProd("muon1718",10,'concrete',False) # +# makeProd("muon1718",10,'concrete',False) # -prefixes = [] +prefixes = [] withChain = 0 -pref = 'muon' -xx = os.path.abspath('.').lower() -if not xx.find('neutrino')<0: pref='neutrino' -if not xx.find('vdis')<0: pref='disV' -elif not xx.find('clby')<0: pref='disCLBY' -elif not xx.find('dis')<0: pref='dis' - -if len(os.sys.argv)>1 : - for i in range(1,len(os.sys.argv)): - for prefix in os.sys.argv[i].split(','): - if prefix.find(pref)<0:prefix=pref+prefix - prefixes.append(prefix) - withChain+=1 +pref = "muon" +xx = os.path.abspath(".").lower() +if not xx.find("neutrino") < 0: + pref = "neutrino" +if not xx.find("vdis") < 0: + pref = "disV" +elif not xx.find("clby") < 0: + pref = "disCLBY" +elif not xx.find("dis") < 0: + pref = "dis" + +if len(os.sys.argv) > 1: + for i in range(1, len(os.sys.argv)): + for prefix in os.sys.argv[i].split(","): + if prefix.find(pref) < 0: + prefix = pref + prefix + prefixes.append(prefix) + withChain += 1 else: - prefixes = [''] + prefixes = [""] -testdir = '.' -path = '' +testdir = "." +path = "" # if local: path = "/media/Data/HNL/muonBackground/" -if prefixes[0]!='': testdir = path+prefixes[0]+'1' +if prefixes[0] != "": + testdir = path + prefixes[0] + "1" # figure out which setup for f in os.listdir(testdir): - if not f.find("geofile_full")<0: - fgeo = ROOT.TFile(testdir+'/'+f) - sGeo = fgeo.FAIRGeom - inputFile = f.replace("geofile_full","ship") - break + if not f.find("geofile_full") < 0: + fgeo = ROOT.TFile(testdir + "/" + f) + sGeo = fgeo.FAIRGeom + inputFile = f.replace("geofile_full", "ship") + break # try to extract from input file name -tmp = inputFile.split('.') +tmp = inputFile.split(".") try: - dy = float( tmp[1]+'.'+tmp[2] ) + dy = float(tmp[1] + "." + tmp[2]) except: - dy = 10. + dy = 10.0 -if not inputFile.find('_D.')<0: - inputFile1 = inputFile.replace('_D.','.') - inputFile2 = inputFile -else : - inputFile1 = inputFile - inputFile2 = inputFile.replace('.root','_D.root') +if not inputFile.find("_D.") < 0: + inputFile1 = inputFile.replace("_D.", ".") + inputFile2 = inputFile +else: + inputFile1 = inputFile + inputFile2 = inputFile.replace(".root", "_D.root") import rootUtils as ut import shipunit as u + PDG = ROOT.TDatabasePDG.Instance() from ShipGeoConfig import ConfigRegistry + # init geometry and mag. field -if not fgeo.FindKey('ShipGeo'): - # old geofile, missing Shipgeo dictionary - if sGeo.GetVolume('EcalModule3') : ecalGeoFile = "ecal_ellipse6x12m2.geo" - else: ecalGeoFile = "ecal_ellipse5x10m2.geo" - print('found ecal geo for ',ecalGeoFile) - # re-create geometry and mag. field - ShipGeo = ConfigRegistry.loadpy("$FAIRSHIP/geometry/geometry_config.py", Yheight = dy, EcalGeoFile = ecalGeoFile ) +if not fgeo.FindKey("ShipGeo"): + # old geofile, missing Shipgeo dictionary + if sGeo.GetVolume("EcalModule3"): + ecalGeoFile = "ecal_ellipse6x12m2.geo" + else: + ecalGeoFile = "ecal_ellipse5x10m2.geo" + print("found ecal geo for ", ecalGeoFile) + # re-create geometry and mag. field + ShipGeo = ConfigRegistry.loadpy( + "$FAIRSHIP/geometry/geometry_config.py", Yheight=dy, EcalGeoFile=ecalGeoFile + ) else: - # new geofile, load Shipgeo dictionary written by run_simScript.py - upkl = Unpickler(fgeo) - ShipGeo = upkl.load('ShipGeo') - ecalGeoFile = ShipGeo.ecal.File + # new geofile, load Shipgeo dictionary written by run_simScript.py + upkl = Unpickler(fgeo) + ShipGeo = upkl.load("ShipGeo") + ecalGeoFile = ShipGeo.ecal.File # -----Create geometry---------------------------------------------- import shipDet_conf + run = ROOT.FairRunSim() -modules = shipDet_conf.configure(run,ShipGeo) - -ecal = modules['Ecal'] - -rz_inter = -1.,0. -def origin(sTree,it): - at = sTree.MCTrack[it] - im = at.GetMotherId() - if im>0: origin(sTree,im) - if im<0: - # print 'does not come from muon' - rz_inter = -1.,0. - if im==0: - #print 'origin z',at.GetStartZ() - rz_inter = ROOT.TMath.Sqrt(at.GetStartX()**2+at.GetStartY()**2),at.GetStartZ() +modules = shipDet_conf.configure(run, ShipGeo) + +ecal = modules["Ecal"] + +rz_inter = -1.0, 0.0 + + +def origin(sTree, it): + at = sTree.MCTrack[it] + im = at.GetMotherId() + if im > 0: + origin(sTree, im) + if im < 0: + # print 'does not come from muon' + rz_inter = -1.0, 0.0 + if im == 0: + # print 'origin z',at.GetStartZ() + rz_inter = ( + ROOT.TMath.Sqrt(at.GetStartX() ** 2 + at.GetStartY() ** 2), + at.GetStartZ(), + ) + otherPhysList = False -noField = False -passive = False +noField = False +passive = False # -top = sGeo.GetTopVolume() +top = sGeo.GetTopVolume() muon = top.GetNode("MuonDetector_1") mvol = muon.GetVolume() zmuon = muon.GetMatrix().GetTranslation()[2] -totl = (zmuon + mvol.GetShape().GetDZ() ) / u.m -ztarget = -100. +totl = (zmuon + mvol.GetShape().GetDZ()) / u.m +ztarget = -100.0 fchain = [] fchainRec = [] # first time trying to read a chain of Fairship files, doesn't seem to work out of the box, try some tricks. -testdir = '.' -if path != '': testdir = path -if withChain>0: - for prefix in prefixes: - for i in range(1,10): - if not prefix+str(i) in os.listdir(testdir): continue - q1 = inputFile1 in os.listdir(path+prefix+str(i)) - q2 = inputFile2 in os.listdir(path+prefix+str(i)) - recFile1 = inputFile1.replace('.root','_rec.root') - recFile2 = inputFile2.replace('.root','_rec.root') - r1 = recFile1 in os.listdir(path+prefix+str(i)) - r2 = recFile2 in os.listdir(path+prefix+str(i)) - if q1 or r1 : inputFile = inputFile1 - elif q2 or r2: inputFile = inputFile2 - else: continue - fname = path+prefix+str(i)+'/'+inputFile - recFile = inputFile.replace('.root','_rec.root') - if not recFile in os.listdir(path+prefix+str(i)): - fchain.append(fname) - continue - fname = path+prefix+str(i)+'/'+recFile - fchainRec.append(fname) - fchain.append(fname) # take rec file if exist +testdir = "." +if path != "": + testdir = path +if withChain > 0: + for prefix in prefixes: + for i in range(1, 10): + if not prefix + str(i) in os.listdir(testdir): + continue + q1 = inputFile1 in os.listdir(path + prefix + str(i)) + q2 = inputFile2 in os.listdir(path + prefix + str(i)) + recFile1 = inputFile1.replace(".root", "_rec.root") + recFile2 = inputFile2.replace(".root", "_rec.root") + r1 = recFile1 in os.listdir(path + prefix + str(i)) + r2 = recFile2 in os.listdir(path + prefix + str(i)) + if q1 or r1: + inputFile = inputFile1 + elif q2 or r2: + inputFile = inputFile2 + else: + continue + fname = path + prefix + str(i) + "/" + inputFile + recFile = inputFile.replace(".root", "_rec.root") + if not recFile in os.listdir(path + prefix + str(i)): + fchain.append(fname) + continue + fname = path + prefix + str(i) + "/" + recFile + fchainRec.append(fname) + fchain.append(fname) # take rec file if exist else: - fchain.append(inputFile) - prefix = '' + fchain.append(inputFile) + prefix = "" + def makeProd(): - ntot = 736406 - ncpu = 4 - n3 = int(ntot/ncpu) - cmd = "python $FAIRSHIP/macro/run_simScript.py --MuonBack -f $SHIPSOFT/data/pythia8_Geant4_onlyMuons.root " # --display" - ns = 0 - prefix = 'muon18' - for i in range(1,ncpu+1): - d = prefix+str(i) - if d not in os.listdir('.'): os.system('mkdir '+d) - os.chdir('./'+prefix+'1') - for i in range(1,ncpu+1): - if i==ncpu: n3 = ntot - i*n3 - os.system('cp $FAIRSHIP/macro/run_simScript.py .') - os.system(cmd+" -n "+str(n3)+" -i "+str(ns) + " > log &") - # print " -n "+str(n3)+" -i "+str(ns) - ns += n3 - if i==ncpu: break - os.chdir('../'+prefix+str(i+1)) + ntot = 736406 + ncpu = 4 + n3 = int(ntot / ncpu) + cmd = "python $FAIRSHIP/macro/run_simScript.py --MuonBack -f $SHIPSOFT/data/pythia8_Geant4_onlyMuons.root " # --display" + ns = 0 + prefix = "muon18" + for i in range(1, ncpu + 1): + d = prefix + str(i) + if d not in os.listdir("."): + os.system("mkdir " + d) + os.chdir("./" + prefix + "1") + for i in range(1, ncpu + 1): + if i == ncpu: + n3 = ntot - i * n3 + os.system("cp $FAIRSHIP/macro/run_simScript.py .") + os.system(cmd + " -n " + str(n3) + " -i " + str(ns) + " > log &") + # print " -n "+str(n3)+" -i "+str(ns) + ns += n3 + if i == ncpu: + break + os.chdir("../" + prefix + str(i + 1)) + def strawEncoding(detid): - # statnb*10000000+vnb*1000000+pnb*100000+lnb*10000+1000+snb - # vnb=view number; pnb=plane number; lnb=layer number; snb=straw number - # statnb = station number. 1,2,3,4 tracking stations, 5 veto station - vnb = ROOT.Long() - pnb = ROOT.Long() - lnb = ROOT.Long() - snb = ROOT.Long() - statnb = ROOT.Long() - modules['Strawtubes'].StrawDecode(detid,statnb,vnb,pnb,lnb,snb) - return [statnb,vnb,pnb,lnb,snb] + # statnb*10000000+vnb*1000000+pnb*100000+lnb*10000+1000+snb + # vnb=view number; pnb=plane number; lnb=layer number; snb=straw number + # statnb = station number. 1,2,3,4 tracking stations, 5 veto station + vnb = ROOT.Long() + pnb = ROOT.Long() + lnb = ROOT.Long() + snb = ROOT.Long() + statnb = ROOT.Long() + modules["Strawtubes"].StrawDecode(detid, statnb, vnb, pnb, lnb, snb) + return [statnb, vnb, pnb, lnb, snb] + def detMap(): - sGeo = ROOT.gGeoManager - detList = {} - for v in sGeo.GetListOfVolumes(): - nm = v.GetName() - i = sGeo.FindVolumeFast(nm).GetNumber() - detList[i] = nm - return detList - -def fitSingleGauss(x,ba=None,be=None): - name = 'myGauss_'+x + sGeo = ROOT.gGeoManager + detList = {} + for v in sGeo.GetListOfVolumes(): + nm = v.GetName() + i = sGeo.FindVolumeFast(nm).GetNumber() + detList[i] = nm + return detList + + +def fitSingleGauss(x, ba=None, be=None): + name = "myGauss_" + x myGauss = h[x].GetListOfFunctions().FindObject(name) if not myGauss: - if not ba : ba = h[x].GetBinCenter(1) - if not be : be = h[x].GetBinCenter(h[x].GetNbinsX()) - bw = h[x].GetBinWidth(1) - mean = h[x].GetMean() - sigma = h[x].GetRMS() - norm = h[x].GetEntries()*0.3 - myGauss = TF1(name,'[0]*'+str(bw)+'/([2]*sqrt(2*pi))*exp(-0.5*((x-[1])/[2])**2)+[3]',4) - myGauss.SetParameter(0,norm) - myGauss.SetParameter(1,mean) - myGauss.SetParameter(2,sigma) - myGauss.SetParameter(3,1.) - myGauss.SetParName(0,'Signal') - myGauss.SetParName(1,'Mean') - myGauss.SetParName(2,'Sigma') - h[x].Fit(myGauss,'','',ba,be) - - -h={} -histlist={} + if not ba: + ba = h[x].GetBinCenter(1) + if not be: + be = h[x].GetBinCenter(h[x].GetNbinsX()) + bw = h[x].GetBinWidth(1) + mean = h[x].GetMean() + sigma = h[x].GetRMS() + norm = h[x].GetEntries() * 0.3 + myGauss = TF1( + name, + "[0]*" + str(bw) + "/([2]*sqrt(2*pi))*exp(-0.5*((x-[1])/[2])**2)+[3]", + 4, + ) + myGauss.SetParameter(0, norm) + myGauss.SetParameter(1, mean) + myGauss.SetParameter(2, sigma) + myGauss.SetParameter(3, 1.0) + myGauss.SetParName(0, "Signal") + myGauss.SetParName(1, "Mean") + myGauss.SetParName(2, "Sigma") + h[x].Fit(myGauss, "", "", ba, be) + + +h = {} +histlist = {} txt = {} -l={} +l = {} logVols = detMap() + def bookHist(detName): - for mu in ['','_mu','_muV0']: - tag = detName+mu - if detName.find('LS')<0: - ut.bookHist(h,tag,'x/y '+detName,100,-3.,3.,100,-6.,6.) - else: - ut.bookHist(h,tag,'z phi '+detName,100,-50.,50.,100,-1.,1.) - ut.bookHist(h,tag+'_E','deposited energy MeV '+detName,100,0.,2.) - ut.bookHist(h,tag+'_P','particle mom GeV '+detName,500,0.,50.) - ut.bookHist(h,tag+'_LP','particle mom GeV '+detName,100,0.,1.) - ut.bookHist(h,tag+'_OP','original particle mom GeV '+detName,400,0.,400.) - ut.bookHist(h,tag+'_id','particle id '+detName,5001,-2499.5,2499.5) - ut.bookHist(h,tag+'_mul','multiplicity of hits/tracks '+detName,100,-0.5,99.5) - ut.bookHist(h,tag+'_evmul','multiplicity of hits/event '+detName,100,-0.5,9999.5) - ut.bookHist(h,tag+'_origin','r vs z',100, ztarget,totl,100,0.,12.) - ut.bookHist(h,tag+'_originmu','r vs z',100,ztarget,totl,100,0.,12.) - -ut.bookHist(h,'origin','r vs z',100,ztarget,totl,100,0.,15.) -ut.bookHist(h,'borigin','r vs z',100,ztarget,totl,500,0.,30.) -ut.bookHist(h,'porigin','r vs z secondary',100,ztarget,totl,500,0.,30.) -ut.bookHist(h,'mu-inter','r vs z',100,ztarget,totl,50,0.,3.) -ut.bookHist(h,'muonP','muon momentum',100,0.,400.) -ut.bookHist(h,'weight','muon weight',1000,1.E3,1.E6) -ut.bookHist(h,'delx13','x diff first and last point, mu-',100,-10.,10.) -ut.bookHist(h,'delx-13','x diff first and last point, mu+',100,-10.,10.) -ut.bookHist(h,'deltaElec','energy of delta electrons',100,0.,10.) -ut.bookHist(h,'secondaries','energy of delta electrons',100,0.,10.) -ut.bookHist(h,'prop_deltaElec','energy of delta elec / muon energy',100,0.,1.) -ut.bookHist(h,'dummy','',10,0.,1.) -ut.bookHist(h,'dE','',100,0.,10.,100,0.,10.) -h['dummy'].SetMaximum(10.) - -histlistAll = {1:'strawstation_5',2:'strawstation_1',3:'strawstation_4',4:'Ecal',5:'muondet', - 6:'VetoTimeDet',7:'T1LiSc',8:'T2LiSc',9:'T3LiSc',10:'T5LiSc', - 11:'ShipRpc',12:'volHPT',13:'Target',14:'TimeDet',15:'Det2'} -hLiSc = {1:{}} -for i in range(1,7): hLiSc[1][i] = "T1LiSc_"+str(i) + for mu in ["", "_mu", "_muV0"]: + tag = detName + mu + if detName.find("LS") < 0: + ut.bookHist(h, tag, "x/y " + detName, 100, -3.0, 3.0, 100, -6.0, 6.0) + else: + ut.bookHist(h, tag, "z phi " + detName, 100, -50.0, 50.0, 100, -1.0, 1.0) + ut.bookHist(h, tag + "_E", "deposited energy MeV " + detName, 100, 0.0, 2.0) + ut.bookHist(h, tag + "_P", "particle mom GeV " + detName, 500, 0.0, 50.0) + ut.bookHist(h, tag + "_LP", "particle mom GeV " + detName, 100, 0.0, 1.0) + ut.bookHist( + h, tag + "_OP", "original particle mom GeV " + detName, 400, 0.0, 400.0 + ) + ut.bookHist(h, tag + "_id", "particle id " + detName, 5001, -2499.5, 2499.5) + ut.bookHist( + h, tag + "_mul", "multiplicity of hits/tracks " + detName, 100, -0.5, 99.5 + ) + ut.bookHist( + h, + tag + "_evmul", + "multiplicity of hits/event " + detName, + 100, + -0.5, + 9999.5, + ) + ut.bookHist(h, tag + "_origin", "r vs z", 100, ztarget, totl, 100, 0.0, 12.0) + ut.bookHist(h, tag + "_originmu", "r vs z", 100, ztarget, totl, 100, 0.0, 12.0) + + +ut.bookHist(h, "origin", "r vs z", 100, ztarget, totl, 100, 0.0, 15.0) +ut.bookHist(h, "borigin", "r vs z", 100, ztarget, totl, 500, 0.0, 30.0) +ut.bookHist(h, "porigin", "r vs z secondary", 100, ztarget, totl, 500, 0.0, 30.0) +ut.bookHist(h, "mu-inter", "r vs z", 100, ztarget, totl, 50, 0.0, 3.0) +ut.bookHist(h, "muonP", "muon momentum", 100, 0.0, 400.0) +ut.bookHist(h, "weight", "muon weight", 1000, 1.0e3, 1.0e6) +ut.bookHist(h, "delx13", "x diff first and last point, mu-", 100, -10.0, 10.0) +ut.bookHist(h, "delx-13", "x diff first and last point, mu+", 100, -10.0, 10.0) +ut.bookHist(h, "deltaElec", "energy of delta electrons", 100, 0.0, 10.0) +ut.bookHist(h, "secondaries", "energy of delta electrons", 100, 0.0, 10.0) +ut.bookHist(h, "prop_deltaElec", "energy of delta elec / muon energy", 100, 0.0, 1.0) +ut.bookHist(h, "dummy", "", 10, 0.0, 1.0) +ut.bookHist(h, "dE", "", 100, 0.0, 10.0, 100, 0.0, 10.0) +h["dummy"].SetMaximum(10.0) + +histlistAll = { + 1: "strawstation_5", + 2: "strawstation_1", + 3: "strawstation_4", + 4: "Ecal", + 5: "muondet", + 6: "VetoTimeDet", + 7: "T1LiSc", + 8: "T2LiSc", + 9: "T3LiSc", + 10: "T5LiSc", + 11: "ShipRpc", + 12: "volHPT", + 13: "Target", + 14: "TimeDet", + 15: "Det2", +} +hLiSc = {1: {}} +for i in range(1, 7): + hLiSc[1][i] = "T1LiSc_" + str(i) hLiSc[2] = {} -for i in range(1,48): hLiSc[2][i] = "T2LiSc_"+str(i) +for i in range(1, 48): + hLiSc[2][i] = "T2LiSc_" + str(i) hLiSc[3] = {} -for i in range(1,3): hLiSc[3][i] = "T3LiSc_"+str(i) +for i in range(1, 3): + hLiSc[3][i] = "T3LiSc_" + str(i) hLiSc[5] = {} -for i in range(1,3): hLiSc[5][i] = "T5LiSc_"+str(i) +for i in range(1, 3): + hLiSc[5][i] = "T5LiSc_" + str(i) hMuon = {} -for i in range(0,4): hMuon[i] = "muondet"+str(i) +for i in range(0, 4): + hMuon[i] = "muondet" + str(i) # start event loop mom = ROOT.TVector3() pos = ROOT.TVector3() + def BigEventLoop(): - pid = 1 - for fn in fchain: - if os.path.islink(fn): - rfn = os.path.realpath(fn).split('eos')[1] - fn = ROOT.gSystem.Getenv("EOSSHIP")+'/eos/'+rfn - elif not os.path.isfile(fn): - print("Don't know what to do with",fn) - 1/0 - if parallel: -# process files parallel instead of sequential - processes.append(mp.Process(target=executeOneFile, args=(fn,output,pid) ) ) - pid+=1 - else: - processes.append(fn) -# Run processes - n=0 - for p in processes: - if parallel: - p.start() - n+=1 - else: executeOneFile(p) - if parallel: -# Exit the completed processes - for p in processes: p.join() -# clean histos before reading in the new ones - for x in h: h[x].Reset() - print("now, collect the output") - pid = 1 - for p in processes: - ut.readHists(h,'tmpHists_'+str(pid)+'.root') - pid+=1 -# compactify liquid scintillator - for mu in ['','_mu','_muV0']: - for x in ['','_E','_P','_LP','_OP','_id','_mul','_evmul','_origin','_originmu']: - for k in [1,2,3,5]: - first = True - for j in hLiSc[k]: - detName=hLiSc[k][j] - tag = detName+mu+x - newh = detName[0:2]+'LiSc'+mu+x - if tag not in h: continue - if first: - h[newh] = h[tag].Clone(newh) - h[newh].SetTitle( h[tag].GetTitle().split('_')[0]) - first = False - else: rc = h[newh].Add(h[tag]) -# compactify muon stations - for mu in ['','_mu','_muV0']: - for x in ['','_E','_P','_LP','_OP','_id','_mul','_evmul','_origin','_originmu']: - first = True - for j in hMuon: - detName=hMuon[j] - tag = detName+mu+x - newh = 'muondet'+mu+x - if first: - h[newh] = h[tag].Clone(newh) - h[newh].SetTitle( h[tag].GetTitle().split(' ')[0]+' '+newh) - first = False - else: rc = h[newh].Add(h[tag]) - - # make list of hists with entries - k = 1 - for x in histlistAll: - if histlistAll[x] in h: - histlist[k]=histlistAll[x] -# make cumulative histograms - for c in ['','_E','_P','_LP','_OP','_id','_mul','_evmul','_origin','_originmu']: - h[histlist[k]+'_mu'+c].Add( h[histlist[k]+'_muV0'+c] ) - h[histlist[k]+c].Add( h[histlist[k]+'_mu'+c] ) - h[histlist[k]+c].SetMinimum(0.) - h[histlist[k]+'_mu'+c].SetMinimum(0.) - h[histlist[k]+'_muV0'+c] .SetMinimum(0.) - k+=1 - nstations = len(histlist) - makePlots(nstations) - -def executeOneFile(fn,output=None,pid=None): - f = ROOT.TFile.Open(fn) - sTree = f.cbmsim - nEvents = sTree.GetEntries() - if sTree.GetBranch("GeoTracks"): sTree.SetBranchStatus("GeoTracks",0) - sTree.GetEntry(0) - hitContainers = [sTree.vetoPoint,sTree.muonPoint,sTree.EcalPointLite,sTree.strawtubesPoint,sTree.ShipRpcPoint,sTree.TargetPoint] - ntot = 0 - for n in range(nEvents): - rc = sTree.GetEntry(n) - theMuon = sTree.MCTrack[0] - if sTree.MCTrack.GetEntries() > 1: - w = sTree.MCTrack[1].GetWeight() # also works for neutrinos - else: - print('should not happen with new files',n,fn) - w = sTree.MCTrack[0].GetWeight() # also works for neutrinos - if w==0 : w = 1. - rc = h['weight'].Fill(w) - rc = h['muonP'].Fill(theMuon.GetP()/u.GeV,w) - ntot+=1 - if ntot%10000 == 0 : print('read event',f.GetName(),n) - hitmult = {} - esum = 0 - for mcp in sTree.MCTrack: - if mcp.GetMotherId() == 0: # mother is original muon - E = mcp.GetEnergy() - if mcp.GetPdgCode() == 11: - rc = h['deltaElec'].Fill(E,w) - esum += E - rc = h['secondaries'].Fill(E,w) - rc = h['prop_deltaElec'].Fill(esum/sTree.MCTrack[0].GetP(),w) # until energy is really made persistent GetEnergy() - for c in hitContainers: - for ahit in c: - if not ahit.GetEnergyLoss()>0: continue - detID = ahit.GetDetectorID() - if ahit.GetName() == 'strawtubesPoint': - tmp = strawEncoding(detID) - # detName = str(tmp[0]*10000000+tmp[1]*1000000+tmp[2]*100000+tmp[3]*10000) - detName = "strawstation_"+str(tmp[0]) - x = ahit.GetX() - y = ahit.GetY() - E = ahit.GetEnergyLoss() - elif ahit.GetName() == 'ecalPoint': - # not needed for lite collection: if abs(ahit.GetPdgCode())==12 or abs(ahit.GetPdgCode())==14 : continue - detName = 'Ecal' - ecal.GetCellCoordForPy(detID,pos) - x = pos.X() - y = pos.Y() - E = ahit.GetEnergyLoss() - else: - if detID not in logVols: - detName = c.GetName().replace('Points','') - if not detName in histlistAll.values(): print(detID,detName,c.GetName()) - else: detName = logVols[detID] - x = ahit.GetX() - y = ahit.GetY() - z = ahit.GetZ() - E = ahit.GetEnergyLoss() - if detName not in h: bookHist(detName) - mu='' - pdgID = -2 - if 'PdgCode' in dir(ahit): pdgID = ahit.PdgCode() - trackID = ahit.GetTrackID() - phit = -100. - mom = ROOT.TVector3() - if not trackID < 0: - aTrack = sTree.MCTrack[trackID] - pdgID = aTrack.GetPdgCode() - aTrack.GetMomentum(mom) # ! this is not momentum of particle at Calorimeter place - phit = mom.Mag()/u.GeV - if abs(pdgID)==13: mu='_mu' - if ahit.GetName().find('ecal')<0: - rc = ahit.Momentum(mom) - phit = mom.Mag()/u.GeV - else: - for ahit in sTree.EcalPoint: - if ahit.GetTrackID() == trackID: - rc = ahit.Momentum(mom) - phit = mom.Mag()/u.GeV - if phit>3 and abs(pdgID)==13: mu='_muV0' - detName = detName + mu - if detName.find('LS')<0: rc = h[detName].Fill(x/u.m,y/u.m,w) - else: rc = h[detName].Fill(ahit.GetZ()/u.m,ROOT.TMath.ATan2(y,x)/ROOT.TMath.Pi(),w) - rc = h[detName+'_E'].Fill(E/u.MeV,w) - if detName not in hitmult: hitmult[detName] = {-1:0} - if trackID not in hitmult[detName]: hitmult[detName][trackID] = 0 - hitmult[detName][trackID] +=1 - hitmult[detName][-1] +=1 - rc = h[detName+'_id'].Fill(pdgID,w) - rc = h[detName+'_P'].Fill(phit,w) - rc = h[detName+'_LP'].Fill(phit,w) - if not trackID < 0: - r = ROOT.TMath.Sqrt(aTrack.GetStartX()**2+aTrack.GetStartY()**2)/u.m - rc = h['origin'].Fill(aTrack.GetStartZ()/u.m,r,w) - rc = h[detName+'_origin'].Fill(aTrack.GetStartZ()/u.m,r,w) - if abs(pdgID)== 13: rc = h[detName+'_originmu'].Fill(aTrack.GetStartZ()/u.m,r,w) - rc = h['borigin'].Fill(aTrack.GetStartZ()/u.m,r,w) - rc = aTrack.GetMomentum(mom) - rc = h[detName+'_OP'].Fill(mom.Mag()/u.GeV,w) - if trackID > 0: - origin(sTree,trackID) - rc = h['porigin'].Fill(aTrack.GetStartZ()/u.m,ROOT.TMath.Sqrt(aTrack.GetStartX()**2+aTrack.GetStartY()**2)/u.m,w) - rc = h['mu-inter'].Fill(rz_inter[1]/u.m,rz_inter[0]/u.m,w) - for detName in hitmult: - rc = h[detName+'_evmul'].Fill(hitmult[detName][-1],w) - for tr in hitmult[detName]: - rc = h[detName+'_mul'].Fill(hitmult[detName][tr],w) - if output: - ut.writeHists(h,'tmpHists_'+str(pid)+'.root') - output.put('ok') - f.Close() + pid = 1 + for fn in fchain: + if os.path.islink(fn): + rfn = os.path.realpath(fn).split("eos")[1] + fn = ROOT.gSystem.Getenv("EOSSHIP") + "/eos/" + rfn + elif not os.path.isfile(fn): + print("Don't know what to do with", fn) + 1 / 0 + if parallel: + # process files parallel instead of sequential + processes.append(mp.Process(target=executeOneFile, args=(fn, output, pid))) + pid += 1 + else: + processes.append(fn) + # Run processes + n = 0 + for p in processes: + if parallel: + p.start() + n += 1 + else: + executeOneFile(p) + if parallel: + # Exit the completed processes + for p in processes: + p.join() + # clean histos before reading in the new ones + for x in h: + h[x].Reset() + print("now, collect the output") + pid = 1 + for p in processes: + ut.readHists(h, "tmpHists_" + str(pid) + ".root") + pid += 1 + # compactify liquid scintillator + for mu in ["", "_mu", "_muV0"]: + for x in [ + "", + "_E", + "_P", + "_LP", + "_OP", + "_id", + "_mul", + "_evmul", + "_origin", + "_originmu", + ]: + for k in [1, 2, 3, 5]: + first = True + for j in hLiSc[k]: + detName = hLiSc[k][j] + tag = detName + mu + x + newh = detName[0:2] + "LiSc" + mu + x + if tag not in h: + continue + if first: + h[newh] = h[tag].Clone(newh) + h[newh].SetTitle(h[tag].GetTitle().split("_")[0]) + first = False + else: + rc = h[newh].Add(h[tag]) + # compactify muon stations + for mu in ["", "_mu", "_muV0"]: + for x in [ + "", + "_E", + "_P", + "_LP", + "_OP", + "_id", + "_mul", + "_evmul", + "_origin", + "_originmu", + ]: + first = True + for j in hMuon: + detName = hMuon[j] + tag = detName + mu + x + newh = "muondet" + mu + x + if first: + h[newh] = h[tag].Clone(newh) + h[newh].SetTitle(h[tag].GetTitle().split(" ")[0] + " " + newh) + first = False + else: + rc = h[newh].Add(h[tag]) + + # make list of hists with entries + k = 1 + for x in histlistAll: + if histlistAll[x] in h: + histlist[k] = histlistAll[x] + # make cumulative histograms + for c in [ + "", + "_E", + "_P", + "_LP", + "_OP", + "_id", + "_mul", + "_evmul", + "_origin", + "_originmu", + ]: + h[histlist[k] + "_mu" + c].Add(h[histlist[k] + "_muV0" + c]) + h[histlist[k] + c].Add(h[histlist[k] + "_mu" + c]) + h[histlist[k] + c].SetMinimum(0.0) + h[histlist[k] + "_mu" + c].SetMinimum(0.0) + h[histlist[k] + "_muV0" + c].SetMinimum(0.0) + k += 1 + nstations = len(histlist) + makePlots(nstations) + + +def executeOneFile(fn, output=None, pid=None): + f = ROOT.TFile.Open(fn) + sTree = f.cbmsim + nEvents = sTree.GetEntries() + if sTree.GetBranch("GeoTracks"): + sTree.SetBranchStatus("GeoTracks", 0) + sTree.GetEntry(0) + hitContainers = [ + sTree.vetoPoint, + sTree.muonPoint, + sTree.EcalPointLite, + sTree.strawtubesPoint, + sTree.ShipRpcPoint, + sTree.TargetPoint, + ] + ntot = 0 + for n in range(nEvents): + rc = sTree.GetEntry(n) + theMuon = sTree.MCTrack[0] + if sTree.MCTrack.GetEntries() > 1: + w = sTree.MCTrack[1].GetWeight() # also works for neutrinos + else: + print("should not happen with new files", n, fn) + w = sTree.MCTrack[0].GetWeight() # also works for neutrinos + if w == 0: + w = 1.0 + rc = h["weight"].Fill(w) + rc = h["muonP"].Fill(theMuon.GetP() / u.GeV, w) + ntot += 1 + if ntot % 10000 == 0: + print("read event", f.GetName(), n) + hitmult = {} + esum = 0 + for mcp in sTree.MCTrack: + if mcp.GetMotherId() == 0: # mother is original muon + E = mcp.GetEnergy() + if mcp.GetPdgCode() == 11: + rc = h["deltaElec"].Fill(E, w) + esum += E + rc = h["secondaries"].Fill(E, w) + rc = h["prop_deltaElec"].Fill( + esum / sTree.MCTrack[0].GetP(), w + ) # until energy is really made persistent GetEnergy() + for c in hitContainers: + for ahit in c: + if not ahit.GetEnergyLoss() > 0: + continue + detID = ahit.GetDetectorID() + if ahit.GetName() == "strawtubesPoint": + tmp = strawEncoding(detID) + # detName = str(tmp[0]*10000000+tmp[1]*1000000+tmp[2]*100000+tmp[3]*10000) + detName = "strawstation_" + str(tmp[0]) + x = ahit.GetX() + y = ahit.GetY() + E = ahit.GetEnergyLoss() + elif ahit.GetName() == "ecalPoint": + # not needed for lite collection: if abs(ahit.GetPdgCode())==12 or abs(ahit.GetPdgCode())==14 : continue + detName = "Ecal" + ecal.GetCellCoordForPy(detID, pos) + x = pos.X() + y = pos.Y() + E = ahit.GetEnergyLoss() + else: + if detID not in logVols: + detName = c.GetName().replace("Points", "") + if not detName in histlistAll.values(): + print(detID, detName, c.GetName()) + else: + detName = logVols[detID] + x = ahit.GetX() + y = ahit.GetY() + z = ahit.GetZ() + E = ahit.GetEnergyLoss() + if detName not in h: + bookHist(detName) + mu = "" + pdgID = -2 + if "PdgCode" in dir(ahit): + pdgID = ahit.PdgCode() + trackID = ahit.GetTrackID() + phit = -100.0 + mom = ROOT.TVector3() + if not trackID < 0: + aTrack = sTree.MCTrack[trackID] + pdgID = aTrack.GetPdgCode() + aTrack.GetMomentum( + mom + ) # ! this is not momentum of particle at Calorimeter place + phit = mom.Mag() / u.GeV + if abs(pdgID) == 13: + mu = "_mu" + if ahit.GetName().find("ecal") < 0: + rc = ahit.Momentum(mom) + phit = mom.Mag() / u.GeV + else: + for ahit in sTree.EcalPoint: + if ahit.GetTrackID() == trackID: + rc = ahit.Momentum(mom) + phit = mom.Mag() / u.GeV + if phit > 3 and abs(pdgID) == 13: + mu = "_muV0" + detName = detName + mu + if detName.find("LS") < 0: + rc = h[detName].Fill(x / u.m, y / u.m, w) + else: + rc = h[detName].Fill( + ahit.GetZ() / u.m, ROOT.TMath.ATan2(y, x) / ROOT.TMath.Pi(), w + ) + rc = h[detName + "_E"].Fill(E / u.MeV, w) + if detName not in hitmult: + hitmult[detName] = {-1: 0} + if trackID not in hitmult[detName]: + hitmult[detName][trackID] = 0 + hitmult[detName][trackID] += 1 + hitmult[detName][-1] += 1 + rc = h[detName + "_id"].Fill(pdgID, w) + rc = h[detName + "_P"].Fill(phit, w) + rc = h[detName + "_LP"].Fill(phit, w) + if not trackID < 0: + r = ( + ROOT.TMath.Sqrt( + aTrack.GetStartX() ** 2 + aTrack.GetStartY() ** 2 + ) + / u.m + ) + rc = h["origin"].Fill(aTrack.GetStartZ() / u.m, r, w) + rc = h[detName + "_origin"].Fill(aTrack.GetStartZ() / u.m, r, w) + if abs(pdgID) == 13: + rc = h[detName + "_originmu"].Fill( + aTrack.GetStartZ() / u.m, r, w + ) + rc = h["borigin"].Fill(aTrack.GetStartZ() / u.m, r, w) + rc = aTrack.GetMomentum(mom) + rc = h[detName + "_OP"].Fill(mom.Mag() / u.GeV, w) + if trackID > 0: + origin(sTree, trackID) + rc = h["porigin"].Fill( + aTrack.GetStartZ() / u.m, + ROOT.TMath.Sqrt( + aTrack.GetStartX() ** 2 + aTrack.GetStartY() ** 2 + ) + / u.m, + w, + ) + rc = h["mu-inter"].Fill(rz_inter[1] / u.m, rz_inter[0] / u.m, w) + for detName in hitmult: + rc = h[detName + "_evmul"].Fill(hitmult[detName][-1], w) + for tr in hitmult[detName]: + rc = h[detName + "_mul"].Fill(hitmult[detName][tr], w) + if output: + ut.writeHists(h, "tmpHists_" + str(pid) + ".root") + output.put("ok") + f.Close() + + # def makePlots(nstations): - cxcy = {1:[2,1],2:[3,1],3:[2,2],4:[3,2],5:[3,2],6:[3,2],7:[3,3],8:[3,3],9:[3,3],10:[4,3],11:[4,3],12:[4,3],13:[5,3],14:[5,3],15:[5,3]} - ut.bookCanvas(h,key='ResultsI',title='hit occupancies', nx=1100,ny=600*cxcy[nstations][1],cx=cxcy[nstations][0],cy=cxcy[nstations][1]) - ut.bookCanvas(h,key='ResultsImu',title='hit occupancies',nx=1100,ny=600*cxcy[nstations][1],cx=cxcy[nstations][0],cy=cxcy[nstations][1]) - ut.bookCanvas(h,key='ResultsImuV0',title='hit occupancies',nx=1100,ny=600*cxcy[nstations][1],cx=cxcy[nstations][0],cy=cxcy[nstations][1]) - ut.bookCanvas(h,key='ResultsII', title='deposited energies',nx=1100,ny=600*cxcy[nstations][1],cx=cxcy[nstations][0],cy=cxcy[nstations][1]) - ut.bookCanvas(h,key='ResultsIII',title='track info',nx=1100,ny=600*cxcy[nstations][1],cx=cxcy[nstations][0],cy=cxcy[nstations][1]) - ut.bookCanvas(h,key='ResultsIV',title='track info',nx=1100,ny=600*cxcy[nstations][1],cx=cxcy[nstations][0],cy=cxcy[nstations][1]) - ut.bookCanvas(h,key='ResultsV',title='origin info',nx=600,ny=400,cx=1,cy=1) - txt[0] ='occupancy 1sec 5E13pot ' - h['dummy'].Fill(-1) - nSpills = len(prefixes) - for i in histlist: - tc = h['ResultsI'].cd(i) - hn = histlist[i] - if hn not in h: continue - h[hn].SetStats(0) - h[hn].Draw('colz') - txt[i] = '%5.2G'%(h[hn].GetSumOfWeights()/nSpills) - l[i] = ROOT.TLatex().DrawLatexNDC(0.15,0.85,txt[i]) -# - hn = histlist[i]+'_mu' - tc = h['ResultsImu'].cd(i) - h[hn].SetStats(0) - h[hn].Draw('colz') - txt[i+100] = '%5.2G'%(h[hn].GetSumOfWeights()/nSpills) - l[i+100] = ROOT.TLatex().DrawLatexNDC(0.15,0.85,txt[i+100]) -# - hn = histlist[i]+'_muV0' - tc = h['ResultsImuV0'].cd(i) - h[hn].SetStats(0) - h[hn].Draw('colz') - txt[i+200] = '%5.2G'%(h[hn].GetSumOfWeights()/nSpills) - l[i+200] = ROOT.TLatex().DrawLatexNDC(0.15,0.85,txt[i+200]) -# - for i in histlist: - tc = h['ResultsII'].cd(i) - h[histlist[i]+'_E'].Draw('colz') -# - for i in histlist: - tc = h['ResultsIII'].cd(i) - tc.SetLogy(1) - hn = histlist[i] - drawBoth('_P',hn) - hid = h[hn+'_id'] - print('particle statistics for '+histlist[i]) - for k in range(hid.GetNbinsX()): - ncont = hid.GetBinContent(k+1) - pid = hid.GetBinCenter(k+1) - if ncont > 0: - temp = int(abs(pid)+0.5)*int(pid/abs(pid)) - nm = PDG.GetParticle(temp).GetName() - print('%s :%5.2g'%(nm,ncont)) - hid = h[histlist[i]+'_mu_id'] - for k in range(hid.GetNbinsX()): - ncont = hid.GetBinContent(k+1) - pid = hid.GetBinCenter(k+1) - if ncont > 0: - temp = int(abs(pid)+0.5)*int(pid/abs(pid)) - nm = PDG.GetParticle(temp).GetName() - print('%s :%5.2g'%(nm,ncont)) -# - tc = h['ResultsV'].cd(1) - h['origin'].SetStats(0) - h['origin'].Draw('colz') -# - for i in histlist: - tc = h['ResultsIV'].cd(i) - tc.SetLogy(1) - hn = histlist[i] - drawBoth('_OP',hn) - persistency() + cxcy = { + 1: [2, 1], + 2: [3, 1], + 3: [2, 2], + 4: [3, 2], + 5: [3, 2], + 6: [3, 2], + 7: [3, 3], + 8: [3, 3], + 9: [3, 3], + 10: [4, 3], + 11: [4, 3], + 12: [4, 3], + 13: [5, 3], + 14: [5, 3], + 15: [5, 3], + } + ut.bookCanvas( + h, + key="ResultsI", + title="hit occupancies", + nx=1100, + ny=600 * cxcy[nstations][1], + cx=cxcy[nstations][0], + cy=cxcy[nstations][1], + ) + ut.bookCanvas( + h, + key="ResultsImu", + title="hit occupancies", + nx=1100, + ny=600 * cxcy[nstations][1], + cx=cxcy[nstations][0], + cy=cxcy[nstations][1], + ) + ut.bookCanvas( + h, + key="ResultsImuV0", + title="hit occupancies", + nx=1100, + ny=600 * cxcy[nstations][1], + cx=cxcy[nstations][0], + cy=cxcy[nstations][1], + ) + ut.bookCanvas( + h, + key="ResultsII", + title="deposited energies", + nx=1100, + ny=600 * cxcy[nstations][1], + cx=cxcy[nstations][0], + cy=cxcy[nstations][1], + ) + ut.bookCanvas( + h, + key="ResultsIII", + title="track info", + nx=1100, + ny=600 * cxcy[nstations][1], + cx=cxcy[nstations][0], + cy=cxcy[nstations][1], + ) + ut.bookCanvas( + h, + key="ResultsIV", + title="track info", + nx=1100, + ny=600 * cxcy[nstations][1], + cx=cxcy[nstations][0], + cy=cxcy[nstations][1], + ) + ut.bookCanvas(h, key="ResultsV", title="origin info", nx=600, ny=400, cx=1, cy=1) + txt[0] = "occupancy 1sec 5E13pot " + h["dummy"].Fill(-1) + nSpills = len(prefixes) + for i in histlist: + tc = h["ResultsI"].cd(i) + hn = histlist[i] + if hn not in h: + continue + h[hn].SetStats(0) + h[hn].Draw("colz") + txt[i] = "%5.2G" % (h[hn].GetSumOfWeights() / nSpills) + l[i] = ROOT.TLatex().DrawLatexNDC(0.15, 0.85, txt[i]) + # + hn = histlist[i] + "_mu" + tc = h["ResultsImu"].cd(i) + h[hn].SetStats(0) + h[hn].Draw("colz") + txt[i + 100] = "%5.2G" % (h[hn].GetSumOfWeights() / nSpills) + l[i + 100] = ROOT.TLatex().DrawLatexNDC(0.15, 0.85, txt[i + 100]) + # + hn = histlist[i] + "_muV0" + tc = h["ResultsImuV0"].cd(i) + h[hn].SetStats(0) + h[hn].Draw("colz") + txt[i + 200] = "%5.2G" % (h[hn].GetSumOfWeights() / nSpills) + l[i + 200] = ROOT.TLatex().DrawLatexNDC(0.15, 0.85, txt[i + 200]) + # + for i in histlist: + tc = h["ResultsII"].cd(i) + h[histlist[i] + "_E"].Draw("colz") + # + for i in histlist: + tc = h["ResultsIII"].cd(i) + tc.SetLogy(1) + hn = histlist[i] + drawBoth("_P", hn) + hid = h[hn + "_id"] + print("particle statistics for " + histlist[i]) + for k in range(hid.GetNbinsX()): + ncont = hid.GetBinContent(k + 1) + pid = hid.GetBinCenter(k + 1) + if ncont > 0: + temp = int(abs(pid) + 0.5) * int(pid / abs(pid)) + nm = PDG.GetParticle(temp).GetName() + print("%s :%5.2g" % (nm, ncont)) + hid = h[histlist[i] + "_mu_id"] + for k in range(hid.GetNbinsX()): + ncont = hid.GetBinContent(k + 1) + pid = hid.GetBinCenter(k + 1) + if ncont > 0: + temp = int(abs(pid) + 0.5) * int(pid / abs(pid)) + nm = PDG.GetParticle(temp).GetName() + print("%s :%5.2g" % (nm, ncont)) + # + tc = h["ResultsV"].cd(1) + h["origin"].SetStats(0) + h["origin"].Draw("colz") + # + for i in histlist: + tc = h["ResultsIV"].cd(i) + tc.SetLogy(1) + hn = histlist[i] + drawBoth("_OP", hn) + persistency() + + # def AnaEventLoop(): - ntot = 0 - fout = open('rareEvents.txt','w') - for fn in fchainRec: - f = ROOT.TFile(fn) - if not f.FindObjectAny('cbmsim'): - print('skip file ',f.GetName()) - continue - sTree = f.cbmsim - sTree.GetEvent(0) - if sTree.GetBranch("GeoTracks"): sTree.SetBranchStatus("GeoTracks",0) - nEvents = sTree.GetEntries() - for n in range(nEvents): - sTree.GetEntry(n) - if n==0 : print('now at event ',n,f.GetName()) - if sTree.MCTrack.GetEntries() > 1: - wg = sTree.MCTrack[1].GetWeight() # also works for neutrinos - else: - wg = sTree.MCTrack[0].GetWeight() # also works for neutrinos - i = -1 - for atrack in sTree.FitTracks: - i+=1 - fitStatus = atrack.getFitStatus() - if not fitStatus.isFitConverged() : continue - nmeas = atrack.getNumPoints() - chi2 = fitStatus.getChi2()/nmeas - fittedState = atrack.getFittedState() - P = fittedState.getMomMag() - fout.write( 'rare event with track %i, %s, %8.2F \n'%(n,f.GetName(),wg) ) - originOfMuon(fout,n,f.GetName(),nEvents) - fout.write( 'reco %i,%5.3F,%8.2F \n'%(nmeas,chi2,P) ) - mcPartKey = sTree.fitTrack2MC[i] - mcPart = sTree.MCTrack[mcPartKey] - for ahit in sTree.strawtubesPoint: - if ahit.GetTrackID() == mcPartKey: - fout.write( 'P when making hit %i, %8.2F \n'%(ahit.PdgCode(),ROOT.TMath.Sqrt(ahit.GetPx()**2+ahit.GetPy()**2+ahit.GetPz()**2)/u.GeV) ) - break - if not mcPart : continue - Ptruth = mcPart.GetP() - fout.write( 'Ptruth %i %8.2F \n'%(mcPart.GetPdgCode(),Ptruth/u.GeV) ) + ntot = 0 + fout = open("rareEvents.txt", "w") + for fn in fchainRec: + f = ROOT.TFile(fn) + if not f.FindObjectAny("cbmsim"): + print("skip file ", f.GetName()) + continue + sTree = f.cbmsim + sTree.GetEvent(0) + if sTree.GetBranch("GeoTracks"): + sTree.SetBranchStatus("GeoTracks", 0) + nEvents = sTree.GetEntries() + for n in range(nEvents): + sTree.GetEntry(n) + if n == 0: + print("now at event ", n, f.GetName()) + if sTree.MCTrack.GetEntries() > 1: + wg = sTree.MCTrack[1].GetWeight() # also works for neutrinos + else: + wg = sTree.MCTrack[0].GetWeight() # also works for neutrinos + i = -1 + for atrack in sTree.FitTracks: + i += 1 + fitStatus = atrack.getFitStatus() + if not fitStatus.isFitConverged(): + continue + nmeas = atrack.getNumPoints() + chi2 = fitStatus.getChi2() / nmeas + fittedState = atrack.getFittedState() + P = fittedState.getMomMag() + fout.write( + "rare event with track %i, %s, %8.2F \n" % (n, f.GetName(), wg) + ) + originOfMuon(fout, n, f.GetName(), nEvents) + fout.write("reco %i,%5.3F,%8.2F \n" % (nmeas, chi2, P)) + mcPartKey = sTree.fitTrack2MC[i] + mcPart = sTree.MCTrack[mcPartKey] + for ahit in sTree.strawtubesPoint: + if ahit.GetTrackID() == mcPartKey: + fout.write( + "P when making hit %i, %8.2F \n" + % ( + ahit.PdgCode(), + ROOT.TMath.Sqrt( + ahit.GetPx() ** 2 + + ahit.GetPy() ** 2 + + ahit.GetPz() ** 2 + ) + / u.GeV, + ) + ) + break + if not mcPart: + continue + Ptruth = mcPart.GetP() + fout.write("Ptruth %i %8.2F \n" % (mcPart.GetPdgCode(), Ptruth / u.GeV)) + + # def muDISntuple(fn): -# take as input the rare events - fout = ROOT.TFile('muDISVetoCounter.root','recreate') - h['ntuple'] = ROOT.TNtuple("muons","muon flux VetoCounter","id:px:py:pz:x:y:z:w") - f = ROOT.TFile(fn) - sTree = f.cbmsim - nEvents = sTree.GetEntries() - for n in range(nEvents): - sTree.GetEntry(n) - if sTree.MCTrack.GetEntries() > 1: - wg = sTree.MCTrack[1].GetWeight() - else: - wg = sTree.MCTrack[0].GetWeight() - for ahit in sTree.vetoPoint: - detID = ahit.GetDetectorID() - if logVols[detID] != 'VetoTimeDet': continue - pid = ahit.PdgCode() - if abs(pid) != 13: continue - P = ROOT.TMath.Sqrt(ahit.GetPx()**2+ahit.GetPy()**2+ahit.GetPz()**2) - if P>3/u.GeV: - h['ntuple'].Fill(float(pid), float(ahit.GetPx()/u.GeV),float(ahit.GetPy()/u.GeV),float(ahit.GetPz()/u.GeV),\ - float(ahit.GetX()/u.m),float(ahit.GetY()/u.m),float(ahit.GetZ()/u.m),float(wg) ) - fout.cd() - h['ntuple'].Write() + # take as input the rare events + fout = ROOT.TFile("muDISVetoCounter.root", "recreate") + h["ntuple"] = ROOT.TNtuple("muons", "muon flux VetoCounter", "id:px:py:pz:x:y:z:w") + f = ROOT.TFile(fn) + sTree = f.cbmsim + nEvents = sTree.GetEntries() + for n in range(nEvents): + sTree.GetEntry(n) + if sTree.MCTrack.GetEntries() > 1: + wg = sTree.MCTrack[1].GetWeight() + else: + wg = sTree.MCTrack[0].GetWeight() + for ahit in sTree.vetoPoint: + detID = ahit.GetDetectorID() + if logVols[detID] != "VetoTimeDet": + continue + pid = ahit.PdgCode() + if abs(pid) != 13: + continue + P = ROOT.TMath.Sqrt( + ahit.GetPx() ** 2 + ahit.GetPy() ** 2 + ahit.GetPz() ** 2 + ) + if P > 3 / u.GeV: + h["ntuple"].Fill( + float(pid), + float(ahit.GetPx() / u.GeV), + float(ahit.GetPy() / u.GeV), + float(ahit.GetPz() / u.GeV), + float(ahit.GetX() / u.m), + float(ahit.GetY() / u.m), + float(ahit.GetZ() / u.m), + float(wg), + ) + fout.cd() + h["ntuple"].Write() + + def analyzeConcrete(): - h['fout'] = ROOT.TFile('muConcrete.root','recreate') - h['ntuple'] = ROOT.TNtuple("muons","muon flux concrete","id:px:py:pz:x:y:z:w") - for m in ['','mu','V0']: - ut.bookHist(h,'conc_hitz'+m,'concrete hit z '+m,100,-100.,100.) - ut.bookHist(h,'conc_hitzP'+m,'concrete hit z vs P'+m,100,-100.,100.,100,0.,25.) - ut.bookHist(h,'conc_hity'+m,'concrete hit y '+m,100,-15.,15.) - ut.bookHist(h,'conc_p'+m,'concrete hit p '+m,1000,0.,400.) - ut.bookHist(h,'conc_pt'+m,'concrete hit pt '+m,100,0.,20.) - ut.bookHist(h,'conc_hitzy'+m,'concrete hit zy '+m,100,-100.,100.,100,-15.,15.) - top = sGeo.GetTopVolume() - magn = top.GetNode("magyoke_1") - z0 = magn.GetMatrix().GetTranslation()[2]/u.m - for fn in fchain: - f = ROOT.TFile(fn) - if not f.FindObjectAny('cbmsim'): - print('skip file ',f.GetName()) - continue - sTree = f.cbmsim - nEvents = sTree.GetEntries() - ROOT.gROOT.cd() - for n in range(nEvents): - rc=sTree.GetEntry(n) - if sTree.MCTrack.GetEntries() > 1: - wg = sTree.MCTrack[1].GetWeight() - else: - wg = sTree.MCTrack[0].GetWeight() - for ahit in sTree.vetoPoint: - detID = ahit.GetDetectorID() - if logVols[detID] != 'rockD': continue - m='' - pid = ahit.PdgCode() - if abs(pid) == 13: m='mu' - P = ROOT.TMath.Sqrt(ahit.GetPx()**2+ahit.GetPy()**2+ahit.GetPz()**2) - if abs(pid) == 13 and P>3/u.GeV: - m='V0' - h['ntuple'].Fill(float(pid), float(ahit.GetPx()/u.GeV),float(ahit.GetPy()/u.GeV),float(ahit.GetPz()/u.GeV),\ - float(ahit.GetX()/u.m),float(ahit.GetY()/u.m),float(ahit.GetZ()/u.m),float(wg) ) - h['conc_hitz'+m].Fill(ahit.GetZ()/u.m-z0,wg) - h['conc_hity'+m].Fill(ahit.GetY()/u.m,wg) - h['conc_p'+m].Fill(P/u.GeV,wg) - h['conc_hitzP'+m].Fill(ahit.GetZ()/u.m,P/u.GeV,wg) - Pt = ROOT.TMath.Sqrt(ahit.GetPx()**2+ahit.GetPy()**2) - h['conc_pt'+m].Fill(Pt/u.GeV,wg) - h['conc_hitzy'+m].Fill(ahit.GetZ()/u.m-z0,ahit.GetY()/u.m,wg) - # - #start = [ahit.GetX()/u.m,ahit.GetY()/u.m,ahit.GetZ()/u.m] - #direc = [-ahit.GetPx()/P,-ahit.GetPy()/P,-ahit.GetPz()/P] - #t = - start[0]/direc[0] - - ut.bookCanvas(h,key='ResultsV0',title='muons hitting concrete, p>3GeV',nx=1000,ny=600,cx=2,cy=2) - ut.bookCanvas(h,key='Resultsmu',title='muons hitting concrete',nx=1000,ny=600,cx=2,cy=2) - ut.bookCanvas(h,key='Results',title='hitting concrete',nx=1000,ny=600,cx=2,cy=2) - for m in ['','mu','V0']: - tc = h['Results'+m].cd(1) - h['conc_hity'+m].Draw() - tc = h['Results'+m].cd(2) - h['conc_hitz'+m].Draw() - tc = h['Results'+m].cd(3) - tc.SetLogy(1) - h['conc_pt'+m].Draw() - tc = h['Results'+m].cd(4) - tc.SetLogy(1) - h['conc_p'+m].Draw() - h['fout'].cd() - h['ntuple'].Write() - -def rareEventEmulsion(fname = 'rareEmulsion.txt'): - ntot = 0 - fout = open(fname,'w') - for fn in fchainRec: - f = ROOT.TFile(fn) - if not f.FindObjectAny('cbmsim'): - print('skip file ',f.GetName()) - continue - sTree = f.cbmsim - sTree.GetEvent(0) - if sTree.GetBranch("GeoTracks"): sTree.SetBranchStatus("GeoTracks",0) - nEvents = sTree.GetEntries() - for n in range(nEvents): - sTree.GetEntry(n) - if n==0 : print('now at event ',n,f.GetName()) - for ahit in sTree.vetoPoint: - detID = ahit.GetDetectorID() - if logVols[detID] != 'Emulsion': continue - x = ahit.GetX() - y = ahit.GetY() - z = ahit.GetZ() - if sTree.MCTrack.GetEntries() > 1: - wg = sTree.MCTrack[1].GetWeight() # also works for neutrinos - else: - wg = sTree.MCTrack[0].GetWeight() # also works for neutrinos - fout.write( 'rare emulsion hit %i, %s, %8.3F, %i \n'%(n,f.GetName(),wg,ahit.PdgCode() )) - if ahit.GetPz()/u.GeV > 1. : - fout.write( 'V,P when making hit %8.3F,%8.3F,%8.3F %8.3F,%8.3F,%8.3F (GeV) \n'%(\ - ahit.GetX()/u.m,ahit.GetY()/u.m,ahit.GetZ()/u.m, \ - ahit.GetPx()/u.GeV,ahit.GetPy()/u.GeV,ahit.GetPz()/u.GeV ) ) - else: - fout.write( 'V,P when making hit %8.3F,%8.3F,%8.3F %8.3F,%8.3F,%8.3F (MeV)\n'%(\ - ahit.GetX()/u.m,ahit.GetY()/u.m,ahit.GetZ()/u.m, \ - ahit.GetPx()/u.MeV,ahit.GetPy()/u.MeV,ahit.GetPz()/u.MeV ) ) - originOfMuon(fout,n,f.GetName(),nEvents) + h["fout"] = ROOT.TFile("muConcrete.root", "recreate") + h["ntuple"] = ROOT.TNtuple("muons", "muon flux concrete", "id:px:py:pz:x:y:z:w") + for m in ["", "mu", "V0"]: + ut.bookHist(h, "conc_hitz" + m, "concrete hit z " + m, 100, -100.0, 100.0) + ut.bookHist( + h, + "conc_hitzP" + m, + "concrete hit z vs P" + m, + 100, + -100.0, + 100.0, + 100, + 0.0, + 25.0, + ) + ut.bookHist(h, "conc_hity" + m, "concrete hit y " + m, 100, -15.0, 15.0) + ut.bookHist(h, "conc_p" + m, "concrete hit p " + m, 1000, 0.0, 400.0) + ut.bookHist(h, "conc_pt" + m, "concrete hit pt " + m, 100, 0.0, 20.0) + ut.bookHist( + h, + "conc_hitzy" + m, + "concrete hit zy " + m, + 100, + -100.0, + 100.0, + 100, + -15.0, + 15.0, + ) + top = sGeo.GetTopVolume() + magn = top.GetNode("magyoke_1") + z0 = magn.GetMatrix().GetTranslation()[2] / u.m + for fn in fchain: + f = ROOT.TFile(fn) + if not f.FindObjectAny("cbmsim"): + print("skip file ", f.GetName()) + continue + sTree = f.cbmsim + nEvents = sTree.GetEntries() + ROOT.gROOT.cd() + for n in range(nEvents): + rc = sTree.GetEntry(n) + if sTree.MCTrack.GetEntries() > 1: + wg = sTree.MCTrack[1].GetWeight() + else: + wg = sTree.MCTrack[0].GetWeight() + for ahit in sTree.vetoPoint: + detID = ahit.GetDetectorID() + if logVols[detID] != "rockD": + continue + m = "" + pid = ahit.PdgCode() + if abs(pid) == 13: + m = "mu" + P = ROOT.TMath.Sqrt( + ahit.GetPx() ** 2 + ahit.GetPy() ** 2 + ahit.GetPz() ** 2 + ) + if abs(pid) == 13 and P > 3 / u.GeV: + m = "V0" + h["ntuple"].Fill( + float(pid), + float(ahit.GetPx() / u.GeV), + float(ahit.GetPy() / u.GeV), + float(ahit.GetPz() / u.GeV), + float(ahit.GetX() / u.m), + float(ahit.GetY() / u.m), + float(ahit.GetZ() / u.m), + float(wg), + ) + h["conc_hitz" + m].Fill(ahit.GetZ() / u.m - z0, wg) + h["conc_hity" + m].Fill(ahit.GetY() / u.m, wg) + h["conc_p" + m].Fill(P / u.GeV, wg) + h["conc_hitzP" + m].Fill(ahit.GetZ() / u.m, P / u.GeV, wg) + Pt = ROOT.TMath.Sqrt(ahit.GetPx() ** 2 + ahit.GetPy() ** 2) + h["conc_pt" + m].Fill(Pt / u.GeV, wg) + h["conc_hitzy" + m].Fill(ahit.GetZ() / u.m - z0, ahit.GetY() / u.m, wg) + # + # start = [ahit.GetX()/u.m,ahit.GetY()/u.m,ahit.GetZ()/u.m] + # direc = [-ahit.GetPx()/P,-ahit.GetPy()/P,-ahit.GetPz()/P] + # t = - start[0]/direc[0] + + ut.bookCanvas( + h, + key="ResultsV0", + title="muons hitting concrete, p>3GeV", + nx=1000, + ny=600, + cx=2, + cy=2, + ) + ut.bookCanvas( + h, key="Resultsmu", title="muons hitting concrete", nx=1000, ny=600, cx=2, cy=2 + ) + ut.bookCanvas( + h, key="Results", title="hitting concrete", nx=1000, ny=600, cx=2, cy=2 + ) + for m in ["", "mu", "V0"]: + tc = h["Results" + m].cd(1) + h["conc_hity" + m].Draw() + tc = h["Results" + m].cd(2) + h["conc_hitz" + m].Draw() + tc = h["Results" + m].cd(3) + tc.SetLogy(1) + h["conc_pt" + m].Draw() + tc = h["Results" + m].cd(4) + tc.SetLogy(1) + h["conc_p" + m].Draw() + h["fout"].cd() + h["ntuple"].Write() + + +def rareEventEmulsion(fname="rareEmulsion.txt"): + ntot = 0 + fout = open(fname, "w") + for fn in fchainRec: + f = ROOT.TFile(fn) + if not f.FindObjectAny("cbmsim"): + print("skip file ", f.GetName()) + continue + sTree = f.cbmsim + sTree.GetEvent(0) + if sTree.GetBranch("GeoTracks"): + sTree.SetBranchStatus("GeoTracks", 0) + nEvents = sTree.GetEntries() + for n in range(nEvents): + sTree.GetEntry(n) + if n == 0: + print("now at event ", n, f.GetName()) + for ahit in sTree.vetoPoint: + detID = ahit.GetDetectorID() + if logVols[detID] != "Emulsion": + continue + x = ahit.GetX() + y = ahit.GetY() + z = ahit.GetZ() + if sTree.MCTrack.GetEntries() > 1: + wg = sTree.MCTrack[1].GetWeight() # also works for neutrinos + else: + wg = sTree.MCTrack[0].GetWeight() # also works for neutrinos + fout.write( + "rare emulsion hit %i, %s, %8.3F, %i \n" + % (n, f.GetName(), wg, ahit.PdgCode()) + ) + if ahit.GetPz() / u.GeV > 1.0: + fout.write( + "V,P when making hit %8.3F,%8.3F,%8.3F %8.3F,%8.3F,%8.3F (GeV) \n" + % ( + ahit.GetX() / u.m, + ahit.GetY() / u.m, + ahit.GetZ() / u.m, + ahit.GetPx() / u.GeV, + ahit.GetPy() / u.GeV, + ahit.GetPz() / u.GeV, + ) + ) + else: + fout.write( + "V,P when making hit %8.3F,%8.3F,%8.3F %8.3F,%8.3F,%8.3F (MeV)\n" + % ( + ahit.GetX() / u.m, + ahit.GetY() / u.m, + ahit.GetZ() / u.m, + ahit.GetPx() / u.MeV, + ahit.GetPy() / u.MeV, + ahit.GetPz() / u.MeV, + ) + ) + originOfMuon(fout, n, f.GetName(), nEvents) + + # -def extractRareEvents(single = None): - for fn in fchainRec: - if single : - if fn.find(str(single)) < 0 : continue - f = ROOT.TFile(fn) - if not f.FindObjectAny('cbmsim'): - print('skip file ',f.GetName()) - continue - sTree = f.cbmsim - nEvents = sTree.GetEntries() - raref = ROOT.TFile(fn.replace(".root","_rare.root"),"recreate") - newTree = sTree.CloneTree(0) - for n in range(nEvents): - sTree.GetEntry(n) - if n==0 : print('now at event ',n,f.GetName()) -# count fitted tracks which have converged and nDF>20: - n = 0 - for fT in sTree.FitTracks: - fst = fT.getFitStatus() - if not fst.isFitConverged(): continue - if fst.getNdf() < 20: continue - n+=1 - if n > 0: - rc = newTree.Fill() - print('filled newTree',rc) - sTree.Clear() - newTree.AutoSave() - print(' --> events saved:',newTree.GetEntries()) - f.Close() - raref.Close() +def extractRareEvents(single=None): + for fn in fchainRec: + if single: + if fn.find(str(single)) < 0: + continue + f = ROOT.TFile(fn) + if not f.FindObjectAny("cbmsim"): + print("skip file ", f.GetName()) + continue + sTree = f.cbmsim + nEvents = sTree.GetEntries() + raref = ROOT.TFile(fn.replace(".root", "_rare.root"), "recreate") + newTree = sTree.CloneTree(0) + for n in range(nEvents): + sTree.GetEntry(n) + if n == 0: + print("now at event ", n, f.GetName()) + # count fitted tracks which have converged and nDF>20: + n = 0 + for fT in sTree.FitTracks: + fst = fT.getFitStatus() + if not fst.isFitConverged(): + continue + if fst.getNdf() < 20: + continue + n += 1 + if n > 0: + rc = newTree.Fill() + print("filled newTree", rc) + sTree.Clear() + newTree.AutoSave() + print(" --> events saved:", newTree.GetEntries()) + f.Close() + raref.Close() + + # -def extractMuCloseByEvents(single = None): - mom = ROOT.TVector3() - pos = ROOT.TVector3() - golmx = top.GetNode("volGoliath_1").GetMatrix() - zGol = golmx.GetTranslation()[2] - for fn in fchainRec: - if single : - if fn.find(str(single)) < 0 : continue - f = ROOT.TFile(fn) - if not f.FindObjectAny('cbmsim'): - print('skip file ',f.GetName()) - continue - sTree = f.cbmsim - nEvents = sTree.GetEntries() - raref = ROOT.TFile(fn.replace(".root","_clby.root"),"recreate") - newTree = sTree.CloneTree(0) - for n in range(nEvents): - sTree.GetEntry(n) - if n==0 : print('now at event ',n,f.GetName()) -# look for muons p>3 hitting something - n = 0 - for c in [sTree.vetoPoint,sTree.strawtubesPoint,sTree.ShipRpcPoint]: - for ahit in c: - if abs(ahit.PdgCode())!=13: continue - ahit.Momentum(mom) - if mom.Mag()<3. : continue - ahit.Position(pos) - if pos.z() 0: - rc = newTree.Fill() - # print 'filled newTree',rc - sTree.Clear() - newTree.AutoSave() - print(' --> events saved:',newTree.GetEntries()) - f.Close() - raref.Close() +def extractMuCloseByEvents(single=None): + mom = ROOT.TVector3() + pos = ROOT.TVector3() + golmx = top.GetNode("volGoliath_1").GetMatrix() + zGol = golmx.GetTranslation()[2] + for fn in fchainRec: + if single: + if fn.find(str(single)) < 0: + continue + f = ROOT.TFile(fn) + if not f.FindObjectAny("cbmsim"): + print("skip file ", f.GetName()) + continue + sTree = f.cbmsim + nEvents = sTree.GetEntries() + raref = ROOT.TFile(fn.replace(".root", "_clby.root"), "recreate") + newTree = sTree.CloneTree(0) + for n in range(nEvents): + sTree.GetEntry(n) + if n == 0: + print("now at event ", n, f.GetName()) + # look for muons p>3 hitting something + n = 0 + for c in [sTree.vetoPoint, sTree.strawtubesPoint, sTree.ShipRpcPoint]: + for ahit in c: + if abs(ahit.PdgCode()) != 13: + continue + ahit.Momentum(mom) + if mom.Mag() < 3.0: + continue + ahit.Position(pos) + if pos.z() < zGol: + continue + n += 1 + if n > 0: + rc = newTree.Fill() + # print 'filled newTree',rc + sTree.Clear() + newTree.AutoSave() + print(" --> events saved:", newTree.GetEntries()) + f.Close() + raref.Close() + + # -def MergeRareEvents(runs=['61','62']): - for prefix in runs: - cmd = '$ROOTSYS/bin/hadd rareEvents_'+prefix+'.root -f ' - for fn in fchainRec: - if fn.find('muon'+prefix)<0 : continue - fr = fn.replace(".root","_rare.root") - cmd = cmd + ' '+ fr - os.system( cmd ) +def MergeRareEvents(runs=["61", "62"]): + for prefix in runs: + cmd = "$ROOTSYS/bin/hadd rareEvents_" + prefix + ".root -f " + for fn in fchainRec: + if fn.find("muon" + prefix) < 0: + continue + fr = fn.replace(".root", "_rare.root") + cmd = cmd + " " + fr + os.system(cmd) + # def persistency(): - printAndCopy(prefix) - ut.writeHists(h,prefix+".root",plusCanvas=True) + printAndCopy(prefix) + ut.writeHists(h, prefix + ".root", plusCanvas=True) + def reDraw(fn): - if fn.find('root')<0: fn=fn+'.root' - if 'tc' not in h: h['tc'] = ROOT.TFile(fn) - for x in ['ResultsI','ResultsII','ResultsImu','ResultsImuV0','ResultsIII','ResultsIV','ResultsV']: - h[x]=h['tc'].FindObjectAny(x) - h[x].Draw() + if fn.find("root") < 0: + fn = fn + ".root" + if "tc" not in h: + h["tc"] = ROOT.TFile(fn) + for x in [ + "ResultsI", + "ResultsII", + "ResultsImu", + "ResultsImuV0", + "ResultsIII", + "ResultsIV", + "ResultsV", + ]: + h[x] = h["tc"].FindObjectAny(x) + h[x].Draw() + + def printAndCopy(prefix=None): - if not prefix: prefix = (h['tc'].GetName()).replace('.root','') - for x in ['ResultsI','ResultsII','ResultsImu','ResultsImuV0','ResultsIII','ResultsIV','ResultsV']: - h[x].Update() - if not prefix in os.listdir('.'): os.mkdir(prefix) - os.chdir(prefix) - h['ResultsI'].Print(prefix+'Back_occ.png') - h['ResultsII'].Print(prefix+'Back_depE.png') - h['ResultsImu'].Print(prefix+'muBack_occ.png') - h['ResultsImuV0'].Print(prefix+'muV0Back_occ.png') - h['ResultsIII'].Print(prefix+'Back_P.png') - h['ResultsIV'].Print(prefix+'Back_OP.png') - h['ResultsV'].Print(prefix+'origin.png') - os.chdir("../") - - -def drawBoth(tag,hn): - n1 = h[hn+'_mu'+tag].GetMaximum() - n2 = h[hn+tag].GetMaximum() - if n1>n2: h[hn+tag].SetMaximum(n1) - h[hn+'_mu'+tag].SetLineColor(4) - h[hn+tag].SetLineColor(3) - h[hn+'_mu'+tag].Draw() - h[hn+tag].Draw('same') + if not prefix: + prefix = (h["tc"].GetName()).replace(".root", "") + for x in [ + "ResultsI", + "ResultsII", + "ResultsImu", + "ResultsImuV0", + "ResultsIII", + "ResultsIV", + "ResultsV", + ]: + h[x].Update() + if not prefix in os.listdir("."): + os.mkdir(prefix) + os.chdir(prefix) + h["ResultsI"].Print(prefix + "Back_occ.png") + h["ResultsII"].Print(prefix + "Back_depE.png") + h["ResultsImu"].Print(prefix + "muBack_occ.png") + h["ResultsImuV0"].Print(prefix + "muV0Back_occ.png") + h["ResultsIII"].Print(prefix + "Back_P.png") + h["ResultsIV"].Print(prefix + "Back_OP.png") + h["ResultsV"].Print(prefix + "origin.png") + os.chdir("../") + + +def drawBoth(tag, hn): + n1 = h[hn + "_mu" + tag].GetMaximum() + n2 = h[hn + tag].GetMaximum() + if n1 > n2: + h[hn + tag].SetMaximum(n1) + h[hn + "_mu" + tag].SetLineColor(4) + h[hn + tag].SetLineColor(3) + h[hn + "_mu" + tag].Draw() + h[hn + tag].Draw("same") def debugGeoTracks(): - for i in range(sTree.GetEntries()): - sTree.GetEntry(i) - n = 0 - for gt in sTree.GeoTracks: - print(i,n,gt.GetFirstPoint()[2],gt.GetLastPoint()[2],gt.GetParticle().GetPdgCode(),gt.GetParticle().P()) - n+=1 + for i in range(sTree.GetEntries()): + sTree.GetEntry(i) + n = 0 + for gt in sTree.GeoTracks: + print( + i, + n, + gt.GetFirstPoint()[2], + gt.GetLastPoint()[2], + gt.GetParticle().GetPdgCode(), + gt.GetParticle().P(), + ) + n += 1 + + def eventsWithStrawPoints(i): - sTree = fchain[i].cbmsim - mom = ROOT.TVector3() - for i in range(sTree.GetEntries()): - sTree.GetEntry(i) - nS = sTree.strawtubesPoint.GetEntries() - if nS>0: - mu = sTree.MCTrack[0] - mu.GetMomentum(mom) - print(i,nS) - mom.Print() - sp = sTree.strawtubesPoint[(max(0,nS-3))] - sp.Momentum(mom) - mom.Print() - print('-----------------------') + sTree = fchain[i].cbmsim + mom = ROOT.TVector3() + for i in range(sTree.GetEntries()): + sTree.GetEntry(i) + nS = sTree.strawtubesPoint.GetEntries() + if nS > 0: + mu = sTree.MCTrack[0] + mu.GetMomentum(mom) + print(i, nS) + mom.Print() + sp = sTree.strawtubesPoint[(max(0, nS - 3))] + sp.Momentum(mom) + mom.Print() + print("-----------------------") + + def eventsWithEntryPoints(i): - sTree = fchain[i].cbmsim - mom = ROOT.TVector3() - for i in range(sTree.GetEntries()): - sTree.GetEntry(i) - np = 0 - for vp in sTree.vetoPoint: - detName = logVols[vp. GetDetectorID()] - if detName== "VetoTimeDet": np+=0 #?? - vp.Momentum(mom) - print(i,detName,vp.PdgCode()) - mom.Print() - print('-----------------------') + sTree = fchain[i].cbmsim + mom = ROOT.TVector3() + for i in range(sTree.GetEntries()): + sTree.GetEntry(i) + np = 0 + for vp in sTree.vetoPoint: + detName = logVols[vp.GetDetectorID()] + if detName == "VetoTimeDet": + np += 0 # ?? + vp.Momentum(mom) + print(i, detName, vp.PdgCode()) + mom.Print() + print("-----------------------") + + def depEnergy(): - for n in range(sTree.GetEntries()): - rc = sTree.GetEntry(n) - for ahit in sTree.strawtubesPoint: - dE = ahit.GetEnergyLoss()/u.keV - rc = ahit.Momentum(mom) - pa = PDG.GetParticle(ahit.PdgCode()) - mpa = pa.Mass() - E = ROOT.TMath.Sqrt(mom.Mag2()+mpa**2) - ekin = E-mpa - rc = h['dE'].Fill(dE,ekin/u.MeV) - h['dE'].SetXTitle('keV') - h['dE'].SetYTitle('MeV') - -def originOfMuon(fout,n,fn,nEvents): - # from fn extract Yandex or CERN/cracow - ncpu = 9 - x = fn.find('/') - ni = int(fn[x-1:x])-1 - if nEvents < 100000: - fm = "$SHIPSOFT/data/pythia8_Geant4_onlyMuons.root" - else: - fm = "$SHIPSOFT/data/pythia8_Geant4_Yandex_onlyMuons.root" - fmuon = ROOT.TFile(fm) - ntupl = fmuon.Get("pythia8-Geant4") - ntot = ntupl.GetEntries() - n3 = int(ntot/ncpu) - N = n3*ni+n - ntupl.GetEvent(N) - P = ROOT.TMath.Sqrt(ntupl.pz*ntupl.pz+ntupl.py*ntupl.py+ntupl.px*ntupl.px) - fout.write('original muon %i, %i, %8.2F \n'%(ntupl.parentid,ntupl.pythiaid,P) ) - fmuon.Close() + for n in range(sTree.GetEntries()): + rc = sTree.GetEntry(n) + for ahit in sTree.strawtubesPoint: + dE = ahit.GetEnergyLoss() / u.keV + rc = ahit.Momentum(mom) + pa = PDG.GetParticle(ahit.PdgCode()) + mpa = pa.Mass() + E = ROOT.TMath.Sqrt(mom.Mag2() + mpa**2) + ekin = E - mpa + rc = h["dE"].Fill(dE, ekin / u.MeV) + h["dE"].SetXTitle("keV") + h["dE"].SetYTitle("MeV") + + +def originOfMuon(fout, n, fn, nEvents): + # from fn extract Yandex or CERN/cracow + ncpu = 9 + x = fn.find("/") + ni = int(fn[x - 1 : x]) - 1 + if nEvents < 100000: + fm = "$SHIPSOFT/data/pythia8_Geant4_onlyMuons.root" + else: + fm = "$SHIPSOFT/data/pythia8_Geant4_Yandex_onlyMuons.root" + fmuon = ROOT.TFile(fm) + ntupl = fmuon.Get("pythia8-Geant4") + ntot = ntupl.GetEntries() + n3 = int(ntot / ncpu) + N = n3 * ni + n + ntupl.GetEvent(N) + P = ROOT.TMath.Sqrt(ntupl.pz * ntupl.pz + ntupl.py * ntupl.py + ntupl.px * ntupl.px) + fout.write("original muon %i, %i, %8.2F \n" % (ntupl.parentid, ntupl.pythiaid, P)) + fmuon.Close() + + # # BigEventLoop() # makePlots() # AnaEventLoop() + # ShipAna def pers(): - xdisk = '/media/Work/HNL/' - for x in h: - if type(h[x])==type(ROOT.TCanvas()): - h[x].Update() - tn = h[x].GetName()+'.png' - h[x].Print(tn) - rpath = os.path.abspath('.').split('/HNL/')[1] - lp = rpath.split('/') - prefix = xdisk - for i in range(len(lp)): - if not lp[i] in os.listdir(prefix): os.system('mkdir '+prefix+'/'+lp[i]) - prefix = prefix+'/'+lp[i] - os.system('cp '+tn+ ' '+xdisk+rpath) + xdisk = "/media/Work/HNL/" + for x in h: + if type(h[x]) == type(ROOT.TCanvas()): + h[x].Update() + tn = h[x].GetName() + ".png" + h[x].Print(tn) + rpath = os.path.abspath(".").split("/HNL/")[1] + lp = rpath.split("/") + prefix = xdisk + for i in range(len(lp)): + if not lp[i] in os.listdir(prefix): + os.system("mkdir " + prefix + "/" + lp[i]) + prefix = prefix + "/" + lp[i] + os.system("cp " + tn + " " + xdisk + rpath) + from operator import itemgetter -def makeNicePrintout(x=['rareEvents_61-62.txt','rareEvents_71-72.txt']): - result = [] - cor = 1. - for fn in x: - f = open(fn) - recTrack = None - if fn=="rareEvents_81-102.txt" : cor = 30. - for lx in f.readlines(): - l = lx.replace('\n','') - if not l.find('rare event')<0: - if recTrack: result.append(recTrack) - tmp = l.split(',') - w = tmp[2].replace(' ','') - ff = tmp[1].split('/')[0].replace(' ','') - recTrack = {'w':w,'file':ff} - elif not l.find('original')<0: - tmp = l.split(',') - recTrack['origin'] = tmp[0].split(' ')[2] - recTrack['pytiaid'] = tmp[1].replace(' ','') - recTrack['o-mom'] = tmp[2].replace(' ','') - elif not l.find('reco ')<0: - tmp = l.split(',') - recTrack['nmeas'] = tmp[0].split(' ')[1] - recTrack['chi2'] = tmp[1] - recTrack['p_rec'] = tmp[2].replace(' ','') - elif not l.find('making')<0: - tmp = l.split(',') - recTrack['p_hit'] = tmp[1].replace(' ','') - recTrack['fp_hit'] = float(tmp[1].replace(' ','')) - elif not l.find('Ptruth')<0: - tmp = l.split(' ') - recTrack['id_hit'] = tmp[1].replace(' ','') - # print a table - print('%4s %8s %8s %4s %8s %8s %8s %8s %8s %8s '%('nr','origin','pythiaID','ID','p_orig','p_hit','chi2','weight','file','cor w')) -# sort according to p_hit - tmp = sorted(result, key=itemgetter('fp_hit')) - muonrate1 = 0 - muonrate2 = 0 - muonrate3 = 0 - for i in range(len(tmp)): - tr = tmp[i] - corw = float(tr['w'])/cor - if float(tr['p_hit'])>1:muonrate1+=corw - if float(tr['p_hit'])>2:muonrate2+=corw - if float(tr['p_hit'])>3:muonrate3+=corw - print('%4i %8s %8s %4s %8s %8s %8s %8s %8s %8s '%( i,tr['origin'],tr['pytiaid'],tr['id_hit'],tr['o-mom'],tr['p_hit'],tr['chi2'],tr['w'],tr['file'],corw)) - print("guestimate for muonrate above 1GeV = ",muonrate1) - print("guestimate for muonrate above 2GeV = ",muonrate2) - print("guestimate for muonrate above 3GeV = ",muonrate3) -#guestimate for muonrate above 1GeV = 56025.4793333 -#guestimate for muonrate above 2GeV = 25584.9546667 -#guestimate for muonrate above 3GeV = 14792.8113333 - return tmp + + +def makeNicePrintout(x=["rareEvents_61-62.txt", "rareEvents_71-72.txt"]): + result = [] + cor = 1.0 + for fn in x: + f = open(fn) + recTrack = None + if fn == "rareEvents_81-102.txt": + cor = 30.0 + for lx in f.readlines(): + l = lx.replace("\n", "") + if not l.find("rare event") < 0: + if recTrack: + result.append(recTrack) + tmp = l.split(",") + w = tmp[2].replace(" ", "") + ff = tmp[1].split("/")[0].replace(" ", "") + recTrack = {"w": w, "file": ff} + elif not l.find("original") < 0: + tmp = l.split(",") + recTrack["origin"] = tmp[0].split(" ")[2] + recTrack["pytiaid"] = tmp[1].replace(" ", "") + recTrack["o-mom"] = tmp[2].replace(" ", "") + elif not l.find("reco ") < 0: + tmp = l.split(",") + recTrack["nmeas"] = tmp[0].split(" ")[1] + recTrack["chi2"] = tmp[1] + recTrack["p_rec"] = tmp[2].replace(" ", "") + elif not l.find("making") < 0: + tmp = l.split(",") + recTrack["p_hit"] = tmp[1].replace(" ", "") + recTrack["fp_hit"] = float(tmp[1].replace(" ", "")) + elif not l.find("Ptruth") < 0: + tmp = l.split(" ") + recTrack["id_hit"] = tmp[1].replace(" ", "") + # print a table + print( + "%4s %8s %8s %4s %8s %8s %8s %8s %8s %8s " + % ( + "nr", + "origin", + "pythiaID", + "ID", + "p_orig", + "p_hit", + "chi2", + "weight", + "file", + "cor w", + ) + ) + # sort according to p_hit + tmp = sorted(result, key=itemgetter("fp_hit")) + muonrate1 = 0 + muonrate2 = 0 + muonrate3 = 0 + for i in range(len(tmp)): + tr = tmp[i] + corw = float(tr["w"]) / cor + if float(tr["p_hit"]) > 1: + muonrate1 += corw + if float(tr["p_hit"]) > 2: + muonrate2 += corw + if float(tr["p_hit"]) > 3: + muonrate3 += corw + print( + "%4i %8s %8s %4s %8s %8s %8s %8s %8s %8s " + % ( + i, + tr["origin"], + tr["pytiaid"], + tr["id_hit"], + tr["o-mom"], + tr["p_hit"], + tr["chi2"], + tr["w"], + tr["file"], + corw, + ) + ) + print("guestimate for muonrate above 1GeV = ", muonrate1) + print("guestimate for muonrate above 2GeV = ", muonrate2) + print("guestimate for muonrate above 3GeV = ", muonrate3) + # guestimate for muonrate above 1GeV = 56025.4793333 + # guestimate for muonrate above 2GeV = 25584.9546667 + # guestimate for muonrate above 3GeV = 14792.8113333 + return tmp + + # def readAndMergeHistos(prods): - for p in prods: - x=p - if p.find('.root')<0: x=p+'.root' - ut.readHists(h,x) -# make list of hists with entries - k = 1 - for x in histlistAll: - if histlistAll[x] in h: - histlist[k]=histlistAll[x] - k+=1 - nstations = len(histlist) - print("make plots for ",nstations) - makePlots(nstations) - printAndCopy(prods[0].replace('.root','')) + for p in prods: + x = p + if p.find(".root") < 0: + x = p + ".root" + ut.readHists(h, x) + # make list of hists with entries + k = 1 + for x in histlistAll: + if histlistAll[x] in h: + histlist[k] = histlistAll[x] + k += 1 + nstations = len(histlist) + print("make plots for ", nstations) + makePlots(nstations) + printAndCopy(prods[0].replace(".root", "")) + # python -i $HNL/ana_ShipMuon.py 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 # python -i $HNL/ana_ShipMuon.py 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 diff --git a/muonShieldOptimization/compactingBackgroundProduction.py b/muonShieldOptimization/compactingBackgroundProduction.py index 5e1e5dbe0f..1aa210801b 100644 --- a/muonShieldOptimization/compactingBackgroundProduction.py +++ b/muonShieldOptimization/compactingBackgroundProduction.py @@ -1,7 +1,14 @@ -import os,ROOT,sys,subprocess,pickle,time,datetime +import datetime +import os +import pickle +import subprocess +import sys +import time + +import ROOT import rootUtils as ut -pdg = ROOT.TDatabasePDG() +pdg = ROOT.TDatabasePDG() charm = False # functions, PoT: statistics per file @@ -17,339 +24,437 @@ # final statistics: 65041000000 pot -> weight 768.75 -prod = '1GeV' -globalPath="/eos/experiment/ship/skygrid/background-prod-2018-1gev/" -fnames = 'pythia8_Geant4_1_1.0.root' -ecut = '1.0' - -def GetGoodAndBadRuns(startDate,endDate): -# find bad runs, try to recover - goodRuns=[] - badRuns=[] - fileName = "pythia8_Geant4_1_"+ecut+".root" - os.system("ls -l --full-time "+globalPath+" >inventory.lst") - f=open("inventory.lst") - runs = f.readlines() - f.close() - N=0 - for r in runs: - tmp = r.split(' ') - if len(tmp) != 9: - print("wrong format",tmp) - continue - date = tmp[5].split('-') - time = tmp[6].split(':') - fileDate = datetime.datetime(int(date[0]),int(date[1]),int(date[2]),int(time[0]),int(time[1]),int(time[2].split('.')[0])) - if fileDate < startDate or fileDate>endDate: continue - theRun = int(tmp[8].replace('\n','')) - test = os.listdir(globalPath+str(theRun)) - if len(test)<2:continue - N+=1 - rc = os.system('grep -q "Number of events produced with activity after hadron absorber" '+globalPath+str(theRun)+"/stdout") - if rc!=0: - badRuns.append(theRun) - continue - for x in test: - if x.find('run_fixedTarget')>0: - test2 = os.listdir(globalPath+str(theRun)+'/'+x) - bad = True - tmpF = False - f = globalPath+str(theRun)+"/"+x+"/"+fileName - if fnames+"tmp" in test2: - tmpF = True - f = f+"tmp" - elif fnames in test2: - f = f - else: - badRuns.append(theRun) - continue - try: - t = ROOT.TFile.Open(os.environ["EOSSHIP"]+f) - if not t: - badRuns.append(theRun) - continue - if N%1000 == 0: print(N,t.GetName()) - if t.ReadKeys()==0: - t.Close() - badRuns.append(theRun) - continue - if t.FindObjectAny('cbmsim'): - bad = False - goodRuns.append(f) - t.Close() - except: - badRuns.append(theRun) - continue - return goodRuns,badRuns - -def addRuns(goodRuns,Nstart=0): - N=0 - while(1>0): - cmd = "" - for i in range(N,min(N+1000,len(goodRuns))): - cmd += " $EOSSHIP"+goodRuns[i] - tmpFile = "pythia8_Geant4_"+ecut+"_c"+str(N+Nstart)+".root" - rc = os.system("hadd -j 10 -O "+tmpFile + " " +cmd) - if rc != 0: - print("hadd failed, stop",N) - return - rc = os.system("xrdcp "+tmpFile+" $EOSSHIP/eos/experiment/ship/data/Mbias/background-prod-2018/"+tmpFile) - if rc != 0: - print("copy to EOS failed, stop",N,N+Nstart) - else: - rc = os.system("rm "+tmpFile) - N+=1000 - if N > len(goodRuns): break +prod = "1GeV" +globalPath = "/eos/experiment/ship/skygrid/background-prod-2018-1gev/" +fnames = "pythia8_Geant4_1_1.0.root" +ecut = "1.0" + + +def GetGoodAndBadRuns(startDate, endDate): + # find bad runs, try to recover + goodRuns = [] + badRuns = [] + fileName = "pythia8_Geant4_1_" + ecut + ".root" + os.system("ls -l --full-time " + globalPath + " >inventory.lst") + f = open("inventory.lst") + runs = f.readlines() + f.close() + N = 0 + for r in runs: + tmp = r.split(" ") + if len(tmp) != 9: + print("wrong format", tmp) + continue + date = tmp[5].split("-") + time = tmp[6].split(":") + fileDate = datetime.datetime( + int(date[0]), + int(date[1]), + int(date[2]), + int(time[0]), + int(time[1]), + int(time[2].split(".")[0]), + ) + if fileDate < startDate or fileDate > endDate: + continue + theRun = int(tmp[8].replace("\n", "")) + test = os.listdir(globalPath + str(theRun)) + if len(test) < 2: + continue + N += 1 + rc = os.system( + 'grep -q "Number of events produced with activity after hadron absorber" ' + + globalPath + + str(theRun) + + "/stdout" + ) + if rc != 0: + badRuns.append(theRun) + continue + for x in test: + if x.find("run_fixedTarget") > 0: + test2 = os.listdir(globalPath + str(theRun) + "/" + x) + bad = True + tmpF = False + f = globalPath + str(theRun) + "/" + x + "/" + fileName + if fnames + "tmp" in test2: + tmpF = True + f = f + "tmp" + elif fnames in test2: + f = f + else: + badRuns.append(theRun) + continue + try: + t = ROOT.TFile.Open(os.environ["EOSSHIP"] + f) + if not t: + badRuns.append(theRun) + continue + if N % 1000 == 0: + print(N, t.GetName()) + if t.ReadKeys() == 0: + t.Close() + badRuns.append(theRun) + continue + if t.FindObjectAny("cbmsim"): + bad = False + goodRuns.append(f) + t.Close() + except: + badRuns.append(theRun) + continue + return goodRuns, badRuns + + +def addRuns(goodRuns, Nstart=0): + N = 0 + while 1 > 0: + cmd = "" + for i in range(N, min(N + 1000, len(goodRuns))): + cmd += " $EOSSHIP" + goodRuns[i] + tmpFile = "pythia8_Geant4_" + ecut + "_c" + str(N + Nstart) + ".root" + rc = os.system("hadd -j 10 -O " + tmpFile + " " + cmd) + if rc != 0: + print("hadd failed, stop", N) + return + rc = os.system( + "xrdcp " + + tmpFile + + " $EOSSHIP/eos/experiment/ship/data/Mbias/background-prod-2018/" + + tmpFile + ) + if rc != 0: + print("copy to EOS failed, stop", N, N + Nstart) + else: + rc = os.system("rm " + tmpFile) + N += 1000 + if N > len(goodRuns): + break + + def YandexProd(): - #startDate = datetime.datetime(2018, 1, 1, 0, 0) # N=0 - #endDate = datetime.datetime(2018, 2, 1, 0, 0) - #startDate = datetime.datetime(2018, 2, 1, 0, 0) # N=23000 - #endDate = datetime.datetime(2018, 2, 6, 0, 0) - #startDate = datetime.datetime(2018, 2, 6, 0, 0) # N=33000 - #endDate = datetime.datetime(2018, 2, 12, 0, 0) - #startDate = datetime.datetime(2018, 2, 12, 0, 0) # N=45000 - #endDate = datetime.datetime(2018, 2, 15, 0, 0) - #startDate = datetime.datetime(2018, 2, 15, 0, 0) # N=51000 - #endDate = datetime.datetime(2018, 2, 21, 0, 0) - #startDate = datetime.datetime(2018, 2, 21, 0, 0) # N=63000 - #endDate = datetime.datetime(2018, 2, 2, 0, 0) - #startDate = datetime.datetime(2018, 1, 1, 0, 0) # start with 1 GeV production - #endDate = datetime.datetime(2018, 2, 27, 0, 0) # N=0 - #startDate = datetime.datetime(2018, 2, 27, 0, 0) # - #endDate = datetime.datetime(2018, 3, 6, 0, 0) # N=3000 - #startDate = datetime.datetime(2018, 3, 6, 0, 0) # - #endDate = datetime.datetime(2018, 3, 12, 0, 0) # N=9000 - goodRuns,badRuns = GetGoodAndBadRuns(startDate,endDate) - pName = 'goodAndBadRuns'+prod+'_'+startDate.__str__().split(' ')[0]+'_'+endDate.__str__().split(' ')[0]+'.pkl' - fpi=open(pName,'w') - database = {} - database['goodruns']=goodRuns - database['badRuns']=badRuns - pickle.dump(database,fpi) - fpi.close() - fpi=open(pName) - database = pickle.load(fpi) - addRuns(database['goodruns'],20000) # next cycle + # startDate = datetime.datetime(2018, 1, 1, 0, 0) # N=0 + # endDate = datetime.datetime(2018, 2, 1, 0, 0) + # startDate = datetime.datetime(2018, 2, 1, 0, 0) # N=23000 + # endDate = datetime.datetime(2018, 2, 6, 0, 0) + # startDate = datetime.datetime(2018, 2, 6, 0, 0) # N=33000 + # endDate = datetime.datetime(2018, 2, 12, 0, 0) + # startDate = datetime.datetime(2018, 2, 12, 0, 0) # N=45000 + # endDate = datetime.datetime(2018, 2, 15, 0, 0) + # startDate = datetime.datetime(2018, 2, 15, 0, 0) # N=51000 + # endDate = datetime.datetime(2018, 2, 21, 0, 0) + # startDate = datetime.datetime(2018, 2, 21, 0, 0) # N=63000 + # endDate = datetime.datetime(2018, 2, 2, 0, 0) + # startDate = datetime.datetime(2018, 1, 1, 0, 0) # start with 1 GeV production + # endDate = datetime.datetime(2018, 2, 27, 0, 0) # N=0 + # startDate = datetime.datetime(2018, 2, 27, 0, 0) # + # endDate = datetime.datetime(2018, 3, 6, 0, 0) # N=3000 + # startDate = datetime.datetime(2018, 3, 6, 0, 0) # + # endDate = datetime.datetime(2018, 3, 12, 0, 0) # N=9000 + goodRuns, badRuns = GetGoodAndBadRuns(startDate, endDate) + pName = ( + "goodAndBadRuns" + + prod + + "_" + + startDate.__str__().split(" ")[0] + + "_" + + endDate.__str__().split(" ")[0] + + ".pkl" + ) + fpi = open(pName, "w") + database = {} + database["goodruns"] = goodRuns + database["badRuns"] = badRuns + pickle.dump(database, fpi) + fpi.close() + fpi = open(pName) + database = pickle.load(fpi) + addRuns(database["goodruns"], 20000) # next cycle + def addAllHistograms(): - h={} - ecut = '10.0' - Nmax=45000 - path = os.environ['EOSSHIP']+"/eos/experiment/ship/data/Mbias/background-prod-2018/" - ut.bookCanvas(h,key='canvas',title='debug',nx=1600,ny=1200,cx=1,cy=1) - h['canvas'].SetLogy(1) - for i in range(0,Nmax,1000): - fname = "pythia8_Geant4_"+ecut+"_c"+str(i)+".root" - ut.readHists(h,path+fname) - if i==0: - h[1012].Draw() - for x in h.keys(): - if h[x].GetName().find('proj')>0: rc = h.pop(x) - ut.writeHists(h,"pythia8_Geant4_"+ecut+"_c"+str(Nmax)+"-histos.root") + h = {} + ecut = "10.0" + Nmax = 45000 + path = ( + os.environ["EOSSHIP"] + "/eos/experiment/ship/data/Mbias/background-prod-2018/" + ) + ut.bookCanvas(h, key="canvas", title="debug", nx=1600, ny=1200, cx=1, cy=1) + h["canvas"].SetLogy(1) + for i in range(0, Nmax, 1000): + fname = "pythia8_Geant4_" + ecut + "_c" + str(i) + ".root" + ut.readHists(h, path + fname) + if i == 0: + h[1012].Draw() + for x in h.keys(): + if h[x].GetName().find("proj") > 0: + rc = h.pop(x) + ut.writeHists(h, "pythia8_Geant4_" + ecut + "_c" + str(Nmax) + "-histos.root") -def compactifyCascade(cycle): - ncpus = 20 - path = "/afs/cern.ch/project/lbcern/vol1/truf/charm/" - cmd = '' - Ntot = 0 - NperJob = 2000000 - for i in range(cycle,cycle+ncpus): - fName = path+"run"+str(i)+"/Cascade-run"+str(i)+"-parp16-MSTP82-1-MSEL4.root" - f=open(path+"run"+str(i)+"/log"+str(i)) - success = False - for l in f.readlines(): - if not l.find('Macro finished succesfully')<0: success = True - if not success: - print("job not finished properly",fName) - continue - cmd += fName +" " - f.close() - Ntot+= NperJob - if cmd.find('root')<0: - print('no file found, exit') - else: - stat = str( int(Ntot/1E6))+'Mpot' - outFile = "Cascade-run"+str(cycle)+"-"+str(cycle+ncpus-1)+"-parp16-MSTP82-1-MSEL4-"+stat+".root" - rc = os.system("hadd -O "+outFile + " " +cmd) - rc = os.system("xrdcp "+outFile+" $EOSSHIP/eos/experiment/ship/data/Mbias/background-prod-2018/"+outFile) - if rc != 0: - print("copy to EOS failed, stop",outFile) - else: - rc = os.system("rm "+outFile) +def compactifyCascade(cycle): + ncpus = 20 + path = "/afs/cern.ch/project/lbcern/vol1/truf/charm/" + cmd = "" + Ntot = 0 + NperJob = 2000000 + for i in range(cycle, cycle + ncpus): + fName = ( + path + + "run" + + str(i) + + "/Cascade-run" + + str(i) + + "-parp16-MSTP82-1-MSEL4.root" + ) + f = open(path + "run" + str(i) + "/log" + str(i)) + success = False + for l in f.readlines(): + if not l.find("Macro finished succesfully") < 0: + success = True + if not success: + print("job not finished properly", fName) + continue + cmd += fName + " " + f.close() + Ntot += NperJob + if cmd.find("root") < 0: + print("no file found, exit") + else: + stat = str(int(Ntot / 1e6)) + "Mpot" + outFile = ( + "Cascade-run" + + str(cycle) + + "-" + + str(cycle + ncpus - 1) + + "-parp16-MSTP82-1-MSEL4-" + + stat + + ".root" + ) + rc = os.system("hadd -O " + outFile + " " + cmd) + rc = os.system( + "xrdcp " + + outFile + + " $EOSSHIP/eos/experiment/ship/data/Mbias/background-prod-2018/" + + outFile + ) + if rc != 0: + print("copy to EOS failed, stop", outFile) + else: + rc = os.system("rm " + outFile) # some old stuff def compactify(charm): - globalPath="/afs/cern.ch/project/lbcern/vol2/truf/muonBackground" - ecut = '10.0' - if charm: - allDirs = os.listdir(globalPath+"/charm") - allFiles = [] - for r in range(int(runMin),int(runMax)+1): -# collect the 20 subdirectories connected to a run - nr = '9000'+str(r) - subruns = [] - badFiles = [] - for x in allDirs: - for k in range(20): - sr = "{0:0>2}".format(k) - if not x.find(nr+sr)<0: - if not x.find('log')<0: continue - fn = 'pythia8_Geant4_'+nr+sr+'_'+ecut+'.root' - aFile = globalPath+"/charm/"+x+'/'+fn - if os.path.exists(aFile): - try: - t = ROOT.TFile.Open(aFile) - if not t: - badFiles.append(d) - continue - if t.ReadKeys()==0: - badFiles.append(d) - continue - if t.FindObjectAny('cbmsim'): - subruns.append(aFile) - except: - badFiles.append(aFile) - continue - ldir = ' ' - for x in subruns: ldir+= (x+" ") - outputr = 'pythia8_Geant4_charm_'+nr+'_'+ecut+'.root' - allFiles += (outputr+" ") - os.system('hadd ' + outputr +' '+ldir) - output = 'pythia8_Geant4_charm_'+str(runMin)+'_'+str(runMax)+'_'+ecut+'.root' - os.system('hadd ' + output +' '+allFiles) - makeHistos(output) - else: - output = 'pythia8_Geant4_'+str(runMin)+'-'+str(runMax)+'_'+ecut+'.root' - if not checkOnly: - ldir = '' - badFiles = [] - for d in os.listdir(globalPath): - if d.find( 'run_fixedTarget') < 0 : continue - srun = d.split('run_fixedTarget_')[1] - run = int(srun) - if not run > runMax and not run < runMin: - f = globalPath+'/'+d+'/pythia8_Geant4_'+srun+'_'+ecut+'.root ' - ftmp = f.replace('.root ','.roottmp') - if os.path.exists(ftmp):f=ftmp+' ' - try: - t = ROOT.TFile.Open(f) - if not t: - badFiles.append(d) - continue - if t.ReadKeys()==0: - badFiles.append(d) - continue - if t.FindObjectAny('cbmsim'): - ldir+=f - except: - badFiles.append(d) - continue - os.system('hadd '+output+' '+ldir) - makeHistos(output) + globalPath = "/afs/cern.ch/project/lbcern/vol2/truf/muonBackground" + ecut = "10.0" + if charm: + allDirs = os.listdir(globalPath + "/charm") + allFiles = [] + for r in range(int(runMin), int(runMax) + 1): + # collect the 20 subdirectories connected to a run + nr = "9000" + str(r) + subruns = [] + badFiles = [] + for x in allDirs: + for k in range(20): + sr = "{0:0>2}".format(k) + if not x.find(nr + sr) < 0: + if not x.find("log") < 0: + continue + fn = "pythia8_Geant4_" + nr + sr + "_" + ecut + ".root" + aFile = globalPath + "/charm/" + x + "/" + fn + if os.path.exists(aFile): + try: + t = ROOT.TFile.Open(aFile) + if not t: + badFiles.append(d) + continue + if t.ReadKeys() == 0: + badFiles.append(d) + continue + if t.FindObjectAny("cbmsim"): + subruns.append(aFile) + except: + badFiles.append(aFile) + continue + ldir = " " + for x in subruns: + ldir += x + " " + outputr = "pythia8_Geant4_charm_" + nr + "_" + ecut + ".root" + allFiles += outputr + " " + os.system("hadd " + outputr + " " + ldir) + output = ( + "pythia8_Geant4_charm_" + + str(runMin) + + "_" + + str(runMax) + + "_" + + ecut + + ".root" + ) + os.system("hadd " + output + " " + allFiles) + makeHistos(output) + else: + output = ( + "pythia8_Geant4_" + str(runMin) + "-" + str(runMax) + "_" + ecut + ".root" + ) + if not checkOnly: + ldir = "" + badFiles = [] + for d in os.listdir(globalPath): + if d.find("run_fixedTarget") < 0: + continue + srun = d.split("run_fixedTarget_")[1] + run = int(srun) + if not run > runMax and not run < runMin: + f = ( + globalPath + + "/" + + d + + "/pythia8_Geant4_" + + srun + + "_" + + ecut + + ".root " + ) + ftmp = f.replace(".root ", ".roottmp") + if os.path.exists(ftmp): + f = ftmp + " " + try: + t = ROOT.TFile.Open(f) + if not t: + badFiles.append(d) + continue + if t.ReadKeys() == 0: + badFiles.append(d) + continue + if t.FindObjectAny("cbmsim"): + ldir += f + except: + badFiles.append(d) + continue + os.system("hadd " + output + " " + ldir) + makeHistos(output) + def makeHistos(rfile): - f=ROOT.TFile.Open(rfile) - sTree = f.cbmsim - nTot = 0 - for k in f.GetListOfKeys(): - if k.GetName() == 'FileHeader': - tmp = k.GetTitle().split('=')[1] - tmp2 = tmp.split('with')[0] - if tmp2.find('E')<0: nTot += int(tmp2) - else: nTot += float(tmp2) - print("POT = ",nTot," number of events:",sTree.GetEntries()) -# particle statistics - h={} - ut.bookHist(h,'pids','pid',19999,-9999.5,9999.5) - ut.bookHist(h,'test','muon p/pt',100,0.,400.,100,0.,5.) - diMuonDecays = [221, 223, 113, 331, 333] - pDict = {} - procDict = {} - for n in range(sTree.GetEntries()): - rc = sTree.GetEvent(n) - for p in sTree.vetoPoint: - t = sTree.MCTrack[p.GetTrackID()] - pid = t.GetPdgCode() - rc = h['pids'].Fill(pid) - if abs(pid)==13: - procID = t.GetProcName().Data() - mother = t.GetMotherId() - if not mother < 0: - moPid = sTree.MCTrack[mother].GetPdgCode() - name = pdg.GetParticle(moPid).GetName() - name = procID+' '+name - if name not in h: h[name]=h['test'].Clone(name) - rc=h[name].Fill(t.GetP(),t.GetPt()) - if procID not in h: h[procID]=h['test'].Clone(procID) - rc=h[procID].Fill(t.GetP(),t.GetPt()) - for x in h: - h[x].Scale(1./nTot) - tmp = rfile.split('/') - hname = tmp[len(tmp)-1].replace('pythia8_Geant4','Histos') - ut.writeHists(h,hname) + f = ROOT.TFile.Open(rfile) + sTree = f.cbmsim + nTot = 0 + for k in f.GetListOfKeys(): + if k.GetName() == "FileHeader": + tmp = k.GetTitle().split("=")[1] + tmp2 = tmp.split("with")[0] + if tmp2.find("E") < 0: + nTot += int(tmp2) + else: + nTot += float(tmp2) + print("POT = ", nTot, " number of events:", sTree.GetEntries()) + # particle statistics + h = {} + ut.bookHist(h, "pids", "pid", 19999, -9999.5, 9999.5) + ut.bookHist(h, "test", "muon p/pt", 100, 0.0, 400.0, 100, 0.0, 5.0) + diMuonDecays = [221, 223, 113, 331, 333] + pDict = {} + procDict = {} + for n in range(sTree.GetEntries()): + rc = sTree.GetEvent(n) + for p in sTree.vetoPoint: + t = sTree.MCTrack[p.GetTrackID()] + pid = t.GetPdgCode() + rc = h["pids"].Fill(pid) + if abs(pid) == 13: + procID = t.GetProcName().Data() + mother = t.GetMotherId() + if not mother < 0: + moPid = sTree.MCTrack[mother].GetPdgCode() + name = pdg.GetParticle(moPid).GetName() + name = procID + " " + name + if name not in h: + h[name] = h["test"].Clone(name) + rc = h[name].Fill(t.GetP(), t.GetPt()) + if procID not in h: + h[procID] = h["test"].Clone(procID) + rc = h[procID].Fill(t.GetP(), t.GetPt()) + for x in h: + h[x].Scale(1.0 / nTot) + tmp = rfile.split("/") + hname = tmp[len(tmp) - 1].replace("pythia8_Geant4", "Histos") + ut.writeHists(h, hname) + hunbiased = {} -hbiased = {} +hbiased = {} import operator + + def makePrintout(): - # Histos_2000000-2001500_10.0.root - ut.readHists(hunbiased,'/media/microdisk/HNL/muonBackground/Histos_1000000-1000600_10.0.root') - ut.readHists(hbiased,'hadded_Histos_1_10.0.root') - - unbiased = {} - biased = {} - for l in hunbiased: - unbiased[l]=hunbiased[l].GetSumOfWeights() - for l in hbiased: - if l.find('proj') < 0 and l.find('test') < 0 and l.find('pids') < 0 : biased[l]=hbiased[l].GetSumOfWeights() - p={} - for i in range( 1,hbiased['pids'].GetNbinsX() + 1 ): - c = hbiased['pids'].GetBinContent(i) - if c>0: p[int(hbiased['pids'].GetBinCenter(i))]=c - - sorted_p = sorted(p.items(), key=operator.itemgetter(1)) - for p in sorted_p: - print("%25s : %5.2G"%(pdg.GetParticle(p[0]).GetName(),float(p[1]))) - sorted_pr = sorted(biased.items(), key=operator.itemgetter(1)) - print("origin of muons") - for p in sorted_pr: - if not p[0].find('Hadronic inelastic')<0: - if len(p[0])>len( 'Hadronic inelastic' ): continue - denom = 0 - if p[0] in unbiased: denom = unbiased[p[0]] - if denom >0: - fac = float(p[1])/denom - print("%40s : %5.2G %5.1F"%(p[0],float(p[1]),fac)) - else: - print("%40s : %5.2G "%(p[0],float(p[1]))) - -if len(sys.argv)>1: - runMin=sys.argv[1] - runMax=sys.argv[2] - if len(sys.argv)>3: charm=sys.argv[3] - compactify(charm) + # Histos_2000000-2001500_10.0.root + ut.readHists( + hunbiased, + "/media/microdisk/HNL/muonBackground/Histos_1000000-1000600_10.0.root", + ) + ut.readHists(hbiased, "hadded_Histos_1_10.0.root") + + unbiased = {} + biased = {} + for l in hunbiased: + unbiased[l] = hunbiased[l].GetSumOfWeights() + for l in hbiased: + if l.find("proj") < 0 and l.find("test") < 0 and l.find("pids") < 0: + biased[l] = hbiased[l].GetSumOfWeights() + p = {} + for i in range(1, hbiased["pids"].GetNbinsX() + 1): + c = hbiased["pids"].GetBinContent(i) + if c > 0: + p[int(hbiased["pids"].GetBinCenter(i))] = c + + sorted_p = sorted(p.items(), key=operator.itemgetter(1)) + for p in sorted_p: + print("%25s : %5.2G" % (pdg.GetParticle(p[0]).GetName(), float(p[1]))) + sorted_pr = sorted(biased.items(), key=operator.itemgetter(1)) + print("origin of muons") + for p in sorted_pr: + if not p[0].find("Hadronic inelastic") < 0: + if len(p[0]) > len("Hadronic inelastic"): + continue + denom = 0 + if p[0] in unbiased: + denom = unbiased[p[0]] + if denom > 0: + fac = float(p[1]) / denom + print("%40s : %5.2G %5.1F" % (p[0], float(p[1]), fac)) + else: + print("%40s : %5.2G " % (p[0], float(p[1]))) + + +if len(sys.argv) > 1: + runMin = sys.argv[1] + runMax = sys.argv[2] + if len(sys.argv) > 3: + charm = sys.argv[3] + compactify(charm) else: -# production without boost factor -#runMin = 1000000 -#runMax = 1000600 -# production with boost factor 100 -# runMin = 2001001 -# runMax = 2001500 # more does not work, maybe limit of hadd? 2001359 -# charm run_fixedTarget_9000119/pythia8_Geant4_9000219_10.0.root - print("methods to run: makeHistos(rfile),makePrintout()") + # production without boost factor + # runMin = 1000000 + # runMax = 1000600 + # production with boost factor 100 + # runMin = 2001001 + # runMax = 2001500 # more does not work, maybe limit of hadd? 2001359 + # charm run_fixedTarget_9000119/pythia8_Geant4_9000219_10.0.root + print("methods to run: makeHistos(rfile),makePrintout()") # yandex compactification, Feb 8 -#... startDate = datetime.datetime(2018, 1, 1, 0, 0) -#... endDate = datetime.datetime(2018, 2, 1, 0, 0) +# ... startDate = datetime.datetime(2018, 1, 1, 0, 0) +# ... endDate = datetime.datetime(2018, 2, 1, 0, 0) # ... goodAndBadRuns_2018-01-01_2018-02-01.pkl # hadd Source file 339: root://eospublic.cern.ch//eos/experiment/ship/skygrid/background-prod-2018/424121/80eefea19104_run_fixedTarget_1/pythia8_Geant4_1_10.0.root # hadd Target path: pythia8_Geant4_10.0_c22000.root:/ # len(database['goodruns']) .22339 # database['goodruns'][22338] '/eos/experiment/ship/skygrid/background-prod-2018/424121/80eefea19104_run_fixedTarget_1/pythia8_Geant4_1_10.0.root' -#... startDate = datetime.datetime(2018, 2, 1, 0, 0) -#... endDate = datetime.datetime(2018, 2, 6, 0, 0) +# ... startDate = datetime.datetime(2018, 2, 1, 0, 0) +# ... endDate = datetime.datetime(2018, 2, 6, 0, 0) # for charm # chicc=1.7e-3; //prob to produce primary ccbar pair/pot @@ -357,32 +462,40 @@ def makePrintout(): # for beauty # chibb=1.6e-7; + # something went wrong Yandex2018Prod-23000.root onwards up to 43000, only have of yield, 44000 ok !!! def removeStupidFiles(): - path = '/eos/experiment/ship/data/Mbias/background-prod-2018' - for f in os.listdir(path): - ff = path+'/'+f - x = os.path.getsize(ff) - if x < 500 : os.remove(ff) + path = "/eos/experiment/ship/data/Mbias/background-prod-2018" + for f in os.listdir(path): + ff = path + "/" + f + x = os.path.getsize(ff) + if x < 500: + os.remove(ff) def check4DoubleRuns(): - allRuns = ['goodAndBadRuns_2018-01-01_2018-02-01.pkl','goodAndBadRuns_2018-02-01_2018-02-06.pkl','goodAndBadRuns_2018-02-06_2018-02-12.pkl',\ - 'goodAndBadRuns_2018-02-12_2018-02-15.pkl','goodAndBadRuns_2018-02-15_2018-02-21.pkl','goodAndBadRuns_2018-02-21_2018-02-26.pkl'] - Nruns=0 - for x in allRuns: - fn = open(x) - dn = pickle.load(fn) - Nruns += len(dn['goodruns']) - print("Total number of runs:",Nruns) - - for n in range( len(allRuns)-1 ): - fn = open(allRuns[n]) - dn = pickle.load(fn) - for m in range( n+1, len(allRuns) ): - fm = open(allRuns[m]) - dm = pickle.load(fm) - for rn in dn['goodruns']: - for rm in dm['goodruns']: - if rn == rm : - print("double entry found",rn,allRuns[n],allRuns[m]) + allRuns = [ + "goodAndBadRuns_2018-01-01_2018-02-01.pkl", + "goodAndBadRuns_2018-02-01_2018-02-06.pkl", + "goodAndBadRuns_2018-02-06_2018-02-12.pkl", + "goodAndBadRuns_2018-02-12_2018-02-15.pkl", + "goodAndBadRuns_2018-02-15_2018-02-21.pkl", + "goodAndBadRuns_2018-02-21_2018-02-26.pkl", + ] + Nruns = 0 + for x in allRuns: + fn = open(x) + dn = pickle.load(fn) + Nruns += len(dn["goodruns"]) + print("Total number of runs:", Nruns) + + for n in range(len(allRuns) - 1): + fn = open(allRuns[n]) + dn = pickle.load(fn) + for m in range(n + 1, len(allRuns)): + fm = open(allRuns[m]) + dm = pickle.load(fm) + for rn in dn["goodruns"]: + for rm in dm["goodruns"]: + if rn == rm: + print("double entry found", rn, allRuns[n], allRuns[m]) diff --git a/muonShieldOptimization/exitHadronAbsorber.cxx b/muonShieldOptimization/exitHadronAbsorber.cxx index 4ddc47f52d..6f28481f05 100644 --- a/muonShieldOptimization/exitHadronAbsorber.cxx +++ b/muonShieldOptimization/exitHadronAbsorber.cxx @@ -1,265 +1,336 @@ #include "exitHadronAbsorber.h" -#include -#include "vetoPoint.h" -#include "FairLogger.h" // for FairLogger, MESSAGE_ORIGIN -#include "FairVolume.h" -#include "FairGeoVolume.h" -#include "FairGeoNode.h" -#include "FairRootManager.h" -#include "FairGeoLoader.h" +#include "FairGeoBuilder.h" #include "FairGeoInterface.h" +#include "FairGeoLoader.h" #include "FairGeoMedia.h" -#include "FairGeoBuilder.h" +#include "FairGeoNode.h" +#include "FairGeoVolume.h" +#include "FairLogger.h" // for FairLogger, MESSAGE_ORIGIN +#include "FairRootManager.h" #include "FairRun.h" #include "FairRuntimeDb.h" +#include "FairVolume.h" #include "ShipDetectorList.h" #include "ShipStack.h" - #include "TClonesArray.h" -#include "TVirtualMC.h" -#include "TGeoManager.h" +#include "TDatabasePDG.h" #include "TGeoBBox.h" -#include "TGeoEltu.h" #include "TGeoBoolNode.h" +#include "TGeoEltu.h" +#include "TGeoManager.h" #include "TGeoMaterial.h" -#include "TParticle.h" -#include "TROOT.h" #include "TH1D.h" #include "TH2D.h" -#include "TDatabasePDG.h" +#include "TParticle.h" +#include "TROOT.h" +#include "TVirtualMC.h" +#include "vetoPoint.h" #include +#include using std::cout; using std::endl; -Double_t cm = 1; // cm -Double_t m = 100*cm; // m -Double_t mm = 0.1*cm; // mm +Double_t cm = 1; // cm +Double_t m = 100 * cm; // m +Double_t mm = 0.1 * cm; // mm exitHadronAbsorber::exitHadronAbsorber() - : FairDetector("exitHadronAbsorber", kTRUE, kVETO), - fTrackID(-1), - fVolumeID(-1), - fPos(), - fMom(), - fTime(-1.), - fLength(-1.), - fOnlyMuons(kFALSE), - fSkipNeutrinos(kFALSE), - fzPos(3E8), - withNtuple(kFALSE), - fexitHadronAbsorberPointCollection(new TClonesArray("vetoPoint")) + : FairDetector("exitHadronAbsorber", kTRUE, kVETO) + , fTrackID(-1) + , fVolumeID(-1) + , fPos() + , fMom() + , fTime(-1.) + , fLength(-1.) + , fOnlyMuons(kFALSE) + , fSkipNeutrinos(kFALSE) + , fzPos(3E8) + , withNtuple(kFALSE) + , fexitHadronAbsorberPointCollection(new TClonesArray("vetoPoint")) {} exitHadronAbsorber::~exitHadronAbsorber() { - if (fexitHadronAbsorberPointCollection) { - fexitHadronAbsorberPointCollection->Delete(); - delete fexitHadronAbsorberPointCollection; - } + if (fexitHadronAbsorberPointCollection) { + fexitHadronAbsorberPointCollection->Delete(); + delete fexitHadronAbsorberPointCollection; + } } -Bool_t exitHadronAbsorber::ProcessHits(FairVolume* vol) +Bool_t exitHadronAbsorber::ProcessHits(FairVolume* vol) { - /** This method is called from the MC stepping */ - if ( gMC->IsTrackEntering() ) { - fTrackID = gMC->GetStack()->GetCurrentTrackNumber(); - TParticle* p = gMC->GetStack()->GetCurrentTrack(); - Int_t pdgCode = p->GetPdgCode(); - gMC->TrackMomentum(fMom); - if (!(fOnlyMuons && TMath::Abs(pdgCode)!=13)){ - fTime = gMC->TrackTime() * 1.0e09; - fLength = gMC->TrackLength(); - gMC->TrackPosition(fPos); - if ( (fMom.E()-fMom.M() )>EMax) { - AddHit(fTrackID, 111, TVector3(fPos.X(),fPos.Y(),fPos.Z()), - TVector3(fMom.Px(), fMom.Py(), fMom.Pz()), fTime, fLength, - 0,pdgCode,TVector3(p->Vx(), p->Vy(), p->Vz()),TVector3(p->Px(), p->Py(), p->Pz()) ); - ShipStack* stack = (ShipStack*) gMC->GetStack(); - stack->AddPoint(kVETO); - } + /** This method is called from the MC stepping */ + if (gMC->IsTrackEntering()) { + fTrackID = gMC->GetStack()->GetCurrentTrackNumber(); + TParticle* p = gMC->GetStack()->GetCurrentTrack(); + Int_t pdgCode = p->GetPdgCode(); + gMC->TrackMomentum(fMom); + if (!(fOnlyMuons && TMath::Abs(pdgCode) != 13)) { + fTime = gMC->TrackTime() * 1.0e09; + fLength = gMC->TrackLength(); + gMC->TrackPosition(fPos); + if ((fMom.E() - fMom.M()) > EMax) { + AddHit(fTrackID, + 111, + TVector3(fPos.X(), fPos.Y(), fPos.Z()), + TVector3(fMom.Px(), fMom.Py(), fMom.Pz()), + fTime, + fLength, + 0, + pdgCode, + TVector3(p->Vx(), p->Vy(), p->Vz()), + TVector3(p->Px(), p->Py(), p->Pz())); + ShipStack* stack = (ShipStack*)gMC->GetStack(); + stack->AddPoint(kVETO); + } + } } - } - gMC->StopTrack(); - return kTRUE; + gMC->StopTrack(); + return kTRUE; } void exitHadronAbsorber::Initialize() { - FairDetector::Initialize(); - TSeqCollection* fileList=gROOT->GetListOfFiles(); - fout = ((TFile*)fileList->At(0)); - // book hists for Genie neutrino momentum distribution - // add also leptons, and photon - // add pi0 111 eta 221 eta' 331 omega 223 for DM production - TDatabasePDG* PDG = TDatabasePDG::Instance(); - for(Int_t idnu=11; idnu<26; idnu+=1){ - // nu or anti-nu - for (Int_t idadd=-1; idadd<3; idadd+=2){ - Int_t idw=idnu; - if (idnu==18){idw=22;} - if (idnu==19){idw=111;} - if (idnu==20){idw=221;} - if (idnu==21){idw=223;} - if (idnu==22){idw=331;} - if (idnu==23){idw=211;} - if (idnu==24){idw=321;} - if (idnu==25){idw=2212;} - Int_t idhnu=10000+idw; - if (idadd==-1){ - if (idnu>17){continue;} - idhnu+=10000; - idw=-idnu; + FairDetector::Initialize(); + TSeqCollection* fileList = gROOT->GetListOfFiles(); + fout = ((TFile*)fileList->At(0)); + // book hists for Genie neutrino momentum distribution + // add also leptons, and photon + // add pi0 111 eta 221 eta' 331 omega 223 for DM production + TDatabasePDG* PDG = TDatabasePDG::Instance(); + for (Int_t idnu = 11; idnu < 26; idnu += 1) { + // nu or anti-nu + for (Int_t idadd = -1; idadd < 3; idadd += 2) { + Int_t idw = idnu; + if (idnu == 18) { + idw = 22; + } + if (idnu == 19) { + idw = 111; + } + if (idnu == 20) { + idw = 221; + } + if (idnu == 21) { + idw = 223; + } + if (idnu == 22) { + idw = 331; + } + if (idnu == 23) { + idw = 211; + } + if (idnu == 24) { + idw = 321; + } + if (idnu == 25) { + idw = 2212; + } + Int_t idhnu = 10000 + idw; + if (idadd == -1) { + if (idnu > 17) { + continue; + } + idhnu += 10000; + idw = -idnu; + } + TString name = PDG->GetParticle(idw)->GetName(); + TString title = name; + title += " momentum (GeV)"; + TString key = ""; + key += idhnu; + TH1D* Hidhnu = new TH1D(key, title, 400, 0., 400.); + title = name; + title += " log10-p vs log10-pt"; + key = ""; + key += idhnu + 1000; + TH2D* Hidhnu100 = new TH2D(key, title, 100, -0.3, 1.7, 100, -2., 0.5); + title = name; + title += " log10-p vs log10-pt"; + key = ""; + key += idhnu + 2000; + TH2D* Hidhnu200 = new TH2D(key, title, 25, -0.3, 1.7, 100, -2., 0.5); + } + } + if (withNtuple) { + fNtuple = new TNtuple("4DP", "4DP", "id:px:py:pz:x:y:z"); } - TString name=PDG->GetParticle(idw)->GetName(); - TString title = name;title+=" momentum (GeV)"; - TString key = "";key+=idhnu; - TH1D* Hidhnu = new TH1D(key,title,400,0.,400.); - title = name;title+=" log10-p vs log10-pt"; - key = "";key+=idhnu+1000; - TH2D* Hidhnu100 = new TH2D(key,title,100,-0.3,1.7,100,-2.,0.5); - title = name;title+=" log10-p vs log10-pt"; - key = "";key+=idhnu+2000; - TH2D* Hidhnu200 = new TH2D(key,title,25,-0.3,1.7,100,-2.,0.5); - } - } - if(withNtuple) { - fNtuple = new TNtuple("4DP","4DP","id:px:py:pz:x:y:z"); - } } void exitHadronAbsorber::EndOfEvent() { - fexitHadronAbsorberPointCollection->Clear(); - + fexitHadronAbsorberPointCollection->Clear(); } -void exitHadronAbsorber::PreTrack(){ +void exitHadronAbsorber::PreTrack() +{ gMC->TrackMomentum(fMom); - if ( (fMom.E()-fMom.M() )StopTrack(); - return; + if ((fMom.E() - fMom.M()) < EMax) { + gMC->StopTrack(); + return; } - TParticle* p = gMC->GetStack()->GetCurrentTrack(); + TParticle* p = gMC->GetStack()->GetCurrentTrack(); Int_t pdgCode = p->GetPdgCode(); -// record statistics for neutrinos, electrons and photons -// add pi0 111 eta 221 eta' 331 omega 223 + // record statistics for neutrinos, electrons and photons + // add pi0 111 eta 221 eta' 331 omega 223 Int_t idabs = TMath::Abs(pdgCode); - if (idabs<18 || idabs==22 || idabs==111 || idabs==221 || idabs==223 || idabs==331 - || idabs==211 || idabs==321 || idabs==2212 ){ - Double_t wspill = p->GetWeight(); - Int_t idhnu=idabs+10000; - if (pdgCode<0){ idhnu+=10000;} - Double_t l10ptot = TMath::Min(TMath::Max(TMath::Log10(fMom.P()),-0.3),1.69999); - Double_t l10pt = TMath::Min(TMath::Max(TMath::Log10(fMom.Pt()),-2.),0.4999); - TString key; key+=idhnu; - TH1D* h1 = (TH1D*)fout->Get(key); - if (h1){h1->Fill(fMom.P(),wspill);} - key="";key+=idhnu+1000; - TH2D* h2 = (TH2D*)fout->Get(key); - if (h2){h2->Fill(l10ptot,l10pt,wspill);} - key="";key+=idhnu+2000; - h2 = (TH2D*)fout->Get(key); - if (h2){h2->Fill(l10ptot,l10pt,wspill);} - if(withNtuple){ - fNtuple->Fill(pdgCode,fMom.Px(),fMom.Py(), fMom.Pz(),fPos.X(),fPos.Y(),fPos.Z()); - } - if (fSkipNeutrinos && (idabs==12 or idabs==14 or idabs == 16 )){gMC->StopTrack();} - } + if (idabs < 18 || idabs == 22 || idabs == 111 || idabs == 221 || idabs == 223 || idabs == 331 || idabs == 211 + || idabs == 321 || idabs == 2212) { + Double_t wspill = p->GetWeight(); + Int_t idhnu = idabs + 10000; + if (pdgCode < 0) { + idhnu += 10000; + } + Double_t l10ptot = TMath::Min(TMath::Max(TMath::Log10(fMom.P()), -0.3), 1.69999); + Double_t l10pt = TMath::Min(TMath::Max(TMath::Log10(fMom.Pt()), -2.), 0.4999); + TString key; + key += idhnu; + TH1D* h1 = (TH1D*)fout->Get(key); + if (h1) { + h1->Fill(fMom.P(), wspill); + } + key = ""; + key += idhnu + 1000; + TH2D* h2 = (TH2D*)fout->Get(key); + if (h2) { + h2->Fill(l10ptot, l10pt, wspill); + } + key = ""; + key += idhnu + 2000; + h2 = (TH2D*)fout->Get(key); + if (h2) { + h2->Fill(l10ptot, l10pt, wspill); + } + if (withNtuple) { + fNtuple->Fill(pdgCode, fMom.Px(), fMom.Py(), fMom.Pz(), fPos.X(), fPos.Y(), fPos.Z()); + } + if (fSkipNeutrinos && (idabs == 12 or idabs == 14 or idabs == 16)) { + gMC->StopTrack(); + } + } } -void exitHadronAbsorber::FinishRun(){ - for(Int_t idnu=11; idnu<23; idnu+=1){ - // nu or anti-nu - for (Int_t idadd=-1; idadd<3; idadd+=2){ - Int_t idw=idnu; - if (idnu==18){idw=22;} - if (idnu==19){idw=111;} - if (idnu==20){idw=221;} - if (idnu==21){idw=223;} - if (idnu==22){idw=331;} - Int_t idhnu=10000+idw; - if (idadd==-1){ - if (idnu>17){continue;} - idhnu+=10000; - idw=-idnu; +void exitHadronAbsorber::FinishRun() +{ + for (Int_t idnu = 11; idnu < 23; idnu += 1) { + // nu or anti-nu + for (Int_t idadd = -1; idadd < 3; idadd += 2) { + Int_t idw = idnu; + if (idnu == 18) { + idw = 22; + } + if (idnu == 19) { + idw = 111; + } + if (idnu == 20) { + idw = 221; + } + if (idnu == 21) { + idw = 223; + } + if (idnu == 22) { + idw = 331; + } + Int_t idhnu = 10000 + idw; + if (idadd == -1) { + if (idnu > 17) { + continue; + } + idhnu += 10000; + idw = -idnu; + } + TString key = ""; + key += idhnu; + TSeqCollection* fileList = gROOT->GetListOfFiles(); + ((TFile*)fileList->At(0))->cd(); + TH1D* Hidhnu = (TH1D*)fout->Get(key); + Hidhnu->Write(); + key = ""; + key += idhnu + 1000; + TH2D* Hidhnu100 = (TH2D*)fout->Get(key); + Hidhnu100->Write(); + key = ""; + key += idhnu + 2000; + TH2D* Hidhnu200 = (TH2D*)fout->Get(key); + Hidhnu200->Write(); + } + } + if (withNtuple) { + fNtuple->Write(); } - TString key = "";key+=idhnu; - TSeqCollection* fileList=gROOT->GetListOfFiles(); - ((TFile*)fileList->At(0))->cd(); - TH1D* Hidhnu = (TH1D*)fout->Get(key); - Hidhnu->Write(); - key="";key+=idhnu+1000; - TH2D* Hidhnu100 = (TH2D*)fout->Get(key); - Hidhnu100->Write(); - key = "";key+=idhnu+2000; - TH2D* Hidhnu200 = (TH2D*)fout->Get(key); - Hidhnu200->Write(); - } - } - if(withNtuple){fNtuple->Write();} } void exitHadronAbsorber::ConstructGeometry() { - static FairGeoLoader *geoLoad=FairGeoLoader::Instance(); - static FairGeoInterface *geoFace=geoLoad->getGeoInterface(); - static FairGeoMedia *media=geoFace->getMedia(); - static FairGeoBuilder *geoBuild=geoLoad->getGeoBuilder(); + static FairGeoLoader* geoLoad = FairGeoLoader::Instance(); + static FairGeoInterface* geoFace = geoLoad->getGeoInterface(); + static FairGeoMedia* media = geoFace->getMedia(); + static FairGeoBuilder* geoBuild = geoLoad->getGeoBuilder(); - FairGeoMedium *ShipMedium=media->getMedium("vacuums"); - TGeoMedium* vac=gGeoManager->GetMedium("vacuums"); - if (vac==NULL) - geoBuild->createMedium(ShipMedium); - vac =gGeoManager->GetMedium("vacuums"); - TGeoVolume *top=gGeoManager->GetTopVolume(); - TGeoNavigator* nav = gGeoManager->GetCurrentNavigator(); - Double_t zLoc; - if (fzPos>1E8){ - //Add thin sensitive plane after hadron absorber - Float_t distance = 1.; - Double_t local[3]= {0,0,0}; - if (not nav->cd("/MuonShieldArea_1/CoatWall_1")) { - nav->cd("/MuonShieldArea_1/MagnAbsorb2_MagRetL_1"); - distance = -1.;} - TGeoBBox* tmp = (TGeoBBox*)(nav->GetCurrentNode()->GetVolume()->GetShape()); - local[2] = distance * tmp->GetDZ(); - Double_t global[3] = {0,0,0}; - nav->LocalToMaster(local,global); - zLoc = global[2] + distance * 1.*cm; - }else{zLoc = fzPos;} // use external input - TGeoVolume *sensPlane = gGeoManager->MakeBox("sensPlane",vac,10.*m-1.*mm,10.*m-1.*mm,1.*mm); - nav->cd("/MuonShieldArea_1/"); - nav->GetCurrentNode()->GetVolume()->AddNode(sensPlane, 1, new TGeoTranslation(0, 0, zLoc)); - AddSensitiveVolume(sensPlane); + FairGeoMedium* ShipMedium = media->getMedium("vacuums"); + TGeoMedium* vac = gGeoManager->GetMedium("vacuums"); + if (vac == NULL) + geoBuild->createMedium(ShipMedium); + vac = gGeoManager->GetMedium("vacuums"); + TGeoVolume* top = gGeoManager->GetTopVolume(); + TGeoNavigator* nav = gGeoManager->GetCurrentNavigator(); + Double_t zLoc; + if (fzPos > 1E8) { + // Add thin sensitive plane after hadron absorber + Float_t distance = 1.; + Double_t local[3] = {0, 0, 0}; + if (not nav->cd("/MuonShieldArea_1/CoatWall_1")) { + nav->cd("/MuonShieldArea_1/MagnAbsorb2_MagRetL_1"); + distance = -1.; + } + TGeoBBox* tmp = (TGeoBBox*)(nav->GetCurrentNode()->GetVolume()->GetShape()); + local[2] = distance * tmp->GetDZ(); + Double_t global[3] = {0, 0, 0}; + nav->LocalToMaster(local, global); + zLoc = global[2] + distance * 1. * cm; + } else { + zLoc = fzPos; + } // use external input + TGeoVolume* sensPlane = gGeoManager->MakeBox("sensPlane", vac, 10. * m - 1. * mm, 10. * m - 1. * mm, 1. * mm); + nav->cd("/MuonShieldArea_1/"); + nav->GetCurrentNode()->GetVolume()->AddNode(sensPlane, 1, new TGeoTranslation(0, 0, zLoc)); + AddSensitiveVolume(sensPlane); } -vetoPoint* exitHadronAbsorber::AddHit(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t time, Double_t length, - Double_t eLoss, Int_t pdgCode,TVector3 Lpos, TVector3 Lmom) +vetoPoint* exitHadronAbsorber::AddHit(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t time, + Double_t length, + Double_t eLoss, + Int_t pdgCode, + TVector3 Lpos, + TVector3 Lmom) { - TClonesArray& clref = *fexitHadronAbsorberPointCollection; - Int_t size = clref.GetEntriesFast(); - return new(clref[size]) vetoPoint(trackID, detID, pos, mom, - time, length, eLoss, pdgCode,Lpos,Lmom); + TClonesArray& clref = *fexitHadronAbsorberPointCollection; + Int_t size = clref.GetEntriesFast(); + return new (clref[size]) vetoPoint(trackID, detID, pos, mom, time, length, eLoss, pdgCode, Lpos, Lmom); } void exitHadronAbsorber::Register() { - FairRootManager::Instance()->Register("vetoPoint", "veto", - fexitHadronAbsorberPointCollection, kTRUE); + FairRootManager::Instance()->Register("vetoPoint", "veto", fexitHadronAbsorberPointCollection, kTRUE); } TClonesArray* exitHadronAbsorber::GetCollection(Int_t iColl) const { - if (iColl == 0) { return fexitHadronAbsorberPointCollection; } - else { return NULL; } + if (iColl == 0) { + return fexitHadronAbsorberPointCollection; + } else { + return NULL; + } } void exitHadronAbsorber::Reset() { - fexitHadronAbsorberPointCollection->Clear(); + fexitHadronAbsorberPointCollection->Clear(); } diff --git a/muonShieldOptimization/exitHadronAbsorber.h b/muonShieldOptimization/exitHadronAbsorber.h index 78401ede4b..1938c7b820 100644 --- a/muonShieldOptimization/exitHadronAbsorber.h +++ b/muonShieldOptimization/exitHadronAbsorber.h @@ -2,26 +2,26 @@ #define EXITHADRONABSORBER_H #include "FairDetector.h" -#include "TVector3.h" -#include "TLorentzVector.h" +#include "TFile.h" #include "TGeoVolume.h" -#include "vetoPoint.h" +#include "TLorentzVector.h" #include "TNtuple.h" -#include "TFile.h" +#include "TVector3.h" +#include "vetoPoint.h" + #include class FairVolume; class TClonesArray; -class exitHadronAbsorber: public FairDetector +class exitHadronAbsorber : public FairDetector { public: - /** Name : Detector Name * Active: kTRUE for active detectors (ProcessHits() will be called) * kFALSE for inactive detectors - */ + */ exitHadronAbsorber(const char* Name, Bool_t Active); /** default constructor */ @@ -31,73 +31,77 @@ class exitHadronAbsorber: public FairDetector virtual ~exitHadronAbsorber(); /** Initialization of the detector is done here */ - virtual void Initialize(); + virtual void Initialize(); /** this method is called for each step during simulation * (see FairMCApplication::Stepping()) - */ - virtual Bool_t ProcessHits( FairVolume* v=0); + */ + virtual Bool_t ProcessHits(FairVolume* v = 0); /** Registers the produced collections in FAIRRootManager. */ - virtual void Register(); + virtual void Register(); /** Gets the produced collections */ - virtual TClonesArray* GetCollection(Int_t iColl) const ; + virtual TClonesArray* GetCollection(Int_t iColl) const; /** has to be called after each event to reset the containers */ - virtual void Reset(); + virtual void Reset(); /** Create the detector geometry */ void ConstructGeometry(); /** The following methods can be implemented if you need to make * any optional action in your detector during the transport. - */ - - virtual void CopyClones( TClonesArray* cl1, TClonesArray* cl2 , - Int_t offset) {;} - virtual void SetSpecialPhysicsCuts() {;} - virtual void EndOfEvent(); - virtual void FinishPrimary() {;} - virtual void FinishRun(); - virtual void BeginPrimary() {;} - virtual void PostTrack() {;} - virtual void PreTrack(); - virtual void BeginEvent() {;} - - vetoPoint* AddHit(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t time, Double_t length, - Double_t eLoss,Int_t pdgcode,TVector3 Lpos, TVector3 Lmom); - inline void SetEnergyCut(Float_t emax) {EMax=emax;}// min energy to be copied to Geant4 - inline void SetOnlyMuons(){fOnlyMuons=kTRUE;} - inline void SetOpt4DP(){withNtuple=kTRUE;} - inline void SkipNeutrinos(){fSkipNeutrinos=kTRUE;} - inline void SetZposition(Float_t x){fzPos=x;} + */ + + virtual void CopyClones(TClonesArray* cl1, TClonesArray* cl2, Int_t offset) { ; } + virtual void SetSpecialPhysicsCuts() { ; } + virtual void EndOfEvent(); + virtual void FinishPrimary() { ; } + virtual void FinishRun(); + virtual void BeginPrimary() { ; } + virtual void PostTrack() { ; } + virtual void PreTrack(); + virtual void BeginEvent() { ; } + + vetoPoint* AddHit(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t time, + Double_t length, + Double_t eLoss, + Int_t pdgcode, + TVector3 Lpos, + TVector3 Lmom); + inline void SetEnergyCut(Float_t emax) { EMax = emax; } // min energy to be copied to Geant4 + inline void SetOnlyMuons() { fOnlyMuons = kTRUE; } + inline void SetOpt4DP() { withNtuple = kTRUE; } + inline void SkipNeutrinos() { fSkipNeutrinos = kTRUE; } + inline void SetZposition(Float_t x) { fzPos = x; } private: - /** Track information to be stored until the track leaves the active volume. */ - Int_t fTrackID; //! track index - Int_t fVolumeID; //! volume id - TLorentzVector fPos; //! position at entrance - TLorentzVector fMom; //! momentum at entrance - Double_t fTime; //! time - Double_t fLength; //! length - Double_t fzPos; //! zPos, optional - Bool_t withNtuple; //! special option for Dark Photon physics studies - TNtuple* fNtuple; //! - Float_t EMax; //! max energy to transport - Bool_t fOnlyMuons; //! flag if only muons should be stored - Bool_t fSkipNeutrinos; //! flag if neutrinos should be ignored - TFile* fout; //! - TClonesArray* fElectrons; //! + Int_t fTrackID; //! track index + Int_t fVolumeID; //! volume id + TLorentzVector fPos; //! position at entrance + TLorentzVector fMom; //! momentum at entrance + Double_t fTime; //! time + Double_t fLength; //! length + Double_t fzPos; //! zPos, optional + Bool_t withNtuple; //! special option for Dark Photon physics studies + TNtuple* fNtuple; //! + Float_t EMax; //! max energy to transport + Bool_t fOnlyMuons; //! flag if only muons should be stored + Bool_t fSkipNeutrinos; //! flag if neutrinos should be ignored + TFile* fout; //! + TClonesArray* fElectrons; //! Int_t index; /** container for data points */ - TClonesArray* fexitHadronAbsorberPointCollection; + TClonesArray* fexitHadronAbsorberPointCollection; ClassDef(exitHadronAbsorber, 0) }; -#endif //EXITHADRONABSORBER_H +#endif // EXITHADRONABSORBER_H diff --git a/muonShieldOptimization/extractMuonsAndUpdateWeight.py b/muonShieldOptimization/extractMuonsAndUpdateWeight.py index f00a5a931c..e90d3e979e 100644 --- a/muonShieldOptimization/extractMuonsAndUpdateWeight.py +++ b/muonShieldOptimization/extractMuonsAndUpdateWeight.py @@ -1,98 +1,118 @@ -import os,ROOT +import os + +import ROOT import rootUtils as ut -path = '/eos/experiment/ship/data/Mbias/background-prod-2018/' + +path = "/eos/experiment/ship/data/Mbias/background-prod-2018/" # functions, should extract events with muons, update weight based on process/decay and PoT -muSources = {'eta':221,'omega':223,'phi':333,'rho0':113,'eta_prime':331} -charmExtern = [4332,4232,4132,4232,4122,431,411,421] +muSources = {"eta": 221, "omega": 223, "phi": 333, "rho0": 113, "eta_prime": 331} +charmExtern = [4332, 4232, 4132, 4232, 4122, 431, 411, 421] # for 10GeV Yandex Production 65.041 Billion PoT, weight = 768.75 for 5E13 pot weightMbias = 768.75 # for 10GeV charm Production 102.2 Billion PoT equivalent, weight = 489.24 # added another cycle -weightCharm = 489.24 * 2./3. +weightCharm = 489.24 * 2.0 / 3.0 # for 10GeV charm Production 5336 Billion PoT equivalent, weight = 9.37 weightBeauty = 9.37 -def muonUpdateWeight(sTree,diMuboost,xSecboost,noCharm=True): - nMu=0 - for v in sTree.vetoPoint: - mu = v.GetTrackID() - t = sTree.MCTrack[mu] - if abs(t.GetPdgCode())!=13: continue - moID = abs(sTree.MCTrack[t.GetMotherId()].GetPdgCode()) - if moID in charmExtern and noCharm: continue # take heavy flavours from separate production - nMu+=1 - pName = t.GetProcName().Data() - t.SetWeight(weight) - if not pName.find('Hadronic inelastic')<0: - t.MultiplyWeight(1./diMuboost) - elif not pName.find('Lepton pair')<0: - t.MultiplyWeight(1./xSecboost) - elif not pName.find('Positron annihilation')<0: - t.MultiplyWeight(1./xSecboost) - elif not pName.find('Primary particle')<0 or not pName.find('Decay')<0: - if moID in muSources.values(): - t.MultiplyWeight(1./diMuboost) - return nMu + +def muonUpdateWeight(sTree, diMuboost, xSecboost, noCharm=True): + nMu = 0 + for v in sTree.vetoPoint: + mu = v.GetTrackID() + t = sTree.MCTrack[mu] + if abs(t.GetPdgCode()) != 13: + continue + moID = abs(sTree.MCTrack[t.GetMotherId()].GetPdgCode()) + if moID in charmExtern and noCharm: + continue # take heavy flavours from separate production + nMu += 1 + pName = t.GetProcName().Data() + t.SetWeight(weight) + if not pName.find("Hadronic inelastic") < 0: + t.MultiplyWeight(1.0 / diMuboost) + elif not pName.find("Lepton pair") < 0: + t.MultiplyWeight(1.0 / xSecboost) + elif not pName.find("Positron annihilation") < 0: + t.MultiplyWeight(1.0 / xSecboost) + elif not pName.find("Primary particle") < 0 or not pName.find("Decay") < 0: + if moID in muSources.values(): + t.MultiplyWeight(1.0 / diMuboost) + return nMu + def PoT(f): - nTot = 0 - # POT = 1000000000 with ecut=10.0 diMu100.0 X100.0 - diMuboost = 0. - xSecboost = 0. - ncycles = 0 - for k in f.GetListOfKeys(): - if k.GetName() == 'FileHeader': - txt = k.GetTitle() - tmp = txt.split('=')[1] - tmp2 = tmp.split('with')[0] - if tmp2.find('E')<0: nTot += int(tmp2) - else: nTot += float(tmp2) - ncycles+=1 - i = txt.find('diMu') - if i < 0: - diMuboost+=1. - else: - diMuboost+=float(txt[i+4:].split(' ')[0]) - i = txt.find('X') - if i < 0: - xSecboost+=1. - else: - xSecboost+=float(txt[i+1:].split(' ')[0]) - diMuboost=diMuboost/float(ncycles) - xSecboost=xSecboost/float(ncycles) - print("POT = ",nTot," number of events:",f.cbmsim.GetEntries(),' diMuboost=',diMuboost,' XsecBoost=',xSecboost) - return nTot,diMuboost,xSecboost + nTot = 0 + # POT = 1000000000 with ecut=10.0 diMu100.0 X100.0 + diMuboost = 0.0 + xSecboost = 0.0 + ncycles = 0 + for k in f.GetListOfKeys(): + if k.GetName() == "FileHeader": + txt = k.GetTitle() + tmp = txt.split("=")[1] + tmp2 = tmp.split("with")[0] + if tmp2.find("E") < 0: + nTot += int(tmp2) + else: + nTot += float(tmp2) + ncycles += 1 + i = txt.find("diMu") + if i < 0: + diMuboost += 1.0 + else: + diMuboost += float(txt[i + 4 :].split(" ")[0]) + i = txt.find("X") + if i < 0: + xSecboost += 1.0 + else: + xSecboost += float(txt[i + 1 :].split(" ")[0]) + diMuboost = diMuboost / float(ncycles) + xSecboost = xSecboost / float(ncycles) + print( + "POT = ", + nTot, + " number of events:", + f.cbmsim.GetEntries(), + " diMuboost=", + diMuboost, + " XsecBoost=", + xSecboost, + ) + return nTot, diMuboost, xSecboost + def TotStat(): - lfiles = os.listdir(path) - ntot = 0 - for fn in lfiles: - f=ROOT.TFile(path+fn) - nPot,diMuboost,xSecboost = PoT(f) - ntot += nPot - print("Total statistics so far",ntot/1.E9," billion") + lfiles = os.listdir(path) + ntot = 0 + for fn in lfiles: + f = ROOT.TFile(path + fn) + nPot, diMuboost, xSecboost = PoT(f) + ntot += nPot + print("Total statistics so far", ntot / 1.0e9, " billion") + -def processFile(fin,noCharm=True): - f = ROOT.TFile.Open(os.environ['EOSSHIP']+path+fin) - nPot,diMuboost,xSecboost = PoT(f) +def processFile(fin, noCharm=True): + f = ROOT.TFile.Open(os.environ["EOSSHIP"] + path + fin) + nPot, diMuboost, xSecboost = PoT(f) sTree = f.cbmsim - outFile = fin.replace(".root","_mu.root") - fmu = ROOT.TFile(outFile,"recreate") + outFile = fin.replace(".root", "_mu.root") + fmu = ROOT.TFile(outFile, "recreate") newTree = sTree.CloneTree(0) for n in range(sTree.GetEntries()): - sTree.GetEntry(n) - nMu = muonUpdateWeight(sTree,diMuboost,xSecboost,noCharm) - if nMu>0: - rc = newTree.Fill() - ff = f.FileHeader.Clone('Extracted Muon Background File') + sTree.GetEntry(n) + nMu = muonUpdateWeight(sTree, diMuboost, xSecboost, noCharm) + if nMu > 0: + rc = newTree.Fill() + ff = f.FileHeader.Clone("Extracted Muon Background File") txt = ff.GetTitle() - tmp = txt.split('=')[1] - newTxt = txt.replace(tmp.split('with')[0].replace(' ',''),str(nPot)) + tmp = txt.split("=")[1] + newTxt = txt.replace(tmp.split("with")[0].replace(" ", ""), str(nPot)) ff.SetTitle(newTxt) fmu.cd() ff.Write("FileHeader", ROOT.TObject.kSingleKey) @@ -100,165 +120,201 @@ def processFile(fin,noCharm=True): fmu.Close() return 0 + def run(): - tmp = "pythia8_Geant4_10.0_cXX.root" - global weight - weight = weightMbias - for run in range(0,67000,1000): - rc = processFile(tmp.replace('XX',str(run))) - if rc == 0: - fmu = tmp.replace('XX',str(run)+"_mu") - rc = os.system("xrdcp "+fmu+" $EOSSHIP/eos/experiment/ship/data/Mbias/background-prod-2018/"+fmu) - if rc != 0: - print("copy to EOS failed, stop",fmu) - else: - rc = os.system("rm "+fmu) + tmp = "pythia8_Geant4_10.0_cXX.root" + global weight + weight = weightMbias + for run in range(0, 67000, 1000): + rc = processFile(tmp.replace("XX", str(run))) + if rc == 0: + fmu = tmp.replace("XX", str(run) + "_mu") + rc = os.system( + "xrdcp " + + fmu + + " $EOSSHIP/eos/experiment/ship/data/Mbias/background-prod-2018/" + + fmu + ) + if rc != 0: + print("copy to EOS failed, stop", fmu) + else: + rc = os.system("rm " + fmu) def run4Charm(): - tmp = "pythia8_Geant4_charm_XX-YY_10.0.root" - global weight - weight = weightCharm - for cycle in [0,1,2]: - for run in range(0,100,20): - crun = run+cycle*1000 - fname = tmp.replace('XX',str(crun)).replace('YY',str(crun+19)) - rc = processFile(fname,False) - if rc == 0: - fmu = fname.replace('.root',"_mu.root") - rc = os.system("xrdcp "+fmu+" $EOSSHIP/eos/experiment/ship/data/Mbias/background-prod-2018/"+fmu) - if rc != 0: - print("copy to EOS failed, stop",fmu) - else: - rc = os.system("rm "+fmu) + tmp = "pythia8_Geant4_charm_XX-YY_10.0.root" + global weight + weight = weightCharm + for cycle in [0, 1, 2]: + for run in range(0, 100, 20): + crun = run + cycle * 1000 + fname = tmp.replace("XX", str(crun)).replace("YY", str(crun + 19)) + rc = processFile(fname, False) + if rc == 0: + fmu = fname.replace(".root", "_mu.root") + rc = os.system( + "xrdcp " + + fmu + + " $EOSSHIP/eos/experiment/ship/data/Mbias/background-prod-2018/" + + fmu + ) + if rc != 0: + print("copy to EOS failed, stop", fmu) + else: + rc = os.system("rm " + fmu) + def run4beauty(): - global weight - weight = weightBeauty - fname = "pythia8_Geant4_beauty_5336B_10.0.root" - rc = processFile(fname,False) - if rc == 0: - fmu = fname.replace('.root',"_mu.root") - rc = os.system("xrdcp "+fmu+" $EOSSHIP/eos/experiment/ship/data/Mbias/background-prod-2018/"+fmu) - if rc != 0: - print("copy to EOS failed, stop",fmu) - else: - rc = os.system("rm "+fmu) + global weight + weight = weightBeauty + fname = "pythia8_Geant4_beauty_5336B_10.0.root" + rc = processFile(fname, False) + if rc == 0: + fmu = fname.replace(".root", "_mu.root") + rc = os.system( + "xrdcp " + + fmu + + " $EOSSHIP/eos/experiment/ship/data/Mbias/background-prod-2018/" + + fmu + ) + if rc != 0: + print("copy to EOS failed, stop", fmu) + else: + rc = os.system("rm " + fmu) + # merge with beauty in a second step # finished one file pythia8_Geant4_10.0_withCharm44000_mu.root 2712798 1113638 + def mergeCharm(): - tmp = "pythia8_Geant4_charm_XX-YY_10.0.root" - mergedFile = "pythia8_Geant4_charm_102.2B_10.0_mu.root" - cmd = "hadd "+mergedFile - for cycle in [0,1]: - for run in range(0,100,20): - crun = run+cycle*1000 - fname = tmp.replace('XX',str(crun)).replace('YY',str(crun+19)) - fmu = " $EOSSHIP/eos/experiment/ship/data/Mbias/background-prod-2018/"+fname.replace('.root',"_mu.root") - cmd += fmu - rc = os.system(cmd) - rc = os.system("xrdcp "+mergedFile+" $EOSSHIP/eos/experiment/ship/data/Mbias/background-prod-2018/"+mergedFile) + tmp = "pythia8_Geant4_charm_XX-YY_10.0.root" + mergedFile = "pythia8_Geant4_charm_102.2B_10.0_mu.root" + cmd = "hadd " + mergedFile + for cycle in [0, 1]: + for run in range(0, 100, 20): + crun = run + cycle * 1000 + fname = tmp.replace("XX", str(crun)).replace("YY", str(crun + 19)) + fmu = ( + " $EOSSHIP/eos/experiment/ship/data/Mbias/background-prod-2018/" + + fname.replace(".root", "_mu.root") + ) + cmd += fmu + rc = os.system(cmd) + rc = os.system( + "xrdcp " + + mergedFile + + " $EOSSHIP/eos/experiment/ship/data/Mbias/background-prod-2018/" + + mergedFile + ) + def mergeMbiasAndCharm(flavour="charm"): - done = [] - timer = ROOT.TStopwatch() - timer.Start() - pp = os.environ['EOSSHIP']+path - Rndm=ROOT.TRandom3() - Rndm.SetSeed(0) - if flavour=="charm": - allFiles = {'charm':"pythia8_Geant4_charm_102.2B_10.0_mu.root"} - tmp = "pythia8_Geant4_10.0_cXX_mu.root" - else: - allFiles = {'beauty':"pythia8_Geant4_beauty_5336B_10.0_mu.root"} - tmp = "pythia8_Geant4_10.0_withCharmXX_mu.root" - for run in range(0,67000,1000): - allFiles[str(run)] = tmp.replace('XX',str(run)) - nEntries = {} - Nall = 0 - for x in allFiles: - f=ROOT.TFile.Open(pp+allFiles[x]) - nEntries[x]=f.cbmsim.GetEntries() - Nall += nEntries[x] - nCharm = 0 - nDone = 0 - frac = nEntries[flavour]/float(Nall) - print("debug",frac) - os.system('xrdcp '+pp +allFiles[flavour] +' '+allFiles[flavour]) - for k in allFiles: - if k==flavour: continue - if k in done: continue - os.system('xrdcp '+pp +allFiles[k] +' ' +allFiles[k]) - os.system('hadd -f tmp.root '+ allFiles[flavour] + ' '+ allFiles[k] ) - os.system('rm '+allFiles[k]) - f = ROOT.TFile('tmp.root') - sTree = f.cbmsim - sTree.LoadBaskets(30000000000) - if flavour=="charm": - outFile = tmp.replace('cXX','withCharm'+k) - else: - outFile = tmp.replace('XX','andBeauty'+k) - fmu = ROOT.TFile(outFile,"recreate") - newTree = sTree.CloneTree(0) - nMbias = 0 - # 0 - nEntries['charm']-1 , nEntries['charm'] - nEntries[0]-1, nEntries[0] - nEntries[1000]-1 - # randomList = ROOT.TEntryList(chain) - myList = [] - while nMbias frac: - # rc = randomList.Enter(nMbias+nEntries['charm']) - myList.append( nMbias+nEntries[flavour] ) - nMbias+=1 - else: - if nEntries[flavour]>nCharm: - # rc = randomList.Enter(nCharm) - myList.append( nCharm ) - nCharm+=1 - else: copyEvent = False - # chain.SetEntryList(randomList) - # nev = randomList.GetN() - nev = len(myList) - print("start:",outFile,nev) - for iev in range(nev) : - rc =sTree.GetEntry(myList[iev]) - rc = newTree.Fill() - if (iev)%100000==0: - timer.Stop() - print("status:",timer.RealTime(),k,iev) - timer.Start() - newTree.AutoSave() - print("finished one file",outFile,nMbias,nCharm) - if flavour=="charm": - ff = f.FileHeader.Clone('With Charm Merged Muon Background File') - else: - ff = f.FileHeader.Clone('With Charm and Beauty Merged Muon Background File') - txt = ff.GetTitle() - fmu.cd() - ff.Write("FileHeader", ROOT.TObject.kSingleKey) - fmu.Close() - f.Close() - rc = os.system("xrdcp "+outFile+" $EOSSHIP/eos/experiment/ship/data/Mbias/background-prod-2018/"+outFile) - if rc != 0: - print("copy to EOS failed",outFile) - else: - rc = os.system("rm "+outFile) + done = [] + timer = ROOT.TStopwatch() + timer.Start() + pp = os.environ["EOSSHIP"] + path + Rndm = ROOT.TRandom3() + Rndm.SetSeed(0) + if flavour == "charm": + allFiles = {"charm": "pythia8_Geant4_charm_102.2B_10.0_mu.root"} + tmp = "pythia8_Geant4_10.0_cXX_mu.root" + else: + allFiles = {"beauty": "pythia8_Geant4_beauty_5336B_10.0_mu.root"} + tmp = "pythia8_Geant4_10.0_withCharmXX_mu.root" + for run in range(0, 67000, 1000): + allFiles[str(run)] = tmp.replace("XX", str(run)) + nEntries = {} + Nall = 0 + for x in allFiles: + f = ROOT.TFile.Open(pp + allFiles[x]) + nEntries[x] = f.cbmsim.GetEntries() + Nall += nEntries[x] + nCharm = 0 + nDone = 0 + frac = nEntries[flavour] / float(Nall) + print("debug", frac) + os.system("xrdcp " + pp + allFiles[flavour] + " " + allFiles[flavour]) + for k in allFiles: + if k == flavour: + continue + if k in done: + continue + os.system("xrdcp " + pp + allFiles[k] + " " + allFiles[k]) + os.system("hadd -f tmp.root " + allFiles[flavour] + " " + allFiles[k]) + os.system("rm " + allFiles[k]) + f = ROOT.TFile("tmp.root") + sTree = f.cbmsim + sTree.LoadBaskets(30000000000) + if flavour == "charm": + outFile = tmp.replace("cXX", "withCharm" + k) + else: + outFile = tmp.replace("XX", "andBeauty" + k) + fmu = ROOT.TFile(outFile, "recreate") + newTree = sTree.CloneTree(0) + nMbias = 0 + # 0 - nEntries['charm']-1 , nEntries['charm'] - nEntries[0]-1, nEntries[0] - nEntries[1000]-1 + # randomList = ROOT.TEntryList(chain) + myList = [] + while nMbias < nEntries[k]: + copyEvent = True + if Rndm.Rndm() > frac: + # rc = randomList.Enter(nMbias+nEntries['charm']) + myList.append(nMbias + nEntries[flavour]) + nMbias += 1 + else: + if nEntries[flavour] > nCharm: + # rc = randomList.Enter(nCharm) + myList.append(nCharm) + nCharm += 1 + else: + copyEvent = False + # chain.SetEntryList(randomList) + # nev = randomList.GetN() + nev = len(myList) + print("start:", outFile, nev) + for iev in range(nev): + rc = sTree.GetEntry(myList[iev]) + rc = newTree.Fill() + if (iev) % 100000 == 0: + timer.Stop() + print("status:", timer.RealTime(), k, iev) + timer.Start() + newTree.AutoSave() + print("finished one file", outFile, nMbias, nCharm) + if flavour == "charm": + ff = f.FileHeader.Clone("With Charm Merged Muon Background File") + else: + ff = f.FileHeader.Clone("With Charm and Beauty Merged Muon Background File") + txt = ff.GetTitle() + fmu.cd() + ff.Write("FileHeader", ROOT.TObject.kSingleKey) + fmu.Close() + f.Close() + rc = os.system( + "xrdcp " + + outFile + + " $EOSSHIP/eos/experiment/ship/data/Mbias/background-prod-2018/" + + outFile + ) + if rc != 0: + print("copy to EOS failed", outFile) + else: + rc = os.system("rm " + outFile) -def testRatio(fname): - f=ROOT.TFile.Open(os.environ['EOSSHIP']+path+fname) - sTree = f.cbmsim - Nall = sTree.GetEntries() - charm = 0 - for n in range(Nall): - rc = sTree.GetEvent(n) - for m in sTree.MCTrack: - pdgID = abs(m.GetPdgCode()) - if pdgID in charmExtern: - charm+=1 - break - print("charm found",charm," ratio ",charm/float(Nall)) +def testRatio(fname): + f = ROOT.TFile.Open(os.environ["EOSSHIP"] + path + fname) + sTree = f.cbmsim + Nall = sTree.GetEntries() + charm = 0 + for n in range(Nall): + rc = sTree.GetEvent(n) + for m in sTree.MCTrack: + pdgID = abs(m.GetPdgCode()) + if pdgID in charmExtern: + charm += 1 + break + print("charm found", charm, " ratio ", charm / float(Nall)) diff --git a/muonShieldOptimization/extractNeutrinosAndUpdateWeight.py b/muonShieldOptimization/extractNeutrinosAndUpdateWeight.py index bc831b7b75..b50dc2435a 100644 --- a/muonShieldOptimization/extractNeutrinosAndUpdateWeight.py +++ b/muonShieldOptimization/extractNeutrinosAndUpdateWeight.py @@ -1,21 +1,24 @@ -import os,ROOT +import os + +import ROOT import rootUtils as ut -path = '/eos/experiment/ship/data/Mbias/background-prod-2018/' + +path = "/eos/experiment/ship/data/Mbias/background-prod-2018/" # should fill hisograms with neutrinos, for mbias, exclude neutrinos from charm # update weight based on process/decay and PoT -charmExtern = [4332,4232,4132,4232,4122,431,411,421,15] -neutrinos = [12,14,16] +charmExtern = [4332, 4232, 4132, 4232, 4122, 431, 411, 421, 15] +neutrinos = [12, 14, 16] # for 10GeV Yandex Production 65.041 Billion PoT, weight = 768.75 for 5E13 pot weightMbias = 768.75 # for 1GeV Yandex Production 1.8 Billion PoT, weight = 27778. for 5E13 pot -weightMbias1GeV = 27778. +weightMbias1GeV = 27778.0 # for 10GeV charm Production 153.3 Billion PoT equivalent, weight = 489.24 # added another cycle -weightCharm = 326. +weightCharm = 326.0 # for 1GeV charm Production 10.2 Billion PoT equivalent, weight = 4895.24 weightCharm1GeV = 4895.24 @@ -23,108 +26,128 @@ weightBeauty = 9.37 import rootUtils as ut -h={} + +h = {} PDG = ROOT.TDatabasePDG.Instance() -for idnu in range(12,17,2): - # nu or anti-nu - for idadd in range(-1,2): - idw=idnu - idhnu=1000+idw - if idadd==-1: - idhnu+=1000 - idw=-idnu - name=PDG.GetParticle(idw).GetName() - title = name+" momentum (GeV)" - key = idhnu - ut.bookHist(h,key,title,400,0.,400.) - title = name+" log10-p vs log10-pt" - key = idhnu+100 - ut.bookHist(h,key,title,100,-0.3,1.7,100,-2.,0.5) - title = name+" log10-p vs log10-pt" - key = idhnu+200 - ut.bookHist(h,key,title,25,-0.3,1.7,100,-2.,0.5) - -def processFile(fin,noCharm=True): - f = ROOT.TFile.Open(os.environ['EOSSHIP']+path+fin) - print("opened file ",fin) +for idnu in range(12, 17, 2): + # nu or anti-nu + for idadd in range(-1, 2): + idw = idnu + idhnu = 1000 + idw + if idadd == -1: + idhnu += 1000 + idw = -idnu + name = PDG.GetParticle(idw).GetName() + title = name + " momentum (GeV)" + key = idhnu + ut.bookHist(h, key, title, 400, 0.0, 400.0) + title = name + " log10-p vs log10-pt" + key = idhnu + 100 + ut.bookHist(h, key, title, 100, -0.3, 1.7, 100, -2.0, 0.5) + title = name + " log10-p vs log10-pt" + key = idhnu + 200 + ut.bookHist(h, key, title, 25, -0.3, 1.7, 100, -2.0, 0.5) + + +def processFile(fin, noCharm=True): + f = ROOT.TFile.Open(os.environ["EOSSHIP"] + path + fin) + print("opened file ", fin) sTree = f.cbmsim for n in range(sTree.GetEntries()): - sTree.GetEntry(n) - for v in sTree.vetoPoint: - nu = v.GetTrackID() - t = sTree.MCTrack[nu] - pdgCode = t.GetPdgCode() - if abs(pdgCode) not in neutrinos: continue - moID = abs(sTree.MCTrack[t.GetMotherId()].GetPdgCode()) - if moID in charmExtern and noCharm: continue # take heavy flavours from separate production - idhnu=abs(pdgCode)+1000 - if pdgCode<0: idhnu+=1000 - l10ptot = ROOT.TMath.Min(ROOT.TMath.Max(ROOT.TMath.Log10(t.GetP()),-0.3),1.69999) - l10pt = ROOT.TMath.Min(ROOT.TMath.Max(ROOT.TMath.Log10(t.GetPt()),-2.),0.4999) - key = idhnu - h[key].Fill(t.GetP(),weight) - key = idhnu+100 - h[key].Fill(l10ptot,l10pt,weight) - key=idhnu+200 - h[key].Fill(l10ptot,l10pt,weight) + sTree.GetEntry(n) + for v in sTree.vetoPoint: + nu = v.GetTrackID() + t = sTree.MCTrack[nu] + pdgCode = t.GetPdgCode() + if abs(pdgCode) not in neutrinos: + continue + moID = abs(sTree.MCTrack[t.GetMotherId()].GetPdgCode()) + if moID in charmExtern and noCharm: + continue # take heavy flavours from separate production + idhnu = abs(pdgCode) + 1000 + if pdgCode < 0: + idhnu += 1000 + l10ptot = ROOT.TMath.Min( + ROOT.TMath.Max(ROOT.TMath.Log10(t.GetP()), -0.3), 1.69999 + ) + l10pt = ROOT.TMath.Min( + ROOT.TMath.Max(ROOT.TMath.Log10(t.GetPt()), -2.0), 0.4999 + ) + key = idhnu + h[key].Fill(t.GetP(), weight) + key = idhnu + 100 + h[key].Fill(l10ptot, l10pt, weight) + key = idhnu + 200 + h[key].Fill(l10ptot, l10pt, weight) + def run(): - tmp = "pythia8_Geant4_10.0_cXX.root" - global weight - weight = weightMbias - for run in range(0,67000,1000): - rc = processFile(tmp.replace('XX',str(run))) - ut.writeHists(h,'pythia8_Geant4_10.0_c0-67000_nu.root') + tmp = "pythia8_Geant4_10.0_cXX.root" + global weight + weight = weightMbias + for run in range(0, 67000, 1000): + rc = processFile(tmp.replace("XX", str(run))) + ut.writeHists(h, "pythia8_Geant4_10.0_c0-67000_nu.root") + def run1GeV(): - tmp = "pythia8_Geant4_1.0_cXX.root" - global weight - weight = weightMbias1GeV - for run in range(0,19000,1000): - rc = processFile(tmp.replace('XX',str(run))) - ut.writeHists(h,'pythia8_Geant4_1.0_c0-19000_nu.root') + tmp = "pythia8_Geant4_1.0_cXX.root" + global weight + weight = weightMbias1GeV + for run in range(0, 19000, 1000): + rc = processFile(tmp.replace("XX", str(run))) + ut.writeHists(h, "pythia8_Geant4_1.0_c0-19000_nu.root") + def run4Charm(): - tmp = "pythia8_Geant4_charm_XX-YY_10.0.root" - global weight - weight = weightCharm - for cycle in [0,1,2]: - for run in range(0,100,20): - crun = run+cycle*1000 - fname = tmp.replace('XX',str(crun)).replace('YY',str(crun+19)) - rc = processFile(fname,False) - ut.writeHists(h,'pythia8_Geant4_charm_10.0_nu.root') + tmp = "pythia8_Geant4_charm_XX-YY_10.0.root" + global weight + weight = weightCharm + for cycle in [0, 1, 2]: + for run in range(0, 100, 20): + crun = run + cycle * 1000 + fname = tmp.replace("XX", str(crun)).replace("YY", str(crun + 19)) + rc = processFile(fname, False) + ut.writeHists(h, "pythia8_Geant4_charm_10.0_nu.root") + def run4Charm1GeV(): - fname = "pythia8_Geant4_charm_0-19_1.0.root" # renamed pythia8_Geant4_charm_XX-YY_10.0.root - global weight - weight = weightCharm1GeV - rc = processFile(fname,False) - ut.writeHists(h,'pythia8_Geant4_charm_1.0_nu.root') + fname = "pythia8_Geant4_charm_0-19_1.0.root" # renamed pythia8_Geant4_charm_XX-YY_10.0.root + global weight + weight = weightCharm1GeV + rc = processFile(fname, False) + ut.writeHists(h, "pythia8_Geant4_charm_1.0_nu.root") + def run4beauty(): - global weight - weight = weightBeauty - fname = "pythia8_Geant4_beauty_5336B_10.0.root" - rc = processFile(fname,False) - if rc == 0: - fmu = fname.replace('.root',"_mu.root") - rc = os.system("xrdcp "+fmu+" $EOSSHIP/eos/experiment/ship/data/Mbias/background-prod-2018/"+fmu) - if rc != 0: - print("copy to EOS failed, stop",fmu) - else: - rc = os.system("rm "+fmu) + global weight + weight = weightBeauty + fname = "pythia8_Geant4_beauty_5336B_10.0.root" + rc = processFile(fname, False) + if rc == 0: + fmu = fname.replace(".root", "_mu.root") + rc = os.system( + "xrdcp " + + fmu + + " $EOSSHIP/eos/experiment/ship/data/Mbias/background-prod-2018/" + + fmu + ) + if rc != 0: + print("copy to EOS failed, stop", fmu) + else: + rc = os.system("rm " + fmu) + def finalResult(): - h10={} - ut.readHists(h10,'pythia8_Geant4_10.0_c0-67000_nu.root') - h1={} - ut.readHists(h1,'pythia8_Geant4_1.0_c0-19000_nu.root') - c10={} - ut.readHists(c10,'pythia8_Geant4_charm_10.0_nu.root') - c1={} - ut.readHists(c1,'pythia8_Geant4_charm_1.0_nu.root') - cmd = "hadd pythia8_Geant4_10.0_withCharm_nu.root pythia8_Geant4_10.0_c0-67000_nu.root pythia8_Geant4_charm_10.0_nu.root" - os.system(cmd) - cmd = "hadd pythia8_Geant4_1.0_withCharm_nu.root pythia8_Geant4_1.0_c0-19000_nu.root pythia8_Geant4_charm_1.0_nu.root" - os.system(cmd) + h10 = {} + ut.readHists(h10, "pythia8_Geant4_10.0_c0-67000_nu.root") + h1 = {} + ut.readHists(h1, "pythia8_Geant4_1.0_c0-19000_nu.root") + c10 = {} + ut.readHists(c10, "pythia8_Geant4_charm_10.0_nu.root") + c1 = {} + ut.readHists(c1, "pythia8_Geant4_charm_1.0_nu.root") + cmd = "hadd pythia8_Geant4_10.0_withCharm_nu.root pythia8_Geant4_10.0_c0-67000_nu.root pythia8_Geant4_charm_10.0_nu.root" + os.system(cmd) + cmd = "hadd pythia8_Geant4_1.0_withCharm_nu.root pythia8_Geant4_1.0_c0-19000_nu.root pythia8_Geant4_charm_1.0_nu.root" + os.system(cmd) diff --git a/muonShieldOptimization/g4Ex.py b/muonShieldOptimization/g4Ex.py index bc225f6af7..01ef2d918f 100644 --- a/muonShieldOptimization/g4Ex.py +++ b/muonShieldOptimization/g4Ex.py @@ -1,38 +1,42 @@ debug = False -withNtuple = True -muonNuclear = True -model = "QGSP_BERT_EMX" -runnr = 1 -nev = 100 -nevTot = 0 +withNtuple = True +muonNuclear = True +model = "QGSP_BERT_EMX" +runnr = 1 +nev = 100 +nevTot = 0 myEventnr = 0 -mytrack = 1 -scoreLog = 1 -myTimer = {'total':0,'pythia':0,'geant4_conv':0} -ecut = 10 # GeV with 1 : ~1sec / event, with 2: 0.4sec / event, 10: 0.13sec - # pythia = geant4 conversion = 0.4/100 +mytrack = 1 +scoreLog = 1 +myTimer = {"total": 0, "pythia": 0, "geant4_conv": 0} +ecut = 10 # GeV with 1 : ~1sec / event, with 2: 0.4sec / event, 10: 0.13sec +# pythia = geant4 conversion = 0.4/100 # should divide number of events over different ecut values. import os tauOnly = False -if len(os.sys.argv)>1: - runnr = int(os.sys.argv[1]) - nev = int(os.sys.argv[2]) - ecut = float(os.sys.argv[3]) - if len(os.sys.argv)>4: tauOnly = True +if len(os.sys.argv) > 1: + runnr = int(os.sys.argv[1]) + nev = int(os.sys.argv[2]) + ecut = float(os.sys.argv[3]) + if len(os.sys.argv) > 4: + tauOnly = True +import time + +import g4py.ezgeom +import g4py.NISTmaterials # ================================================================== # ROOT IMPORT # # ================================================================== -import ROOT,time -from ROOT import TLorentzVector +import ROOT +from g4py.ezgeom import G4EzVolume # ================================================================== # GEANT4 IMPORT # # ================================================================== from Geant4 import * -import g4py.NISTmaterials -import g4py.ezgeom -from g4py.ezgeom import G4EzVolume +from ROOT import TLorentzVector + # ================================================================== # PYTHIA8 PART # # ================================================================== @@ -40,7 +44,7 @@ ROOT.gSystem.Load("libpythia8") ROOT.gSystem.Load("libEGPythia8") myPythia = ROOT.TPythia8() -rnr = ROOT.TRandom() +rnr = ROOT.TRandom() # Configure myPythia.listAll() # myPythia.list(431) @@ -52,35 +56,42 @@ myPythia.ReadString("PromptPhoton:all = on") myPythia.ReadString("WeakBosonExchange:all = on") # http://home.thep.lu.se/~torbjorn/pythia81html/ParticleDecays.html -if tauOnly : - myPythia.ReadString("431:new D_s+ D_s- 1 3 0 1.96849 0.00000 0.00000 0.00000 1.49900e-01 0 1 0 1 0") - myPythia.ReadString("431:addChannel = 1 0.0640000 0 -15 16") +if tauOnly: + myPythia.ReadString( + "431:new D_s+ D_s- 1 3 0 1.96849 0.00000 0.00000 0.00000 1.49900e-01 0 1 0 1 0" + ) + myPythia.ReadString("431:addChannel = 1 0.0640000 0 -15 16") # set random number seed myPythia.ReadString("Random:setSeed = On") -R = int(time.time()%900000000) -myPythia.ReadString("Random:seed = "+str(R)) +R = int(time.time() % 900000000) +myPythia.ReadString("Random:seed = " + str(R)) # Initialize proton (400GeV) on proton at rest -myPythia.Initialize(2212,2212,400.,0.) # required to hack TPythia8 in root ! +myPythia.Initialize(2212, 2212, 400.0, 0.0) # required to hack TPythia8 in root ! # W = 74 protons and 184-74= 110 neutrons -if tauOnly: myPythia.Plist(431) +if tauOnly: + myPythia.Plist(431) # Open an output file h = {} if withNtuple: - f = ROOT.TFile.Open('pythia8_Geant4_'+str(runnr)+'_'+str(ecut)+'.root', 'RECREATE') - h['ntuple'] = ROOT.TNtuple("pythia8-Geant4","muon/nu flux","id:px:py:pz:x:y:z:pythiaid:parentid") + f = ROOT.TFile.Open( + "pythia8_Geant4_" + str(runnr) + "_" + str(ecut) + ".root", "RECREATE" + ) + h["ntuple"] = ROOT.TNtuple( + "pythia8-Geant4", "muon/nu flux", "id:px:py:pz:x:y:z:pythiaid:parentid" + ) -leptons = [12,13,14,15,16] # nu_e, mu, nu_mu, tau, nu_tau -pionkaons = [211,321] -rest = [130,310,3122] -allPart = [] +leptons = [12, 13, 14, 15, 16] # nu_e, mu, nu_mu, tau, nu_tau +pionkaons = [211, 321] +rest = [130, 310, 3122] +allPart = [] allPart.extend(leptons) allPart.extend(pionkaons) allPart.extend(rest) -notWanted = [22,11,-11,990] +notWanted = [22, 11, -11, 990] # ================================================================== # Geant4 PART # # ================================================================== @@ -90,215 +101,256 @@ rand_engine = Ranlux64Engine() HepRandom.setTheEngine(rand_engine) HepRandom.setTheSeed(runnr) + + # ================================================================== # user actions in python # ================================================================== # ------------------------------------------------------------------ class MyGeneratorAction(G4VUserPrimaryGeneratorAction): - " My Generator Action" - def GeneratePrimaries(self,anEvent): - global debug,nevTot - t_0 = time.time() - npart = 0 - while npart == 0: - myPythia.GenerateEvent() - nevTot+=1 - myTimer['pythia']+=time.time()-t_0 -# pythia interaction happens at 0,0,0 - #x = rnr.Uniform(-3.,3.) - #y = rnr.Uniform(-3.,3.) - # leave this smearing for later - pos = G4ThreeVector(0*cm, 0*cm, -50*m) - vertex = G4PrimaryVertex(pos,0.) - # create new primaries and set them to the vertex - particles = myPythia.GetListOfParticles() - for p in particles: - if p.GetStatusCode()!=1 : continue - pid = p.GetPdgCode() - if tauOnly and abs(pid) != 16: continue - if pid in notWanted : continue - G4particle = G4PrimaryParticle( pid ) - v = TLorentzVector() - p.Momentum(v) - if v.E()*GeV < ecut : continue - G4particle.Set4Momentum( v.Px()*GeV,v.Py()*GeV,v.Pz()*GeV,v.E()*GeV ) - vertex.SetPrimary( G4particle ) -# store mother ID - mkey = p.GetMother(0)+1 - mother = myPythia.GetParticle(mkey) - curPid = p.GetPdgCode() + 10000 # make it positive - moPid = mother.GetPdgCode() + 10000 - w = curPid + moPid * 100000 - G4particle.SetWeight(w) - npart += 1 - if tauOnly and debug: myPythia.EventListing() - anEvent.AddPrimaryVertex( vertex ) - myTimer['geant4_conv']+=time.time()-t_0 + "My Generator Action" + + def GeneratePrimaries(self, anEvent): + global debug, nevTot + t_0 = time.time() + npart = 0 + while npart == 0: + myPythia.GenerateEvent() + nevTot += 1 + myTimer["pythia"] += time.time() - t_0 + # pythia interaction happens at 0,0,0 + # x = rnr.Uniform(-3.,3.) + # y = rnr.Uniform(-3.,3.) + # leave this smearing for later + pos = G4ThreeVector(0 * cm, 0 * cm, -50 * m) + vertex = G4PrimaryVertex(pos, 0.0) + # create new primaries and set them to the vertex + particles = myPythia.GetListOfParticles() + for p in particles: + if p.GetStatusCode() != 1: + continue + pid = p.GetPdgCode() + if tauOnly and abs(pid) != 16: + continue + if pid in notWanted: + continue + G4particle = G4PrimaryParticle(pid) + v = TLorentzVector() + p.Momentum(v) + if v.E() * GeV < ecut: + continue + G4particle.Set4Momentum( + v.Px() * GeV, v.Py() * GeV, v.Pz() * GeV, v.E() * GeV + ) + vertex.SetPrimary(G4particle) + # store mother ID + mkey = p.GetMother(0) + 1 + mother = myPythia.GetParticle(mkey) + curPid = p.GetPdgCode() + 10000 # make it positive + moPid = mother.GetPdgCode() + 10000 + w = curPid + moPid * 100000 + G4particle.SetWeight(w) + npart += 1 + if tauOnly and debug: + myPythia.EventListing() + anEvent.AddPrimaryVertex(vertex) + myTimer["geant4_conv"] += time.time() - t_0 + + class MyRunAction(G4UserRunAction): - "My Run Action" - - def EndOfRunAction(self, run): - global debug,nevTot - print("*** End of Run") - print("- Run summary : (id= %d, #events= %d)" \ - % (run.GetRunID(), nevTot)) - h['ntuple'].Fill(-1., float(nevTot) ) - h['ntuple'].Write() - print('lepton masses used') - for l in leptons: - G4particle = G4PrimaryParticle( l ) - G4def = G4particle.GetParticleDefinition() - print(l, G4def.GetParticleName(), G4particle.GetMass()) + "My Run Action" + + def EndOfRunAction(self, run): + global debug, nevTot + print("*** End of Run") + print("- Run summary : (id= %d, #events= %d)" % (run.GetRunID(), nevTot)) + h["ntuple"].Fill(-1.0, float(nevTot)) + h["ntuple"].Write() + print("lepton masses used") + for l in leptons: + G4particle = G4PrimaryParticle(l) + G4def = G4particle.GetParticleDefinition() + print(l, G4def.GetParticleName(), G4particle.GetMass()) + # ------------------------------------------------------------------ class MyEventAction(G4UserEventAction): - "My Event Action" - def EndOfEventAction(self, event): - global myEventnr - myEventnr += 1 - # self.myPrintout(event) - def myPrintout(self, event): - prim = event.GetPrimaryVertex() - print('vertex ',prim.GetX0()/m,prim.GetY0()/m,prim.GetZ0()/m) - for k in range( prim.GetNumberOfParticle() ): - p = prim.GetPrimary(k) - print('event',p.GetPDGcode(),p.GetPx()/GeV,p.GetPy()/GeV,p.GetPz()/GeV) + "My Event Action" + + def EndOfEventAction(self, event): + global myEventnr + myEventnr += 1 + # self.myPrintout(event) + + def myPrintout(self, event): + prim = event.GetPrimaryVertex() + print("vertex ", prim.GetX0() / m, prim.GetY0() / m, prim.GetZ0() / m) + for k in range(prim.GetNumberOfParticle()): + p = prim.GetPrimary(k) + print( + "event", + p.GetPDGcode(), + p.GetPx() / GeV, + p.GetPy() / GeV, + p.GetPz() / GeV, + ) + + # ------------------------------------------------------------------ class MySteppingAction(G4UserSteppingAction): - "My Stepping Action" + "My Stepping Action" + + def UserSteppingAction(self, step): + pass - def UserSteppingAction(self, step): - pass # ------------------------------------------------------------------ class MyTrackingAction(G4UserTrackingAction): - def PostUserTrackingAction(self,atrack): - pass - def PreUserTrackingAction(self,atrack): - # self.myPrintout(atrack) - if atrack.GetTotalEnergy()/GeV < ecut : - G4TrackingManager().SetStoreTrajectory(False) - atrack.SetTrackStatus(atrack.GetTrackStatus().fStopAndKill) - part = atrack.GetDynamicParticle() - pid = part.GetPDGcode() - if pid in notWanted: - G4TrackingManager().SetStoreTrajectory(False) - atrack.SetTrackStatus(atrack.GetTrackStatus().fStopAndKill) - - def myPrintout(self, atrack): - part = atrack.GetDynamicParticle() - pid = part.GetPDGcode() - print('TA',pid,atrack.GetTotalEnergy()/GeV,ecut*GeV) + def PostUserTrackingAction(self, atrack): + pass + + def PreUserTrackingAction(self, atrack): + # self.myPrintout(atrack) + if atrack.GetTotalEnergy() / GeV < ecut: + G4TrackingManager().SetStoreTrajectory(False) + atrack.SetTrackStatus(atrack.GetTrackStatus().fStopAndKill) + part = atrack.GetDynamicParticle() + pid = part.GetPDGcode() + if pid in notWanted: + G4TrackingManager().SetStoreTrajectory(False) + atrack.SetTrackStatus(atrack.GetTrackStatus().fStopAndKill) + + def myPrintout(self, atrack): + part = atrack.GetDynamicParticle() + pid = part.GetPDGcode() + print("TA", pid, atrack.GetTotalEnergy() / GeV, ecut * GeV) + # ------------------------------------------------------------------ class ScoreSD(G4VSensitiveDetector): - "SD for score voxels" - - def __init__(self,Name): - G4VSensitiveDetector.__init__(self, Name) - - def ProcessHits(self, step, rohist): - preStepPoint = step.GetPreStepPoint() - track = step.GetTrack() - part = track.GetDynamicParticle() - pid = part.GetPDGcode() - if abs(pid) in leptons : - mom = track.GetMomentum() - pos = track.GetPosition() -# - # primPart = part.GetPrimaryParticle() - w = track.GetWeight() - parentid = int(w)/100000-10000 - pythiaid = int(w)%100000-10000 - h['ntuple'].Fill(float(pid), float(mom.x/GeV),float(mom.y/GeV),float(mom.z/GeV), - float(pos.x/m),float(pos.y/m),float(pos.z/m),pythiaid,parentid) - #print 'xxx',pid, float(mom.x/GeV),float(mom.y/GeV),float(mom.z/GeV),pythiaid,parentid,float(pos.x/m),float(pos.y/m),float(pos.z/m) - #myPythia.EventListing() + "SD for score voxels" + + def __init__(self, Name): + G4VSensitiveDetector.__init__(self, Name) + + def ProcessHits(self, step, rohist): + preStepPoint = step.GetPreStepPoint() + track = step.GetTrack() + part = track.GetDynamicParticle() + pid = part.GetPDGcode() + if abs(pid) in leptons: + mom = track.GetMomentum() + pos = track.GetPosition() + # + # primPart = part.GetPrimaryParticle() + w = track.GetWeight() + parentid = int(w) / 100000 - 10000 + pythiaid = int(w) % 100000 - 10000 + h["ntuple"].Fill( + float(pid), + float(mom.x / GeV), + float(mom.y / GeV), + float(mom.z / GeV), + float(pos.x / m), + float(pos.y / m), + float(pos.z / m), + pythiaid, + parentid, + ) + # print 'xxx',pid, float(mom.x/GeV),float(mom.y/GeV),float(mom.z/GeV),pythiaid,parentid,float(pos.x/m),float(pos.y/m),float(pos.z/m) + # myPythia.EventListing() + def ConstructGeom(): - print("* Constructing geometry...") - world_r = 100.*m - # reset world material - vac = G4Material.GetMaterial("G4_Galactic") - g4py.ezgeom.SetWorldMaterial(vac) - g4py.ezgeom.ResizeWorld(world_r, world_r, world_r) - # a snoopy world is placed - global snoopy,snoopyPhys,scoreLog - snoopy = G4EzVolume("Snoopy") - snoopy.CreateTubeVolume(vac, 0., 10*m, 50.*m) - snoopyPhys = snoopy.PlaceIt(G4ThreeVector(0.,0.,0.*m)) - snoopyLog = snoopyPhys.GetLogicalVolume() - snoopy.SetVisibility(False) - # a target box is placed - global target,targetPhys - iron = G4Material.GetMaterial("G4_Fe") - air = G4Material.GetMaterial("G4_AIR") - tungsten = G4Material.GetMaterial("G4_W") - lead = G4Material.GetMaterial("G4_Pb") - alum = G4Material.GetMaterial("G4_Al") - target = G4EzVolume("Target") - target.CreateTubeVolume(tungsten, 0., 25.*cm, 25.*cm) - targetPhys = target.PlaceIt(G4ThreeVector(0.,0.,-50.*m+25.*cm),1,snoopy) - target.SetColor(G4Color(0.0,0.5,0.5,1.0)) - target.SetVisibility(True) - # = 0.1m3 = 2t - # a hadron absorber is placed - absorber = G4EzVolume("Absorber") -# iron alloys saturate at 1.6-2.2T - # inner radius outer radius length - absorber.CreateTubeVolume(iron, 0., 100.*cm, 150.*cm) - absorberPhys = absorber.PlaceIt(G4ThreeVector(0.,0.,-50*m+2*25.*cm+150.*cm),1,snoopy) - absorber.SetColor(G4Color(0.898,0.902,0.91,1.0)) - absorber.SetVisibility(True) - xx = G4VisAttributes() - xx.SetForceWireframe(True) - absorberlog = absorberPhys.GetLogicalVolume() - absorberlog.SetVisAttributes(xx) -# scoring plane - scorez = -50.*m+2*25.*cm+2*150.*cm+1*mm - score = G4EzVolume("Score") - score.CreateTubeVolume(vac, 0., 50.*m, 1.*mm) - scorePhys = score.PlaceIt(G4ThreeVector(0.,0.,scorez),1,snoopy) - scoreLog = scorePhys.GetLogicalVolume() - g4py.ezgeom.Construct() + print("* Constructing geometry...") + world_r = 100.0 * m + # reset world material + vac = G4Material.GetMaterial("G4_Galactic") + g4py.ezgeom.SetWorldMaterial(vac) + g4py.ezgeom.ResizeWorld(world_r, world_r, world_r) + # a snoopy world is placed + global snoopy, snoopyPhys, scoreLog + snoopy = G4EzVolume("Snoopy") + snoopy.CreateTubeVolume(vac, 0.0, 10 * m, 50.0 * m) + snoopyPhys = snoopy.PlaceIt(G4ThreeVector(0.0, 0.0, 0.0 * m)) + snoopyLog = snoopyPhys.GetLogicalVolume() + snoopy.SetVisibility(False) + # a target box is placed + global target, targetPhys + iron = G4Material.GetMaterial("G4_Fe") + air = G4Material.GetMaterial("G4_AIR") + tungsten = G4Material.GetMaterial("G4_W") + lead = G4Material.GetMaterial("G4_Pb") + alum = G4Material.GetMaterial("G4_Al") + target = G4EzVolume("Target") + target.CreateTubeVolume(tungsten, 0.0, 25.0 * cm, 25.0 * cm) + targetPhys = target.PlaceIt( + G4ThreeVector(0.0, 0.0, -50.0 * m + 25.0 * cm), 1, snoopy + ) + target.SetColor(G4Color(0.0, 0.5, 0.5, 1.0)) + target.SetVisibility(True) + # = 0.1m3 = 2t + # a hadron absorber is placed + absorber = G4EzVolume("Absorber") + # iron alloys saturate at 1.6-2.2T + # inner radius outer radius length + absorber.CreateTubeVolume(iron, 0.0, 100.0 * cm, 150.0 * cm) + absorberPhys = absorber.PlaceIt( + G4ThreeVector(0.0, 0.0, -50 * m + 2 * 25.0 * cm + 150.0 * cm), 1, snoopy + ) + absorber.SetColor(G4Color(0.898, 0.902, 0.91, 1.0)) + absorber.SetVisibility(True) + xx = G4VisAttributes() + xx.SetForceWireframe(True) + absorberlog = absorberPhys.GetLogicalVolume() + absorberlog.SetVisAttributes(xx) + # scoring plane + scorez = -50.0 * m + 2 * 25.0 * cm + 2 * 150.0 * cm + 1 * mm + score = G4EzVolume("Score") + score.CreateTubeVolume(vac, 0.0, 50.0 * m, 1.0 * mm) + scorePhys = score.PlaceIt(G4ThreeVector(0.0, 0.0, scorez), 1, snoopy) + scoreLog = scorePhys.GetLogicalVolume() + g4py.ezgeom.Construct() + g4py.NISTmaterials.Construct() -#print Geant4.gMaterialTable +# print Geant4.gMaterialTable if not muonNuclear: - physList = Geant4.FTFP_BERT() - gRunManager.SetUserInitialization(physList) + physList = Geant4.FTFP_BERT() + gRunManager.SetUserInitialization(physList) # with muon nuclear else: - if 'G4PhysListFactory' in dir(G4physicslists): - factory = G4physicslists.G4PhysListFactory() - xx = factory.GetReferencePhysList(model) - else: xx = G4physicslists.GetReferencePhysList(model) - gRunManager.SetUserInitialization(xx) + if "G4PhysListFactory" in dir(G4physicslists): + factory = G4physicslists.G4PhysListFactory() + xx = factory.GetReferencePhysList(model) + else: + xx = G4physicslists.GetReferencePhysList(model) + gRunManager.SetUserInitialization(xx) myGE = MyGeneratorAction() gRunManager.SetUserAction(myGE) # -myTA= MyTrackingAction() +myTA = MyTrackingAction() gRunManager.SetUserAction(myTA) # ConstructGeom() -myRA= MyRunAction() +myRA = MyRunAction() gRunManager.SetUserAction(myRA) -myEA= MyEventAction() +myEA = MyEventAction() gRunManager.SetUserAction(myEA) # initialize gRunManager.Initialize() # scoring should be set after geometry construction -sens = ScoreSD('Score') +sens = ScoreSD("Score") scoreLog.SetSensitiveDetector(sens) t0 = time.time() gRunManager.BeamOn(nev) t1 = time.time() -print('Time used',t1-t0, ' seconds') +print("Time used", t1 - t0, " seconds") for x in myTimer: - print(x,myTimer[x]) + print(x, myTimer[x]) diff --git a/muonShieldOptimization/g4Ex_args.py b/muonShieldOptimization/g4Ex_args.py index fc4fc7633c..f7cee1a748 100755 --- a/muonShieldOptimization/g4Ex_args.py +++ b/muonShieldOptimization/g4Ex_args.py @@ -1,91 +1,116 @@ #!/usr/bin/env python debug = False -withNtuple = True -muonNuclear = True -model = "QGSP_BERT_EMX" -runnr = 1 -nev = 100 -nevTot = 0 +withNtuple = True +muonNuclear = True +model = "QGSP_BERT_EMX" +runnr = 1 +nev = 100 +nevTot = 0 myEventnr = 0 -mytrack = 1 -scoreLog = 1 -myTimer = {'total':0,'pythia':0,'geant4_conv':0} -tauOnly = False -work_dir = "./" -ecut = 10 # GeV with 1 : ~1sec / event, with 2: 0.4sec / event, 10: 0.13sec - # pythia = geant4 conversion = 0.4/100 +mytrack = 1 +scoreLog = 1 +myTimer = {"total": 0, "pythia": 0, "geant4_conv": 0} +tauOnly = False +work_dir = "./" +ecut = 10 # GeV with 1 : ~1sec / event, with 2: 0.4sec / event, 10: 0.13sec +import argparse +import logging +# pythia = geant4 conversion = 0.4/100 # should divide number of events over different ecut values. import os import shutil -import argparse -import logging + logging.info("") logger = logging.getLogger(os.path.splitext(os.path.basename(os.sys.argv[0]))[0]) logger.setLevel(logging.INFO) def get_work_dir(run_number): - import socket - host = socket.gethostname() - job_base_name = os.path.splitext(os.path.basename(os.sys.argv[0]))[0] - out_dir = "{host}_{base}_{runnr}".format(host=host, base=job_base_name, runnr=run_number) - return out_dir + import socket + + host = socket.gethostname() + job_base_name = os.path.splitext(os.path.basename(os.sys.argv[0]))[0] + out_dir = "{host}_{base}_{runnr}".format( + host=host, base=job_base_name, runnr=run_number + ) + return out_dir def init(): - global runnr, nev, ecut, tauOnly, work_dir - logger.info("SHiP proton-on-taget simulator (C) Thomas Ruf, 2014") - - ap = argparse.ArgumentParser( - description='Run SHiP "pot" simulation') - ap.add_argument('-d', '--debug', action='store_true') - ap.add_argument('-f', '--force', action='store_true', help="force overwriting output directory") - ap.add_argument('-r', '--run-number', type=int, dest='runnr', default=runnr) - ap.add_argument('-e', '--ecut', type=float, help="energy cut", dest='ecut', default=ecut) - ap.add_argument('-n', '--num-events', type=int, help="number of events to generate", dest='nev', default=nev) - ap.add_argument('-t', '--tau-only', action='store_true', dest='tauOnly') - ap.add_argument('-o', '--output', type=str, help="output directory", dest='work_dir', default=None) - args = ap.parse_args() - if args.debug: - logger.setLevel(logging.DEBUG) - runnr = args.runnr - nev = args.nev - ecut = args.ecut - tauOnly = args.tauOnly - if args.work_dir is None: - args.work_dir = get_work_dir(runnr) - work_dir = args.work_dir - logger.info("params: %s" % args) - logger.debug("work_dir: %s" % work_dir) - logger.debug("command line arguments: %s", args) - if os.path.exists(work_dir): - logger.warn("output directory '%s' already exists." % work_dir) - if args.force: - logger.warn("...cleaning") - for root, dirs, files in os.walk(work_dir): - for f in files: - os.unlink(os.path.join(root, f)) - for d in dirs: - shutil.rmtree(os.path.join(root, d)) + global runnr, nev, ecut, tauOnly, work_dir + logger.info("SHiP proton-on-taget simulator (C) Thomas Ruf, 2014") + + ap = argparse.ArgumentParser(description='Run SHiP "pot" simulation') + ap.add_argument("-d", "--debug", action="store_true") + ap.add_argument( + "-f", "--force", action="store_true", help="force overwriting output directory" + ) + ap.add_argument("-r", "--run-number", type=int, dest="runnr", default=runnr) + ap.add_argument( + "-e", "--ecut", type=float, help="energy cut", dest="ecut", default=ecut + ) + ap.add_argument( + "-n", + "--num-events", + type=int, + help="number of events to generate", + dest="nev", + default=nev, + ) + ap.add_argument("-t", "--tau-only", action="store_true", dest="tauOnly") + ap.add_argument( + "-o", + "--output", + type=str, + help="output directory", + dest="work_dir", + default=None, + ) + args = ap.parse_args() + if args.debug: + logger.setLevel(logging.DEBUG) + runnr = args.runnr + nev = args.nev + ecut = args.ecut + tauOnly = args.tauOnly + if args.work_dir is None: + args.work_dir = get_work_dir(runnr) + work_dir = args.work_dir + logger.info("params: %s" % args) + logger.debug("work_dir: %s" % work_dir) + logger.debug("command line arguments: %s", args) + if os.path.exists(work_dir): + logger.warn("output directory '%s' already exists." % work_dir) + if args.force: + logger.warn("...cleaning") + for root, dirs, files in os.walk(work_dir): + for f in files: + os.unlink(os.path.join(root, f)) + for d in dirs: + shutil.rmtree(os.path.join(root, d)) + else: + logger.warn("...use '-f' option to overwrite it") else: - logger.warn("...use '-f' option to overwrite it") - else: - os.makedirs(work_dir) + os.makedirs(work_dir) + init() os.chdir(work_dir) +import time + +import g4py.ezgeom +import g4py.NISTmaterials # ================================================================== # ROOT IMPORT # # ================================================================== -import ROOT,time -from ROOT import TLorentzVector +import ROOT +from g4py.ezgeom import G4EzVolume # ================================================================== # GEANT4 IMPORT # # ================================================================== from Geant4 import * -import g4py.NISTmaterials -import g4py.ezgeom -from g4py.ezgeom import G4EzVolume +from ROOT import TLorentzVector + # ================================================================== # PYTHIA8 PART # # ================================================================== @@ -93,7 +118,7 @@ def init(): ROOT.gSystem.Load("libpythia8") ROOT.gSystem.Load("libEGPythia8") myPythia = ROOT.TPythia8() -rnr = ROOT.TRandom() +rnr = ROOT.TRandom() # Configure myPythia.listAll() # myPythia.list(431) @@ -105,35 +130,42 @@ def init(): myPythia.ReadString("PromptPhoton:all = on") myPythia.ReadString("WeakBosonExchange:all = on") # http://home.thep.lu.se/~torbjorn/pythia81html/ParticleDecays.html -if tauOnly : - myPythia.ReadString("431:new D_s+ D_s- 1 3 0 1.96849 0.00000 0.00000 0.00000 1.49900e-01 0 1 0 1 0") - myPythia.ReadString("431:addChannel = 1 0.0640000 0 -15 16") +if tauOnly: + myPythia.ReadString( + "431:new D_s+ D_s- 1 3 0 1.96849 0.00000 0.00000 0.00000 1.49900e-01 0 1 0 1 0" + ) + myPythia.ReadString("431:addChannel = 1 0.0640000 0 -15 16") # set random number seed myPythia.ReadString("Random:setSeed = On") R = int(time.time() % 900000000) -myPythia.ReadString("Random:seed = "+str(R)) +myPythia.ReadString("Random:seed = " + str(R)) # Initialize proton (400GeV) on proton at rest -myPythia.Initialize(2212, 2212, 400., 0.) # required to hack TPythia8 in root ! +myPythia.Initialize(2212, 2212, 400.0, 0.0) # required to hack TPythia8 in root ! # W = 74 protons and 184-74= 110 neutrons -if tauOnly: myPythia.plist(431) +if tauOnly: + myPythia.plist(431) # Open an output file h = {} if withNtuple: - f = ROOT.TFile.Open('pythia8_Geant4_'+str(runnr)+'_'+str(ecut)+'.root', 'RECREATE') - h['ntuple'] = ROOT.TNtuple("pythia8-Geant4","muon/nu flux","id:px:py:pz:x:y:z:pythiaid:parentid") + f = ROOT.TFile.Open( + "pythia8_Geant4_" + str(runnr) + "_" + str(ecut) + ".root", "RECREATE" + ) + h["ntuple"] = ROOT.TNtuple( + "pythia8-Geant4", "muon/nu flux", "id:px:py:pz:x:y:z:pythiaid:parentid" + ) -leptons = [12,13,14,15,16] # nu_e, mu, nu_mu, tau, nu_tau -pionkaons = [211,321] -rest = [130,310,3122] -allPart = [] +leptons = [12, 13, 14, 15, 16] # nu_e, mu, nu_mu, tau, nu_tau +pionkaons = [211, 321] +rest = [130, 310, 3122] +allPart = [] allPart.extend(leptons) allPart.extend(pionkaons) allPart.extend(rest) -notWanted = [22,11,-11,990] +notWanted = [22, 11, -11, 990] # ================================================================== # Geant4 PART # # ================================================================== @@ -150,212 +182,251 @@ def init(): class MyGeneratorAction(G4VUserPrimaryGeneratorAction): - " My Generator Action" - def GeneratePrimaries(self,anEvent): - global debug,nevTot - t_0 = time.time() - npart = 0 - while npart == 0: - myPythia.GenerateEvent() - nevTot+=1 - myTimer['pythia']+=time.time()-t_0 -# pythia interaction happens at 0,0,0 - #x = rnr.Uniform(-3.,3.) - #y = rnr.Uniform(-3.,3.) - # leave this smearing for later - pos = G4ThreeVector(0*cm, 0*cm, -50*m) - vertex = G4PrimaryVertex(pos,0.) - # create new primaries and set them to the vertex - particles = myPythia.GetListOfParticles() - for p in particles: - if p.GetStatusCode()!=1 : continue - pid = p.GetPdgCode() - if tauOnly and abs(pid) != 16: continue - if pid in notWanted : continue - G4particle = G4PrimaryParticle( pid ) - v = TLorentzVector() - p.Momentum(v) - if v.E()*GeV < ecut : continue - G4particle.Set4Momentum( v.Px()*GeV,v.Py()*GeV,v.Pz()*GeV,v.E()*GeV ) - vertex.SetPrimary( G4particle ) -# store mother ID - mkey = p.GetMother(0)+1 - mother = myPythia.GetParticle(mkey) - curPid = p.GetPdgCode() + 10000 # make it positive - moPid = mother.GetPdgCode() + 10000 - w = curPid + moPid * 100000 - G4particle.SetWeight(w) - npart += 1 - if tauOnly and debug: myPythia.EventListing() - anEvent.AddPrimaryVertex( vertex ) - myTimer['geant4_conv']+=time.time()-t_0 + "My Generator Action" + + def GeneratePrimaries(self, anEvent): + global debug, nevTot + t_0 = time.time() + npart = 0 + while npart == 0: + myPythia.GenerateEvent() + nevTot += 1 + myTimer["pythia"] += time.time() - t_0 + # pythia interaction happens at 0,0,0 + # x = rnr.Uniform(-3.,3.) + # y = rnr.Uniform(-3.,3.) + # leave this smearing for later + pos = G4ThreeVector(0 * cm, 0 * cm, -50 * m) + vertex = G4PrimaryVertex(pos, 0.0) + # create new primaries and set them to the vertex + particles = myPythia.GetListOfParticles() + for p in particles: + if p.GetStatusCode() != 1: + continue + pid = p.GetPdgCode() + if tauOnly and abs(pid) != 16: + continue + if pid in notWanted: + continue + G4particle = G4PrimaryParticle(pid) + v = TLorentzVector() + p.Momentum(v) + if v.E() * GeV < ecut: + continue + G4particle.Set4Momentum( + v.Px() * GeV, v.Py() * GeV, v.Pz() * GeV, v.E() * GeV + ) + vertex.SetPrimary(G4particle) + # store mother ID + mkey = p.GetMother(0) + 1 + mother = myPythia.GetParticle(mkey) + curPid = p.GetPdgCode() + 10000 # make it positive + moPid = mother.GetPdgCode() + 10000 + w = curPid + moPid * 100000 + G4particle.SetWeight(w) + npart += 1 + if tauOnly and debug: + myPythia.EventListing() + anEvent.AddPrimaryVertex(vertex) + myTimer["geant4_conv"] += time.time() - t_0 + + class MyRunAction(G4UserRunAction): - "My Run Action" - - def EndOfRunAction(self, run): - global debug,nevTot - print("*** End of Run") - print("- Run summary : (id= %d, #events= %d)" \ - % (run.GetRunID(), nevTot)) - h['ntuple'].Fill(-1., float(nevTot) ) - h['ntuple'].Write() - print('lepton masses used') - for l in leptons: - G4particle = G4PrimaryParticle( l ) - G4def = G4particle.GetParticleDefinition() - print(l, G4def.GetParticleName(), G4particle.GetMass()) + "My Run Action" + + def EndOfRunAction(self, run): + global debug, nevTot + print("*** End of Run") + print("- Run summary : (id= %d, #events= %d)" % (run.GetRunID(), nevTot)) + h["ntuple"].Fill(-1.0, float(nevTot)) + h["ntuple"].Write() + print("lepton masses used") + for l in leptons: + G4particle = G4PrimaryParticle(l) + G4def = G4particle.GetParticleDefinition() + print(l, G4def.GetParticleName(), G4particle.GetMass()) + # ------------------------------------------------------------------ class MyEventAction(G4UserEventAction): - "My Event Action" - def EndOfEventAction(self, event): - global myEventnr - myEventnr += 1 - # self.myPrintout(event) - def myPrintout(self, event): - prim = event.GetPrimaryVertex() - print('vertex ',prim.GetX0()/m,prim.GetY0()/m,prim.GetZ0()/m) - for k in range( prim.GetNumberOfParticle() ): - p = prim.GetPrimary(k) - print('event',p.GetPDGcode(),p.GetPx()/GeV,p.GetPy()/GeV,p.GetPz()/GeV) + "My Event Action" + + def EndOfEventAction(self, event): + global myEventnr + myEventnr += 1 + # self.myPrintout(event) + + def myPrintout(self, event): + prim = event.GetPrimaryVertex() + print("vertex ", prim.GetX0() / m, prim.GetY0() / m, prim.GetZ0() / m) + for k in range(prim.GetNumberOfParticle()): + p = prim.GetPrimary(k) + print( + "event", + p.GetPDGcode(), + p.GetPx() / GeV, + p.GetPy() / GeV, + p.GetPz() / GeV, + ) + + # ------------------------------------------------------------------ class MySteppingAction(G4UserSteppingAction): - "My Stepping Action" + "My Stepping Action" + + def UserSteppingAction(self, step): + pass - def UserSteppingAction(self, step): - pass # ------------------------------------------------------------------ class MyTrackingAction(G4UserTrackingAction): - def PostUserTrackingAction(self,atrack): - pass - def PreUserTrackingAction(self,atrack): - # self.myPrintout(atrack) - if atrack.GetTotalEnergy()/GeV < ecut : - G4TrackingManager().SetStoreTrajectory(False) - atrack.SetTrackStatus(atrack.GetTrackStatus().fStopAndKill) - part = atrack.GetDynamicParticle() - pid = part.GetPDGcode() - if pid in notWanted: - G4TrackingManager().SetStoreTrajectory(False) - atrack.SetTrackStatus(atrack.GetTrackStatus().fStopAndKill) - - def myPrintout(self, atrack): - part = atrack.GetDynamicParticle() - pid = part.GetPDGcode() - print('TA',pid,atrack.GetTotalEnergy()/GeV,ecut*GeV) + def PostUserTrackingAction(self, atrack): + pass + + def PreUserTrackingAction(self, atrack): + # self.myPrintout(atrack) + if atrack.GetTotalEnergy() / GeV < ecut: + G4TrackingManager().SetStoreTrajectory(False) + atrack.SetTrackStatus(atrack.GetTrackStatus().fStopAndKill) + part = atrack.GetDynamicParticle() + pid = part.GetPDGcode() + if pid in notWanted: + G4TrackingManager().SetStoreTrajectory(False) + atrack.SetTrackStatus(atrack.GetTrackStatus().fStopAndKill) + + def myPrintout(self, atrack): + part = atrack.GetDynamicParticle() + pid = part.GetPDGcode() + print("TA", pid, atrack.GetTotalEnergy() / GeV, ecut * GeV) + # ------------------------------------------------------------------ class ScoreSD(G4VSensitiveDetector): - "SD for score voxels" - - def __init__(self,Name): - G4VSensitiveDetector.__init__(self, Name) - - def ProcessHits(self, step, rohist): - preStepPoint = step.GetPreStepPoint() - track = step.GetTrack() - part = track.GetDynamicParticle() - pid = part.GetPDGcode() - if abs(pid) in leptons : - mom = track.GetMomentum() - pos = track.GetPosition() -# - # primPart = part.GetPrimaryParticle() - w = track.GetWeight() - parentid = int(w)/100000-10000 - pythiaid = int(w)%100000-10000 - h['ntuple'].Fill(float(pid), float(mom.x/GeV),float(mom.y/GeV),float(mom.z/GeV), - float(pos.x/m),float(pos.y/m),float(pos.z/m),pythiaid,parentid) - #print 'xxx',pid, float(mom.x/GeV),float(mom.y/GeV),float(mom.z/GeV),pythiaid,parentid,float(pos.x/m),float(pos.y/m),float(pos.z/m) - #myPythia.EventListing() + "SD for score voxels" + + def __init__(self, Name): + G4VSensitiveDetector.__init__(self, Name) + + def ProcessHits(self, step, rohist): + preStepPoint = step.GetPreStepPoint() + track = step.GetTrack() + part = track.GetDynamicParticle() + pid = part.GetPDGcode() + if abs(pid) in leptons: + mom = track.GetMomentum() + pos = track.GetPosition() + # + # primPart = part.GetPrimaryParticle() + w = track.GetWeight() + parentid = int(w) / 100000 - 10000 + pythiaid = int(w) % 100000 - 10000 + h["ntuple"].Fill( + float(pid), + float(mom.x / GeV), + float(mom.y / GeV), + float(mom.z / GeV), + float(pos.x / m), + float(pos.y / m), + float(pos.z / m), + pythiaid, + parentid, + ) + # print 'xxx',pid, float(mom.x/GeV),float(mom.y/GeV),float(mom.z/GeV),pythiaid,parentid,float(pos.x/m),float(pos.y/m),float(pos.z/m) + # myPythia.EventListing() + def ConstructGeom(): - print("* Constructing geometry...") - world_r = 100.*m - # reset world material - vac = G4Material.GetMaterial("G4_Galactic") - g4py.ezgeom.SetWorldMaterial(vac) - g4py.ezgeom.ResizeWorld(world_r, world_r, world_r) - # a snoopy world is placed - global snoopy,snoopyPhys,scoreLog - snoopy = G4EzVolume("Snoopy") - snoopy.CreateTubeVolume(vac, 0., 10*m, 50.*m) - snoopyPhys = snoopy.PlaceIt(G4ThreeVector(0.,0.,0.*m)) - snoopyLog = snoopyPhys.GetLogicalVolume() - snoopy.SetVisibility(False) - # a target box is placed - global target,targetPhys - iron = G4Material.GetMaterial("G4_Fe") - air = G4Material.GetMaterial("G4_AIR") - tungsten = G4Material.GetMaterial("G4_W") - lead = G4Material.GetMaterial("G4_Pb") - alum = G4Material.GetMaterial("G4_Al") - target = G4EzVolume("Target") - target.CreateTubeVolume(tungsten, 0., 25.*cm, 25.*cm) - targetPhys = target.PlaceIt(G4ThreeVector(0.,0.,-50.*m+25.*cm),1,snoopy) - target.SetColor(G4Color(0.0,0.5,0.5,1.0)) - target.SetVisibility(True) - # = 0.1m3 = 2t - # a hadron absorber is placed - absorber = G4EzVolume("Absorber") -# iron alloys saturate at 1.6-2.2T - # inner radius outer radius length - absorber.CreateTubeVolume(iron, 0., 100.*cm, 150.*cm) - absorberPhys = absorber.PlaceIt(G4ThreeVector(0.,0.,-50*m+2*25.*cm+150.*cm),1,snoopy) - absorber.SetColor(G4Color(0.898,0.902,0.91,1.0)) - absorber.SetVisibility(True) - xx = G4VisAttributes() - xx.SetForceWireframe(True) - absorberlog = absorberPhys.GetLogicalVolume() - absorberlog.SetVisAttributes(xx) -# scoring plane - scorez = -50.*m+2*25.*cm+2*150.*cm+1*mm - score = G4EzVolume("Score") - score.CreateTubeVolume(vac, 0., 50.*m, 1.*mm) - scorePhys = score.PlaceIt(G4ThreeVector(0.,0.,scorez),1,snoopy) - scoreLog = scorePhys.GetLogicalVolume() - g4py.ezgeom.Construct() + print("* Constructing geometry...") + world_r = 100.0 * m + # reset world material + vac = G4Material.GetMaterial("G4_Galactic") + g4py.ezgeom.SetWorldMaterial(vac) + g4py.ezgeom.ResizeWorld(world_r, world_r, world_r) + # a snoopy world is placed + global snoopy, snoopyPhys, scoreLog + snoopy = G4EzVolume("Snoopy") + snoopy.CreateTubeVolume(vac, 0.0, 10 * m, 50.0 * m) + snoopyPhys = snoopy.PlaceIt(G4ThreeVector(0.0, 0.0, 0.0 * m)) + snoopyLog = snoopyPhys.GetLogicalVolume() + snoopy.SetVisibility(False) + # a target box is placed + global target, targetPhys + iron = G4Material.GetMaterial("G4_Fe") + air = G4Material.GetMaterial("G4_AIR") + tungsten = G4Material.GetMaterial("G4_W") + lead = G4Material.GetMaterial("G4_Pb") + alum = G4Material.GetMaterial("G4_Al") + target = G4EzVolume("Target") + target.CreateTubeVolume(tungsten, 0.0, 25.0 * cm, 25.0 * cm) + targetPhys = target.PlaceIt( + G4ThreeVector(0.0, 0.0, -50.0 * m + 25.0 * cm), 1, snoopy + ) + target.SetColor(G4Color(0.0, 0.5, 0.5, 1.0)) + target.SetVisibility(True) + # = 0.1m3 = 2t + # a hadron absorber is placed + absorber = G4EzVolume("Absorber") + # iron alloys saturate at 1.6-2.2T + # inner radius outer radius length + absorber.CreateTubeVolume(iron, 0.0, 100.0 * cm, 150.0 * cm) + absorberPhys = absorber.PlaceIt( + G4ThreeVector(0.0, 0.0, -50 * m + 2 * 25.0 * cm + 150.0 * cm), 1, snoopy + ) + absorber.SetColor(G4Color(0.898, 0.902, 0.91, 1.0)) + absorber.SetVisibility(True) + xx = G4VisAttributes() + xx.SetForceWireframe(True) + absorberlog = absorberPhys.GetLogicalVolume() + absorberlog.SetVisAttributes(xx) + # scoring plane + scorez = -50.0 * m + 2 * 25.0 * cm + 2 * 150.0 * cm + 1 * mm + score = G4EzVolume("Score") + score.CreateTubeVolume(vac, 0.0, 50.0 * m, 1.0 * mm) + scorePhys = score.PlaceIt(G4ThreeVector(0.0, 0.0, scorez), 1, snoopy) + scoreLog = scorePhys.GetLogicalVolume() + g4py.ezgeom.Construct() + g4py.NISTmaterials.Construct() -#print Geant4.gMaterialTable +# print Geant4.gMaterialTable if not muonNuclear: - physList = Geant4.FTFP_BERT() - gRunManager.SetUserInitialization(physList) + physList = Geant4.FTFP_BERT() + gRunManager.SetUserInitialization(physList) # with muon nuclear else: - if 'G4PhysListFactory' in dir(G4physicslists): - factory = G4physicslists.G4PhysListFactory() - xx = factory.GetReferencePhysList(model) - else: xx = G4physicslists.GetReferencePhysList(model) - gRunManager.SetUserInitialization(xx) + if "G4PhysListFactory" in dir(G4physicslists): + factory = G4physicslists.G4PhysListFactory() + xx = factory.GetReferencePhysList(model) + else: + xx = G4physicslists.GetReferencePhysList(model) + gRunManager.SetUserInitialization(xx) myGE = MyGeneratorAction() gRunManager.SetUserAction(myGE) # -myTA= MyTrackingAction() +myTA = MyTrackingAction() gRunManager.SetUserAction(myTA) # ConstructGeom() -myRA= MyRunAction() +myRA = MyRunAction() gRunManager.SetUserAction(myRA) -myEA= MyEventAction() +myEA = MyEventAction() gRunManager.SetUserAction(myEA) # initialize gRunManager.Initialize() # scoring should be set after geometry construction -sens = ScoreSD('Score') +sens = ScoreSD("Score") scoreLog.SetSensitiveDetector(sens) t0 = time.time() gRunManager.BeamOn(nev) t1 = time.time() -print('Time used',t1-t0, ' seconds') +print("Time used", t1 - t0, " seconds") for x in myTimer: - print(x,myTimer[x]) + print(x, myTimer[x]) logger.info("output directory: %s" % work_dir) diff --git a/muonShieldOptimization/g4Ex_gap.py b/muonShieldOptimization/g4Ex_gap.py index 56335ea943..8d39aaaaf7 100644 --- a/muonShieldOptimization/g4Ex_gap.py +++ b/muonShieldOptimization/g4Ex_gap.py @@ -1,9 +1,11 @@ #!/usr/bin/env python import os + import saveBasicParameters local = False -if not os.uname()[1].find('ubuntu')<0: local = True +if not os.uname()[1].find("ubuntu") < 0: + local = True debug = False particleGun = False @@ -13,88 +15,116 @@ # new attempt, make general Ekin cut at 0.5 -withNtuple = True -muonNuclear = True -model = "QGSP_BERT_EMV" # QGSP_BERT_EMV <-- less accurate EM showers, should be fine, otherwise "QGSP_BERT_EMX" -runnr = 1 -nev = 1000 -nevTot = 0 +withNtuple = True +muonNuclear = True +model = "QGSP_BERT_EMV" # QGSP_BERT_EMV <-- less accurate EM showers, should be fine, otherwise "QGSP_BERT_EMX" +runnr = 1 +nev = 1000 +nevTot = 0 myEventnr = 0 -mytrack = 1 -scoreLog = 1 -inclusive = True # write out all particles crossing scoring plane ! -myTimer = {'total':0,'pythia':0,'geant4_conv':0} -tauOnly = False +mytrack = 1 +scoreLog = 1 +inclusive = True # write out all particles crossing scoring plane ! +myTimer = {"total": 0, "pythia": 0, "geant4_conv": 0} +tauOnly = False JpsiMainly = False fullTungsten = False -work_dir = "./" -ecut = 0.5 # GeV with 1 : ~1sec / event, with 2: 0.4sec / event, 10: 0.13sec - # pythia = geant4 conversion = 0.4/100 -allPart = True -qedlist = [22,11,-11,12,-12,14,14,2212,2112,13,-13] -rangeCut = False +work_dir = "./" +ecut = 0.5 # GeV with 1 : ~1sec / event, with 2: 0.4sec / event, 10: 0.13sec +# pythia = geant4 conversion = 0.4/100 +allPart = True +qedlist = [22, 11, -11, 12, -12, 14, 14, 2212, 2112, 13, -13] +rangeCut = False trackHistory = {} -#----------------------------- Yandex production ------------------------------ -import shutil import argparse import logging +# ----------------------------- Yandex production ------------------------------ +import shutil + logging.info("") logger = logging.getLogger(os.path.splitext(os.path.basename(os.sys.argv[0]))[0]) logger.setLevel(logging.INFO) def get_work_dir(run_number): - import socket - host = socket.gethostname() - job_base_name = os.path.splitext(os.path.basename(os.sys.argv[0]))[0] - out_dir = "{host}_{base}_{runnr}".format(host=host, base=job_base_name, runnr=run_number) - return out_dir + import socket + + host = socket.gethostname() + job_base_name = os.path.splitext(os.path.basename(os.sys.argv[0]))[0] + out_dir = "{host}_{base}_{runnr}".format( + host=host, base=job_base_name, runnr=run_number + ) + return out_dir def init(): - global runnr, nev, ecut, tauOnly,JpsiMainly,fullTungsten, work_dir - logger.info("SHiP proton-on-taget simulator (C) Thomas Ruf, 2014") - - ap = argparse.ArgumentParser( - description='Run SHiP "pot" simulation') - ap.add_argument('-d', '--debug', action='store_true') - ap.add_argument('-f', '--force', action='store_true', help="force overwriting output directory") - ap.add_argument('-r', '--run-number', type=int, dest='runnr', default=runnr) - ap.add_argument('-e', '--ecut', type=float, help="energy cut", dest='ecut', default=ecut) - ap.add_argument('-n', '--num-events', type=int, help="number of events to generate", dest='nev', default=nev) - ap.add_argument('-t', '--tau-only', action='store_true', dest='tauOnly',default=False) - ap.add_argument('-J', '--Jpsi-mainly', action='store_true', dest='JpsiMainly',default=False) - ap.add_argument('-W', '--FullTungsten', action='store_true',dest='fullTungsten',default=False) - ap.add_argument('-o', '--output', type=str, help="output directory", dest='work_dir', default=None) - args = ap.parse_args() - if args.debug: - logger.setLevel(logging.DEBUG) - runnr = args.runnr - nev = args.nev - ecut = args.ecut - tauOnly = args.tauOnly - JpsiMainly = args.JpsiMainly - fullTungsten = args.fullTungsten - if args.work_dir is None: - args.work_dir = get_work_dir(runnr) - work_dir = args.work_dir - logger.debug("work_dir: %s" % work_dir) - logger.debug("command line arguments: %s", args) - if os.path.exists(work_dir): - logger.warn("output directory '%s' already exists." % work_dir) - if args.force: - logger.warn("...cleaning") - for root, dirs, files in os.walk(work_dir): - for f in files: - os.unlink(os.path.join(root, f)) - for d in dirs: - shutil.rmtree(os.path.join(root, d)) + global runnr, nev, ecut, tauOnly, JpsiMainly, fullTungsten, work_dir + logger.info("SHiP proton-on-taget simulator (C) Thomas Ruf, 2014") + + ap = argparse.ArgumentParser(description='Run SHiP "pot" simulation') + ap.add_argument("-d", "--debug", action="store_true") + ap.add_argument( + "-f", "--force", action="store_true", help="force overwriting output directory" + ) + ap.add_argument("-r", "--run-number", type=int, dest="runnr", default=runnr) + ap.add_argument( + "-e", "--ecut", type=float, help="energy cut", dest="ecut", default=ecut + ) + ap.add_argument( + "-n", + "--num-events", + type=int, + help="number of events to generate", + dest="nev", + default=nev, + ) + ap.add_argument( + "-t", "--tau-only", action="store_true", dest="tauOnly", default=False + ) + ap.add_argument( + "-J", "--Jpsi-mainly", action="store_true", dest="JpsiMainly", default=False + ) + ap.add_argument( + "-W", "--FullTungsten", action="store_true", dest="fullTungsten", default=False + ) + ap.add_argument( + "-o", + "--output", + type=str, + help="output directory", + dest="work_dir", + default=None, + ) + args = ap.parse_args() + if args.debug: + logger.setLevel(logging.DEBUG) + runnr = args.runnr + nev = args.nev + ecut = args.ecut + tauOnly = args.tauOnly + JpsiMainly = args.JpsiMainly + fullTungsten = args.fullTungsten + if args.work_dir is None: + args.work_dir = get_work_dir(runnr) + work_dir = args.work_dir + logger.debug("work_dir: %s" % work_dir) + logger.debug("command line arguments: %s", args) + if os.path.exists(work_dir): + logger.warn("output directory '%s' already exists." % work_dir) + if args.force: + logger.warn("...cleaning") + for root, dirs, files in os.walk(work_dir): + for f in files: + os.unlink(os.path.join(root, f)) + for d in dirs: + shutil.rmtree(os.path.join(root, d)) + else: + logger.warn("...use '-f' option to overwrite it") else: - logger.warn("...use '-f' option to overwrite it") - else: - os.makedirs(work_dir) - return args + os.makedirs(work_dir) + return args + args = init() @@ -102,65 +132,81 @@ def init(): # ------------------------------------------------------------------- +import time + +import g4py.ezgeom +import g4py.NISTmaterials # ================================================================== # ROOT IMPORT # # ================================================================== -import ROOT,time +import ROOT +from g4py.ezgeom import G4EzVolume # ================================================================== # GEANT4 IMPORT # # ================================================================== from Geant4 import * -import g4py.NISTmaterials -import g4py.ezgeom -from g4py.ezgeom import G4EzVolume + # ================================================================== # PYTHIA8 PART # # ================================================================== -pdg = ROOT.TDatabasePDG() -pdg.AddParticle("Pomeron","Pomeron", 0,False,0,0,'',990) -pdg.AddParticle("ccbar[1S0(8)]","ccbar[1S0(8)]",0,False,0,0,'',9900441) -pdg.AddParticle("c~c[3P08]","c~c[3P08]",0,False,0,0,'',9910441) +pdg = ROOT.TDatabasePDG() +pdg.AddParticle("Pomeron", "Pomeron", 0, False, 0, 0, "", 990) +pdg.AddParticle("ccbar[1S0(8)]", "ccbar[1S0(8)]", 0, False, 0, 0, "", 9900441) +pdg.AddParticle("c~c[3P08]", "c~c[3P08]", 0, False, 0, 0, "", 9910441) ROOT.gSystem.Load("libEG") ROOT.gSystem.Load("libpythia8") ROOT.gSystem.Load("libEGPythia8") myPythia = ROOT.TPythia8() -rnr = ROOT.TRandom() +rnr = ROOT.TRandom() myPythia.ReadString("Next:numberCount = 100000") myPythia.ReadString("SoftQCD:inelastic = on") myPythia.ReadString("PhotonCollision:gmgm2mumu = on") myPythia.ReadString("PromptPhoton:all = on") myPythia.ReadString("WeakBosonExchange:all = on") # http://home.thep.lu.se/~torbjorn/pythia81html/ParticleDecays.html -if tauOnly : - myPythia.ReadString("431:new D_s+ D_s- 1 3 0 1.96849 0.00000 0.00000 0.00000 1.49900e-01 0 1 0 1 0") - myPythia.ReadString("431:addChannel = 1 0.0640000 0 -15 16") -if JpsiMainly : - myPythia.ReadString("443:new J/psi J/psi 4 0 0 3.09692 0.00009 3.09602 3.09782 0. 1 1 0 1 0") - myPythia.ReadString("443:addChannel = 1 0.1 0 -13 13") +if tauOnly: + myPythia.ReadString( + "431:new D_s+ D_s- 1 3 0 1.96849 0.00000 0.00000 0.00000 1.49900e-01 0 1 0 1 0" + ) + myPythia.ReadString("431:addChannel = 1 0.0640000 0 -15 16") +if JpsiMainly: + myPythia.ReadString( + "443:new J/psi J/psi 4 0 0 3.09692 0.00009 3.09602 3.09782 0. 1 1 0 1 0" + ) + myPythia.ReadString("443:addChannel = 1 0.1 0 -13 13") # make pions/kaons/lambda stable -for s in [211,321,130,310,3122,3112,3312]: # last two added 18Feb2015 - myPythia.ReadString(str(s)+':mayDecay = false') +for s in [211, 321, 130, 310, 3122, 3112, 3312]: # last two added 18Feb2015 + myPythia.ReadString(str(s) + ":mayDecay = false") # set random number seed myPythia.ReadString("Random:setSeed = On") -R = int(time.time()%900000000) -myPythia.ReadString("Random:seed = "+str(R)) +R = int(time.time() % 900000000) +myPythia.ReadString("Random:seed = " + str(R)) # Initialize proton (400GeV) on proton at rest -myPythia.Initialize(2212,2212,400.,0.) # required to hack TPythia8 in root ! +myPythia.Initialize(2212, 2212, 400.0, 0.0) # required to hack TPythia8 in root ! # W = 74 protons and 184-74= 110 neutrons -if tauOnly: myPythia.Plist(431) +if tauOnly: + myPythia.Plist(431) # if there is no energy cut, there are no particles to apply it to. -if ecut == 0: qedlist = [] +if ecut == 0: + qedlist = [] # ecut applied to all particles -if allPart: qedlist = [] +if allPart: + qedlist = [] # Open an output file h = {} if withNtuple: - f = ROOT.TFile.Open('pythia8_Geant4_'+str(runnr)+'_'+str(ecut)+'.root', 'RECREATE') - h['ntuple'] = ROOT.TNtuple("pythia8-Geant4","muon/nu flux","id:px:py:pz:x:y:z:opx:opy:opz:ox:oy:oz:pythiaid:parentid") + f = ROOT.TFile.Open( + "pythia8_Geant4_" + str(runnr) + "_" + str(ecut) + ".root", "RECREATE" + ) + h["ntuple"] = ROOT.TNtuple( + "pythia8-Geant4", + "muon/nu flux", + "id:px:py:pz:x:y:z:opx:opy:opz:ox:oy:oz:pythiaid:parentid", + ) # ================================================================== # Geant4 PART # @@ -171,7 +217,7 @@ def init(): rand_engine = Ranlux64Engine() HepRandom.setTheEngine(rand_engine) HepRandom.setTheSeed(runnr) -world_r = 200.*m +world_r = 200.0 * m # ================================================================== # user actions in python @@ -181,409 +227,597 @@ def init(): # visualization # ================================================================== if local: - gVisManager.SetVerboseLevel(2) - gVisManager.Initialize() - gApplyUICommand('/vis/open OGLIX 1200x400-0+0') - gApplyUICommand('/vis/viewer/set/viewpointThetaPhi -90. 90.') + gVisManager.SetVerboseLevel(2) + gVisManager.Initialize() + gApplyUICommand("/vis/open OGLIX 1200x400-0+0") + gApplyUICommand("/vis/viewer/set/viewpointThetaPhi -90. 90.") + # ------------------------------------------------------------------ class MyGeneratorAction(G4VUserPrimaryGeneratorAction): - " My Generator Action" - pos = G4ThreeVector(0*cm, 0*cm, -world_r/2.) - - def GeneratePrimaries(self,anEvent): - global debug,nevTot,particleGun,fullTungsten - t_0 = time.time() - npart = 0 - if particleGun: -# to evaluate interaction position - ztarget = G4ThreeVector(0*cm, 0*cm, -50.*m) - vertex = G4PrimaryVertex(ztarget,0.) - G4particle = G4PrimaryParticle( 2212 ) - G4particle.Set4Momentum( 0,0,400*GeV,400.0011*GeV ) -# store mother ID - w = 2212 + 0 * 100000 - G4particle.SetWeight(w) - vertex.SetPrimary( G4particle ) - npart += 1 - else: - while npart == 0: - myPythia.GenerateEvent() - nevTot+=1 - myTimer['pythia']+=time.time()-t_0 -# pythia interaction happens at 0,0,0 - #x = rnr.Uniform(-3.,3.) - #y = rnr.Uniform(-3.,3.) - # leave this smearing for later - # create new primaries and set them to the vertex - particles = myPythia.GetListOfParticles() - if fullTungsten: z = rnr.Exp(10*cm) -50.*m # tungsten interaction length - else: z = rnr.Exp(16*cm) -50.*m # Mo/H20/W average interaction length - ztarget = G4ThreeVector(0*cm, 0*cm, z) - vertex = G4PrimaryVertex(ztarget,0.) - v = ROOT.TLorentzVector() - for p in particles: - if p.GetStatusCode()!=1 : continue - pid = p.GetPdgCode() - mkey = p.GetMother(0)+1 - mother = myPythia.GetParticle(mkey) - if JpsiMainly and abs(pid) != 13 : continue - if tauOnly and abs(pid) != 16 : continue - if JpsiMainly and mother.GetPdgCode() != 443 : continue - if tauOnly : - mmkey = mother.GetMother(0)+1 - mmother = myPythia.GetParticle(mmkey) - if abs(mother.GetPdgCode()) != 431 and abs(mmother.GetPdgCode()) != 431 : - myPythia.EventListing() - continue - qed = pid in qedlist # use cut only for photons, leptons/neutrinos, protons and neutrons - p.Momentum(v) - Ekin = (v.E()-v.M()) - if Ekin*GeV < ecut and (qed or allPart): continue - G4particle = G4PrimaryParticle( pid ) - G4particle.Set4Momentum( v.Px()*GeV,v.Py()*GeV,v.Pz()*GeV,v.E()*GeV ) -# store mother ID - curPid = p.GetPdgCode() + 10000 # make it positive - moPid = mother.GetPdgCode() + 10000 - w = curPid + moPid * 100000 - G4particle.SetWeight(w) - vertex.SetPrimary( G4particle ) - npart += 1 - # if debug: myPythia.EventListing() - anEvent.AddPrimaryVertex( vertex ) - if debug and not particleGun: print('new event at ',ztarget.z/m) - myTimer['geant4_conv']+=time.time()-t_0 + "My Generator Action" + + pos = G4ThreeVector(0 * cm, 0 * cm, -world_r / 2.0) + + def GeneratePrimaries(self, anEvent): + global debug, nevTot, particleGun, fullTungsten + t_0 = time.time() + npart = 0 + if particleGun: + # to evaluate interaction position + ztarget = G4ThreeVector(0 * cm, 0 * cm, -50.0 * m) + vertex = G4PrimaryVertex(ztarget, 0.0) + G4particle = G4PrimaryParticle(2212) + G4particle.Set4Momentum(0, 0, 400 * GeV, 400.0011 * GeV) + # store mother ID + w = 2212 + 0 * 100000 + G4particle.SetWeight(w) + vertex.SetPrimary(G4particle) + npart += 1 + else: + while npart == 0: + myPythia.GenerateEvent() + nevTot += 1 + myTimer["pythia"] += time.time() - t_0 + # pythia interaction happens at 0,0,0 + # x = rnr.Uniform(-3.,3.) + # y = rnr.Uniform(-3.,3.) + # leave this smearing for later + # create new primaries and set them to the vertex + particles = myPythia.GetListOfParticles() + if fullTungsten: + z = rnr.Exp(10 * cm) - 50.0 * m # tungsten interaction length + else: + z = ( + rnr.Exp(16 * cm) - 50.0 * m + ) # Mo/H20/W average interaction length + ztarget = G4ThreeVector(0 * cm, 0 * cm, z) + vertex = G4PrimaryVertex(ztarget, 0.0) + v = ROOT.TLorentzVector() + for p in particles: + if p.GetStatusCode() != 1: + continue + pid = p.GetPdgCode() + mkey = p.GetMother(0) + 1 + mother = myPythia.GetParticle(mkey) + if JpsiMainly and abs(pid) != 13: + continue + if tauOnly and abs(pid) != 16: + continue + if JpsiMainly and mother.GetPdgCode() != 443: + continue + if tauOnly: + mmkey = mother.GetMother(0) + 1 + mmother = myPythia.GetParticle(mmkey) + if ( + abs(mother.GetPdgCode()) != 431 + and abs(mmother.GetPdgCode()) != 431 + ): + myPythia.EventListing() + continue + qed = ( + pid in qedlist + ) # use cut only for photons, leptons/neutrinos, protons and neutrons + p.Momentum(v) + Ekin = v.E() - v.M() + if Ekin * GeV < ecut and (qed or allPart): + continue + G4particle = G4PrimaryParticle(pid) + G4particle.Set4Momentum( + v.Px() * GeV, v.Py() * GeV, v.Pz() * GeV, v.E() * GeV + ) + # store mother ID + curPid = p.GetPdgCode() + 10000 # make it positive + moPid = mother.GetPdgCode() + 10000 + w = curPid + moPid * 100000 + G4particle.SetWeight(w) + vertex.SetPrimary(G4particle) + npart += 1 + # if debug: myPythia.EventListing() + anEvent.AddPrimaryVertex(vertex) + if debug and not particleGun: + print("new event at ", ztarget.z / m) + myTimer["geant4_conv"] += time.time() - t_0 + + class MyRunAction(G4UserRunAction): - "My Run Action" - - def EndOfRunAction(self, run): - global debug,nevTot - print("*** End of Run") - print("- Run summary : (id= %d, #events= %d)" \ - % (run.GetRunID(), nevTot)) - h['ntuple'].Write() - print('ecut applied to',allPart,qedlist,' range cut for e,gamma:',rangeCut) + "My Run Action" + + def EndOfRunAction(self, run): + global debug, nevTot + print("*** End of Run") + print("- Run summary : (id= %d, #events= %d)" % (run.GetRunID(), nevTot)) + h["ntuple"].Write() + print("ecut applied to", allPart, qedlist, " range cut for e,gamma:", rangeCut) + + # ------------------------------------------------------------------ class MyEventAction(G4UserEventAction): - "My Event Action" - def EndOfEventAction(self, event): - global myEventnr - if debug and not particleGun: print('end of event',myEventnr) - myEventnr += 1 - # self.myPrintout(event) - def StartOfEventAction(self, event): - global trackHistory - trackHistory={} - def myPrintout(self, event): - prim = event.GetPrimaryVertex() - print('vertex ',prim.GetX0()/m,prim.GetY0()/m,prim.GetZ0()/m) - for k in range( prim.GetNumberOfParticle() ): - p = prim.GetPrimary(k) - print('event',p.GetPDGcode(),p.GetPx()/GeV,p.GetPy()/GeV,p.GetPz()/GeV) + "My Event Action" + + def EndOfEventAction(self, event): + global myEventnr + if debug and not particleGun: + print("end of event", myEventnr) + myEventnr += 1 + # self.myPrintout(event) + + def StartOfEventAction(self, event): + global trackHistory + trackHistory = {} + + def myPrintout(self, event): + prim = event.GetPrimaryVertex() + print("vertex ", prim.GetX0() / m, prim.GetY0() / m, prim.GetZ0() / m) + for k in range(prim.GetNumberOfParticle()): + p = prim.GetPrimary(k) + print( + "event", + p.GetPDGcode(), + p.GetPx() / GeV, + p.GetPy() / GeV, + p.GetPz() / GeV, + ) + + # ------------------------------------------------------------------ class MySteppingAction(G4UserSteppingAction): - "My Stepping Action" - - def UserSteppingAction(self, step): - preStepPoint = step.GetPreStepPoint() - touch = preStepPoint.GetTouchableHandle() - volName = touch.GetVolume().GetName().__format__('') - pos = preStepPoint.GetPosition() - print('stepping name, z pos dedx (MeV): ',volName,pos.z/m,step.GetTotalEnergyDeposit()/MeV) + "My Stepping Action" + + def UserSteppingAction(self, step): + preStepPoint = step.GetPreStepPoint() + touch = preStepPoint.GetTouchableHandle() + volName = touch.GetVolume().GetName().__format__("") + pos = preStepPoint.GetPosition() + print( + "stepping name, z pos dedx (MeV): ", + volName, + pos.z / m, + step.GetTotalEnergyDeposit() / MeV, + ) + + # ------------------------------------------------------------------ class MyTrackingAction(G4UserTrackingAction): - def PostUserTrackingAction(self,atrack): - pass - def PreUserTrackingAction(self,atrack): -# need to be careful with energy cut, anti-protons and anti-neutrons can always produce pions and kaons - part = atrack.GetDynamicParticle() - pid = part.GetPDGcode() - muCut = JpsiMainly and abs(pid)!=13 - qed = pid in qedlist # use cut only for photons, electrons, protons and neutrons - if (atrack.GetKineticEnergy()/GeV < ecut and (qed or allPart) ) or muCut : - G4TrackingManager().SetStoreTrajectory(False) - atrack.SetTrackStatus(atrack.GetTrackStatus().fStopAndKill) + def PostUserTrackingAction(self, atrack): + pass + + def PreUserTrackingAction(self, atrack): + # need to be careful with energy cut, anti-protons and anti-neutrons can always produce pions and kaons + part = atrack.GetDynamicParticle() + pid = part.GetPDGcode() + muCut = JpsiMainly and abs(pid) != 13 + qed = ( + pid in qedlist + ) # use cut only for photons, electrons, protons and neutrons + if (atrack.GetKineticEnergy() / GeV < ecut and (qed or allPart)) or muCut: + G4TrackingManager().SetStoreTrajectory(False) + atrack.SetTrackStatus(atrack.GetTrackStatus().fStopAndKill) + # ------------------------------------------------------------------ class MyTrackingActionD(G4UserTrackingAction): - def PostUserTrackingAction(self,atrack): - if particleGun and atrack.GetTrackID() == 1: - # record dead of 400GeV proton - if atrack.GetTrackStatus() != atrack.GetTrackStatus().fAlive : - part = atrack.GetDynamicParticle() - pid = part.GetPDGcode() - vx = atrack.GetVertexPosition() - mom = atrack.GetMomentum() - ekin = atrack.GetKineticEnergy()/GeV - pos = atrack.GetPosition() - w = atrack.GetWeight() - parentid = int(w)/100000-10000 - pythiaid = int(w)%100000-10000 - h['ntuple'].Fill(float(pid), float(mom.x/GeV),float(mom.y/GeV),float(mom.z/GeV),\ - float(pos.x/m),float(pos.y/m),float(pos.z/m),\ - float(vx.x/m),float(vx.y/m),float(vx.z/m),pythiaid,parentid) - - def PreUserTrackingAction(self,atrack): - global trackHistory -# need to be careful with energy cut, anti-protons and neutrons can always produce pions and kaons - part = atrack.GetDynamicParticle() - pid = part.GetPDGcode() - # if debug: self.myPrintout(atrack) - moid = atrack.GetParentID() - trackHistory[atrack.GetTrackID()]=[pid,moid] - tmoid = str(moid) - if moid in trackHistory: - mo = pdg.GetParticle(trackHistory[moid][0]) - if mo : tmoid = mo.GetName() - tid = str(pid) - if pdg.GetParticle(pid): tid = pdg.GetParticle(pid).GetName() - mom = atrack.GetMomentum() - p = ROOT.TMath.Sqrt(mom.x*mom.x+mom.y*mom.y+mom.z*mom.z) - if debug and abs(pid)==13: print('track',atrack.GetTrackID(),tid,tmoid,moid,atrack.GetKineticEnergy()/MeV,p/MeV) - if pid==12: - if moid in trackHistory: - gmoid = trackHistory[moid][1] - if gmoid in trackHistory: - tgmoid = str(gmoid) - mo = pdg.GetParticle(trackHistory[gmoid][0]) - if mo : tgmoid = mo.GetName() - print(' <--',gmoid,tgmoid) - gmoid = trackHistory[gmoid][1] - if gmoid in trackHistory: - tgmoid = str(gmoid) - mo = pdg.GetParticle(trackHistory[gmoid][0]) - if mo : tgmoid = mo.GetName() - print(' <--',gmoid,tgmoid) - - qed = pid in qedlist # use cut only for photons, electrons, protons and neutrons - if atrack.GetKineticEnergy()/GeV < ecut and (qed or allPart): - G4TrackingManager().SetStoreTrajectory(False) - atrack.SetTrackStatus(atrack.GetTrackStatus().fStopAndKill) - - def myPrintout(self, atrack): - part = atrack.GetDynamicParticle() - pid = part.GetPDGcode() - vx = atrack.GetVertexPosition() - pos = atrack.GetPosition() - mom = atrack.GetMomentum() - print('TA',pid,atrack.GetTotalEnergy()/GeV,ecut*GeV) - print('start tracking',atrack.GetDynamicParticle().GetPDGcode(),atrack.GetKineticEnergy()/GeV,vx.z/m,pos.z/m,mom.z/GeV) + def PostUserTrackingAction(self, atrack): + if particleGun and atrack.GetTrackID() == 1: + # record dead of 400GeV proton + if atrack.GetTrackStatus() != atrack.GetTrackStatus().fAlive: + part = atrack.GetDynamicParticle() + pid = part.GetPDGcode() + vx = atrack.GetVertexPosition() + mom = atrack.GetMomentum() + ekin = atrack.GetKineticEnergy() / GeV + pos = atrack.GetPosition() + w = atrack.GetWeight() + parentid = int(w) / 100000 - 10000 + pythiaid = int(w) % 100000 - 10000 + h["ntuple"].Fill( + float(pid), + float(mom.x / GeV), + float(mom.y / GeV), + float(mom.z / GeV), + float(pos.x / m), + float(pos.y / m), + float(pos.z / m), + float(vx.x / m), + float(vx.y / m), + float(vx.z / m), + pythiaid, + parentid, + ) + + def PreUserTrackingAction(self, atrack): + global trackHistory + # need to be careful with energy cut, anti-protons and neutrons can always produce pions and kaons + part = atrack.GetDynamicParticle() + pid = part.GetPDGcode() + # if debug: self.myPrintout(atrack) + moid = atrack.GetParentID() + trackHistory[atrack.GetTrackID()] = [pid, moid] + tmoid = str(moid) + if moid in trackHistory: + mo = pdg.GetParticle(trackHistory[moid][0]) + if mo: + tmoid = mo.GetName() + tid = str(pid) + if pdg.GetParticle(pid): + tid = pdg.GetParticle(pid).GetName() + mom = atrack.GetMomentum() + p = ROOT.TMath.Sqrt(mom.x * mom.x + mom.y * mom.y + mom.z * mom.z) + if debug and abs(pid) == 13: + print( + "track", + atrack.GetTrackID(), + tid, + tmoid, + moid, + atrack.GetKineticEnergy() / MeV, + p / MeV, + ) + if pid == 12: + if moid in trackHistory: + gmoid = trackHistory[moid][1] + if gmoid in trackHistory: + tgmoid = str(gmoid) + mo = pdg.GetParticle(trackHistory[gmoid][0]) + if mo: + tgmoid = mo.GetName() + print(" <--", gmoid, tgmoid) + gmoid = trackHistory[gmoid][1] + if gmoid in trackHistory: + tgmoid = str(gmoid) + mo = pdg.GetParticle(trackHistory[gmoid][0]) + if mo: + tgmoid = mo.GetName() + print(" <--", gmoid, tgmoid) + + qed = ( + pid in qedlist + ) # use cut only for photons, electrons, protons and neutrons + if atrack.GetKineticEnergy() / GeV < ecut and (qed or allPart): + G4TrackingManager().SetStoreTrajectory(False) + atrack.SetTrackStatus(atrack.GetTrackStatus().fStopAndKill) + + def myPrintout(self, atrack): + part = atrack.GetDynamicParticle() + pid = part.GetPDGcode() + vx = atrack.GetVertexPosition() + pos = atrack.GetPosition() + mom = atrack.GetMomentum() + print("TA", pid, atrack.GetTotalEnergy() / GeV, ecut * GeV) + print( + "start tracking", + atrack.GetDynamicParticle().GetPDGcode(), + atrack.GetKineticEnergy() / GeV, + vx.z / m, + pos.z / m, + mom.z / GeV, + ) + # ------------------------------------------------------------------ class ScoreSD(G4VSensitiveDetector): - "SD for score voxels" - - def __init__(self,Name): - G4VSensitiveDetector.__init__(self, Name) - - def ProcessHits(self, step, rohist): - preStepPoint = step.GetPreStepPoint() - track = step.GetTrack() - part = track.GetDynamicParticle() - pid = part.GetPDGcode() - vx = track.GetVertexPosition() - pvx = track.GetVertexMomentumDirection() - ekinvx = track.GetVertexKineticEnergy() - M = part.GetMass() - Pvx = ROOT.TMath.Sqrt( ekinvx*(ekinvx+2*M) ) - mom = track.GetMomentum() - ekin = track.GetKineticEnergy()/GeV - pos = track.GetPosition() -# - # primPart = part.GetPrimaryParticle() - w = track.GetWeight() - parentid = int(w)/100000-10000 - pythiaid = int(w)%100000-10000 - h['ntuple'].Fill(float(pid), float(mom.x/GeV),float(mom.y/GeV),float(mom.z/GeV),\ - float(pos.x/m),float(pos.y/m),float(pos.z/m),\ - float(Pvx*pvx.x/GeV),float(Pvx*pvx.y/GeV),float(Pvx*pvx.z/GeV),\ - float(vx.x/m),float(vx.y/m),float(vx.z/m),pythiaid,parentid) - if debug: - print('xxx',pid, float(mom.x/GeV),float(mom.y/GeV),float(mom.z/GeV),\ - float(pos.x/m),float(pos.y/m),float(pos.z/m),\ - float(Pvx*pvx.x/GeV),float(Pvx*pvx.y/GeV),float(Pvx*pvx.z/GeV),\ - float(vx.x/m),float(vx.y/m),float(vx.z/m),pythiaid,parentid) + "SD for score voxels" + + def __init__(self, Name): + G4VSensitiveDetector.__init__(self, Name) + + def ProcessHits(self, step, rohist): + preStepPoint = step.GetPreStepPoint() + track = step.GetTrack() + part = track.GetDynamicParticle() + pid = part.GetPDGcode() + vx = track.GetVertexPosition() + pvx = track.GetVertexMomentumDirection() + ekinvx = track.GetVertexKineticEnergy() + M = part.GetMass() + Pvx = ROOT.TMath.Sqrt(ekinvx * (ekinvx + 2 * M)) + mom = track.GetMomentum() + ekin = track.GetKineticEnergy() / GeV + pos = track.GetPosition() + # + # primPart = part.GetPrimaryParticle() + w = track.GetWeight() + parentid = int(w) / 100000 - 10000 + pythiaid = int(w) % 100000 - 10000 + h["ntuple"].Fill( + float(pid), + float(mom.x / GeV), + float(mom.y / GeV), + float(mom.z / GeV), + float(pos.x / m), + float(pos.y / m), + float(pos.z / m), + float(Pvx * pvx.x / GeV), + float(Pvx * pvx.y / GeV), + float(Pvx * pvx.z / GeV), + float(vx.x / m), + float(vx.y / m), + float(vx.z / m), + pythiaid, + parentid, + ) + if debug: + print( + "xxx", + pid, + float(mom.x / GeV), + float(mom.y / GeV), + float(mom.z / GeV), + float(pos.x / m), + float(pos.y / m), + float(pos.z / m), + float(Pvx * pvx.x / GeV), + float(Pvx * pvx.y / GeV), + float(Pvx * pvx.z / GeV), + float(vx.x / m), + float(vx.y / m), + float(vx.z / m), + pythiaid, + parentid, + ) + def ConstructGeom(): - print("* Constructing geometry...") - # reset world material - vac = G4Material.GetMaterial("G4_Galactic") - g4py.ezgeom.SetWorldMaterial(vac) - g4py.ezgeom.ResizeWorld(world_r/2., world_r/2., world_r) - # a snoopy world is placed - global snoopy,snoopyPhys,scoreLog - snoopy = G4EzVolume("Snoopy") - snoopy.CreateTubeVolume(vac, 0., 20*m, world_r/2.) - snoopyPhys = snoopy.PlaceIt(G4ThreeVector(0.,0.,0.*m)) - snoopyLog = snoopyPhys.GetLogicalVolume() - snoopy.SetVisibility(False) - # a target box is placed - global target,targetPhys - iron = G4Material.GetMaterial("G4_Fe") - air = G4Material.GetMaterial("G4_AIR") - water = G4Material.GetMaterial("G4_WATER") - tungsten = G4Material.GetMaterial("G4_W") - lead = G4Material.GetMaterial("G4_Pb") - alum = G4Material.GetMaterial("G4_Al") - elementMo = G4Element("Molybdenum","Mo",42., 95.94*g/mole) - molybdenum = G4Material("molybdenum", 10.22*g/cm3, 1) - molybdenum.AddElement(elementMo, 1.00) -# - if fullTungsten: - target = G4EzVolume("Target") - slit = G4EzVolume("Slit") - slitDZ = 0.5*cm - targetDZ = 5.*cm -# target is sliced, 4 slits of 1cm, 10cm tungsten blocks - target.CreateTubeVolume(tungsten, 0., 25.*cm,targetDZ) - target.SetColor(G4Color(0.0,0.5,0.5,1.0)) - target.SetVisibility(True) -# additional 5 interaction lengths - #targetOpt = G4EzVolume("TargetOpt") - #targetOpt.CreateTubeVolume(tungsten, 0., 25.*cm, 25.*cm) - #targetOpt.SetColor(G4Color(0.0,0.5,0.5,1.0)) - #targetOpt.SetVisibility(True) - slit.CreateTubeVolume(water, 0., 25.*cm, slitDZ) - slit.SetVisibility(False) - targetPhys = [] - slitPhys = [] - targetL = 0*cm - z0Pos = -50.*m - for i in range(4): - targetPhys.append(target.PlaceIt(G4ThreeVector(0.,0.,z0Pos + targetL + targetDZ) ,1,snoopy)) - slitPhys.append(slit.PlaceIt(G4ThreeVector(0.,0., z0Pos + targetL + 2*targetDZ + slitDZ),1,snoopy)) - targetL+= 2*(slitDZ+targetDZ) - targetPhys.append(target.PlaceIt(G4ThreeVector(0.,0., z0Pos + targetL + targetDZ),1,snoopy)) - targetL+= 2*(targetDZ) - # put iron around - moreShielding = G4EzVolume("moreShielding") - moreShielding.CreateTubeVolume(iron, 30.*cm, 400.*cm, targetL/2.) - moreShieldingPhys = moreShielding.PlaceIt(G4ThreeVector(0.,0.,z0Pos + targetL/2.),1,snoopy) -# - else: # new design with mixture Molybdaen and Tungsten - slitDZ = 0.5*cm - diameter = 30.*cm - spaceTopBot = 10.*cm - spaceSide = 5.*cm - slit = G4EzVolume("Slit") - slit.CreateBoxVolume(water, diameter,diameter,slitDZ) - slit.SetVisibility(False) - targetPhys = [] - targetVol = [] - slitPhys = [] - targetL = 0*cm - z0Pos = -50.*m - # material,length - layout = {1:[molybdenum,8.*cm],\ - 2:[molybdenum,2.5*cm],3:[molybdenum,2.5*cm],4:[molybdenum,2.5*cm],5:[molybdenum,2.5*cm],\ - 6:[molybdenum,2.5*cm],7:[molybdenum,2.5*cm],8:[molybdenum,2.5*cm],\ - 9:[molybdenum,5.0*cm],10:[molybdenum,5.0*cm],\ - 11:[molybdenum,6.5*cm],\ - 12:[molybdenum,8.0*cm],13:[molybdenum,8.0*cm],\ - 14:[tungsten,5.*cm],15:[tungsten,8.*cm],16:[tungsten,10.*cm],17:[tungsten,35.*cm] } - for i in range(1,18): - targetVol.append(G4EzVolume("Target_Layer_"+str(i))) - targetVol[i-1].CreateBoxVolume(layout[i][0], diameter,diameter,layout[i][1]) - if layout[i][0]==tungsten: targetVol[i-1].SetColor(G4Color(0.0,0.5,0.5,1.0)) - else: targetVol[i-1].SetColor(G4Color(0.3,0.2,0.5,1.0)) - targetVol[i-1].SetVisibility(True) - targetPhys.append(targetVol[i-1].PlaceIt(G4ThreeVector(0.,0.,z0Pos + targetL + layout[i][1]/2.),1,snoopy)) - if i<17: - slitPhys.append(slit.PlaceIt( G4ThreeVector(0.,0.,z0Pos + targetL + layout[i][1] + slitDZ/2.),1,snoopy)) - targetL+= slitDZ+layout[i][1] - else: targetL+= layout[i][1] - # put iron around - xTot = 400.*cm - yTot = 400.*cm - moreShieldingTopBot = G4EzVolume("moreShieldingTopBot") - moreShieldingTopBot.CreateBoxVolume(iron, xTot, yTot/2., targetL) - moreShieldingTopPhys = moreShieldingTopBot.PlaceIt(G4ThreeVector(0.,diameter/2. +spaceTopBot+yTot/4.,z0Pos + targetL/2.),1,snoopy) - moreShieldingBotPhys = moreShieldingTopBot.PlaceIt(G4ThreeVector(0.,-diameter/2.-spaceTopBot-yTot/4.,z0Pos + targetL/2.),1,snoopy) - moreShieldingSide = G4EzVolume("moreShieldingSide") - moreShieldingSide.CreateBoxVolume(iron, xTot/2., diameter+1.9*spaceTopBot, targetL) - moreShieldingLeftPhys = moreShieldingSide.PlaceIt(G4ThreeVector(diameter/2. +spaceSide+xTot/4.,0.,z0Pos + targetL/2.),1,snoopy) - moreShieldingRightPhys = moreShieldingSide.PlaceIt(G4ThreeVector(-diameter/2.-spaceSide-xTot/4.,0.,z0Pos + targetL/2.),1,snoopy) - # = 0.1m3 = 2t - # a hadron absorber is placed - absorberL = 2*150.*cm - absorber = G4EzVolume("Absorber") - # inner radius outer radius length - absorber.CreateTubeVolume(iron, 0., 400.*cm, absorberL/2.) - absorberPhys = absorber.PlaceIt(G4ThreeVector(0.,0.,z0Pos+targetL+absorberL/2.+5.*cm),1,snoopy) - absorber.SetColor(G4Color(0.898,0.902,0.91,1.0)) - absorber.SetVisibility(True) - xx = G4VisAttributes() - xx.SetForceWireframe(True) - absorberlog = absorberPhys.GetLogicalVolume() - absorberlog.SetVisAttributes(xx) -# scoring plane - afterHadronZ = z0Pos+targetL+absorberL+5.1*cm - scorez = afterHadronZ - score = G4EzVolume("Score") - score.CreateTubeVolume(vac, 0., 20.*m, 1.*mm) - scorePhys = score.PlaceIt(G4ThreeVector(0.,0.,scorez),1,snoopy) - scoreLog = scorePhys.GetLogicalVolume() - g4py.ezgeom.Construct() + print("* Constructing geometry...") + # reset world material + vac = G4Material.GetMaterial("G4_Galactic") + g4py.ezgeom.SetWorldMaterial(vac) + g4py.ezgeom.ResizeWorld(world_r / 2.0, world_r / 2.0, world_r) + # a snoopy world is placed + global snoopy, snoopyPhys, scoreLog + snoopy = G4EzVolume("Snoopy") + snoopy.CreateTubeVolume(vac, 0.0, 20 * m, world_r / 2.0) + snoopyPhys = snoopy.PlaceIt(G4ThreeVector(0.0, 0.0, 0.0 * m)) + snoopyLog = snoopyPhys.GetLogicalVolume() + snoopy.SetVisibility(False) + # a target box is placed + global target, targetPhys + iron = G4Material.GetMaterial("G4_Fe") + air = G4Material.GetMaterial("G4_AIR") + water = G4Material.GetMaterial("G4_WATER") + tungsten = G4Material.GetMaterial("G4_W") + lead = G4Material.GetMaterial("G4_Pb") + alum = G4Material.GetMaterial("G4_Al") + elementMo = G4Element("Molybdenum", "Mo", 42.0, 95.94 * g / mole) + molybdenum = G4Material("molybdenum", 10.22 * g / cm3, 1) + molybdenum.AddElement(elementMo, 1.00) + # + if fullTungsten: + target = G4EzVolume("Target") + slit = G4EzVolume("Slit") + slitDZ = 0.5 * cm + targetDZ = 5.0 * cm + # target is sliced, 4 slits of 1cm, 10cm tungsten blocks + target.CreateTubeVolume(tungsten, 0.0, 25.0 * cm, targetDZ) + target.SetColor(G4Color(0.0, 0.5, 0.5, 1.0)) + target.SetVisibility(True) + # additional 5 interaction lengths + # targetOpt = G4EzVolume("TargetOpt") + # targetOpt.CreateTubeVolume(tungsten, 0., 25.*cm, 25.*cm) + # targetOpt.SetColor(G4Color(0.0,0.5,0.5,1.0)) + # targetOpt.SetVisibility(True) + slit.CreateTubeVolume(water, 0.0, 25.0 * cm, slitDZ) + slit.SetVisibility(False) + targetPhys = [] + slitPhys = [] + targetL = 0 * cm + z0Pos = -50.0 * m + for i in range(4): + targetPhys.append( + target.PlaceIt( + G4ThreeVector(0.0, 0.0, z0Pos + targetL + targetDZ), 1, snoopy + ) + ) + slitPhys.append( + slit.PlaceIt( + G4ThreeVector(0.0, 0.0, z0Pos + targetL + 2 * targetDZ + slitDZ), + 1, + snoopy, + ) + ) + targetL += 2 * (slitDZ + targetDZ) + targetPhys.append( + target.PlaceIt( + G4ThreeVector(0.0, 0.0, z0Pos + targetL + targetDZ), 1, snoopy + ) + ) + targetL += 2 * (targetDZ) + # put iron around + moreShielding = G4EzVolume("moreShielding") + moreShielding.CreateTubeVolume(iron, 30.0 * cm, 400.0 * cm, targetL / 2.0) + moreShieldingPhys = moreShielding.PlaceIt( + G4ThreeVector(0.0, 0.0, z0Pos + targetL / 2.0), 1, snoopy + ) + # + else: # new design with mixture Molybdaen and Tungsten + slitDZ = 0.5 * cm + diameter = 30.0 * cm + spaceTopBot = 10.0 * cm + spaceSide = 5.0 * cm + slit = G4EzVolume("Slit") + slit.CreateBoxVolume(water, diameter, diameter, slitDZ) + slit.SetVisibility(False) + targetPhys = [] + targetVol = [] + slitPhys = [] + targetL = 0 * cm + z0Pos = -50.0 * m + # material,length + layout = { + 1: [molybdenum, 8.0 * cm], + 2: [molybdenum, 2.5 * cm], + 3: [molybdenum, 2.5 * cm], + 4: [molybdenum, 2.5 * cm], + 5: [molybdenum, 2.5 * cm], + 6: [molybdenum, 2.5 * cm], + 7: [molybdenum, 2.5 * cm], + 8: [molybdenum, 2.5 * cm], + 9: [molybdenum, 5.0 * cm], + 10: [molybdenum, 5.0 * cm], + 11: [molybdenum, 6.5 * cm], + 12: [molybdenum, 8.0 * cm], + 13: [molybdenum, 8.0 * cm], + 14: [tungsten, 5.0 * cm], + 15: [tungsten, 8.0 * cm], + 16: [tungsten, 10.0 * cm], + 17: [tungsten, 35.0 * cm], + } + for i in range(1, 18): + targetVol.append(G4EzVolume("Target_Layer_" + str(i))) + targetVol[i - 1].CreateBoxVolume( + layout[i][0], diameter, diameter, layout[i][1] + ) + if layout[i][0] == tungsten: + targetVol[i - 1].SetColor(G4Color(0.0, 0.5, 0.5, 1.0)) + else: + targetVol[i - 1].SetColor(G4Color(0.3, 0.2, 0.5, 1.0)) + targetVol[i - 1].SetVisibility(True) + targetPhys.append( + targetVol[i - 1].PlaceIt( + G4ThreeVector(0.0, 0.0, z0Pos + targetL + layout[i][1] / 2.0), + 1, + snoopy, + ) + ) + if i < 17: + slitPhys.append( + slit.PlaceIt( + G4ThreeVector( + 0.0, 0.0, z0Pos + targetL + layout[i][1] + slitDZ / 2.0 + ), + 1, + snoopy, + ) + ) + targetL += slitDZ + layout[i][1] + else: + targetL += layout[i][1] + # put iron around + xTot = 400.0 * cm + yTot = 400.0 * cm + moreShieldingTopBot = G4EzVolume("moreShieldingTopBot") + moreShieldingTopBot.CreateBoxVolume(iron, xTot, yTot / 2.0, targetL) + moreShieldingTopPhys = moreShieldingTopBot.PlaceIt( + G4ThreeVector( + 0.0, diameter / 2.0 + spaceTopBot + yTot / 4.0, z0Pos + targetL / 2.0 + ), + 1, + snoopy, + ) + moreShieldingBotPhys = moreShieldingTopBot.PlaceIt( + G4ThreeVector( + 0.0, -diameter / 2.0 - spaceTopBot - yTot / 4.0, z0Pos + targetL / 2.0 + ), + 1, + snoopy, + ) + moreShieldingSide = G4EzVolume("moreShieldingSide") + moreShieldingSide.CreateBoxVolume( + iron, xTot / 2.0, diameter + 1.9 * spaceTopBot, targetL + ) + moreShieldingLeftPhys = moreShieldingSide.PlaceIt( + G4ThreeVector( + diameter / 2.0 + spaceSide + xTot / 4.0, 0.0, z0Pos + targetL / 2.0 + ), + 1, + snoopy, + ) + moreShieldingRightPhys = moreShieldingSide.PlaceIt( + G4ThreeVector( + -diameter / 2.0 - spaceSide - xTot / 4.0, 0.0, z0Pos + targetL / 2.0 + ), + 1, + snoopy, + ) + # = 0.1m3 = 2t + # a hadron absorber is placed + absorberL = 2 * 150.0 * cm + absorber = G4EzVolume("Absorber") + # inner radius outer radius length + absorber.CreateTubeVolume(iron, 0.0, 400.0 * cm, absorberL / 2.0) + absorberPhys = absorber.PlaceIt( + G4ThreeVector(0.0, 0.0, z0Pos + targetL + absorberL / 2.0 + 5.0 * cm), 1, snoopy + ) + absorber.SetColor(G4Color(0.898, 0.902, 0.91, 1.0)) + absorber.SetVisibility(True) + xx = G4VisAttributes() + xx.SetForceWireframe(True) + absorberlog = absorberPhys.GetLogicalVolume() + absorberlog.SetVisAttributes(xx) + # scoring plane + afterHadronZ = z0Pos + targetL + absorberL + 5.1 * cm + scorez = afterHadronZ + score = G4EzVolume("Score") + score.CreateTubeVolume(vac, 0.0, 20.0 * m, 1.0 * mm) + scorePhys = score.PlaceIt(G4ThreeVector(0.0, 0.0, scorez), 1, snoopy) + scoreLog = scorePhys.GetLogicalVolume() + g4py.ezgeom.Construct() + g4py.NISTmaterials.Construct() -#print Geant4.gMaterialTable +# print Geant4.gMaterialTable xx = G4physicslists.GetReferencePhysList(model) if rangeCut: - xx.SetCutValue(10.,'gamma') - xx.SetCutValue(10.,'e-') - xx.SetCutValue(10.,'e+') + xx.SetCutValue(10.0, "gamma") + xx.SetCutValue(10.0, "e-") + xx.SetCutValue(10.0, "e+") gRunManager.SetUserInitialization(xx) myGE = MyGeneratorAction() gRunManager.SetUserAction(myGE) # -if debug: myTA= MyTrackingActionD() -else: myTA= MyTrackingAction() +if debug: + myTA = MyTrackingActionD() +else: + myTA = MyTrackingAction() gRunManager.SetUserAction(myTA) # ConstructGeom() -myRA= MyRunAction() +myRA = MyRunAction() gRunManager.SetUserAction(myRA) -myEA= MyEventAction() +myEA = MyEventAction() gRunManager.SetUserAction(myEA) -mySA= MySteppingAction() -if withStepping : gRunManager.SetUserAction(mySA) +mySA = MySteppingAction() +if withStepping: + gRunManager.SetUserAction(mySA) # initialize gRunManager.Initialize() # scoring should be set after geometry construction -sens = ScoreSD('Score') +sens = ScoreSD("Score") scoreLog.SetSensitiveDetector(sens) if local and not particleGun: - gApplyUICommand('/vis/drawVolume') - gApplyUICommand('/vis/scene/add/trajectories') - gApplyUICommand('/vis/viewer/zoom 1.5') + gApplyUICommand("/vis/drawVolume") + gApplyUICommand("/vis/scene/add/trajectories") + gApplyUICommand("/vis/viewer/zoom 1.5") t0 = time.time() gRunManager.BeamOn(nev) t1 = time.time() -print('Time used',t1-t0, ' seconds') +print("Time used", t1 - t0, " seconds") for x in myTimer: - print(x,myTimer[x]) + print(x, myTimer[x]) logger.info("output directory: %s" % work_dir) # save arguments and GIT tags import saveBasicParameters -saveBasicParameters.execute(f,args,'SHiP-Params') + +saveBasicParameters.execute(f, args, "SHiP-Params") if local: - wrld = snoopyPhys.GetMotherLogical() - parser = G4GDMLParser() - geofile = work_dir+'/g4Geom.gdml' - if os.path.isfile(geofile): os.system('rm '+geofile) - parser.Write('g4Geom.gdml',wrld) - ROOT.TGeoManager() - geomgr = ROOT.gGeoManager - geomgr.Import('g4Geom.gdml','world','new') - ROOT.gGeoManager.CheckOverlaps() - ROOT.gGeoManager.PrintOverlaps() - geomgr.GetTopVolume().Draw('ogl') + wrld = snoopyPhys.GetMotherLogical() + parser = G4GDMLParser() + geofile = work_dir + "/g4Geom.gdml" + if os.path.isfile(geofile): + os.system("rm " + geofile) + parser.Write("g4Geom.gdml", wrld) + ROOT.TGeoManager() + geomgr = ROOT.gGeoManager + geomgr.Import("g4Geom.gdml", "world", "new") + ROOT.gGeoManager.CheckOverlaps() + ROOT.gGeoManager.PrintOverlaps() + geomgr.GetTopVolume().Draw("ogl") diff --git a/muonShieldOptimization/g4Ex_gap_mergeFiles.py b/muonShieldOptimization/g4Ex_gap_mergeFiles.py index e624610ebf..9d428f444f 100644 --- a/muonShieldOptimization/g4Ex_gap_mergeFiles.py +++ b/muonShieldOptimization/g4Ex_gap_mergeFiles.py @@ -1,200 +1,289 @@ # result_1Bn_ecut_5.root 1E9 with Ecut > 5 GeV # result_0.1Bn_ecut_0.5.root 1E8 with Ecut > 0.5 GeV -Yandex = False # False -Yandex2 = False # summer 2015 production, 10B, Ecut>10GeV, Mo/W/ target -Yandex3 = True # spring 2016 production, 10B, Ecut>10GeV, Mo/W/ target, record start of track +Yandex = False # False +Yandex2 = False # summer 2015 production, 10B, Ecut>10GeV, Mo/W/ target +Yandex3 = ( + True # spring 2016 production, 10B, Ecut>10GeV, Mo/W/ target, record start of track +) afterHadronAbsorber = False -JPsi = False # True +JPsi = False # True MoTarget = False -Tau = False +Tau = False -import ROOT,os +import os from array import array -from ROOT import TDatabasePDG,TMath,gDirectory + +import ROOT +from ROOT import TDatabasePDG, TMath, gDirectory from rootUtils import * -pdg = TDatabasePDG() -mu = pdg.GetParticle(13) -Mmu = mu.Mass() + +pdg = TDatabasePDG() +mu = pdg.GetParticle(13) +Mmu = mu.Mass() Mmu2 = Mmu * Mmu if Yandex: - stats = {5.:[1E9,1E9],0.5:[1E8]} - files = {5.:['$SHIPSOFT/data/result_1Bn_ecut_5.root','$SHIPSOFT/data/result_1Bn_ecut_5-v02.root'],0.5:['$SHIPSOFT/data/result_0.1Bn_ecut_0.5.root']} - fnew = 'pythia8_Geant4_total_Yandex.root' + stats = {5.0: [1e9, 1e9], 0.5: [1e8]} + files = { + 5.0: [ + "$SHIPSOFT/data/result_1Bn_ecut_5.root", + "$SHIPSOFT/data/result_1Bn_ecut_5-v02.root", + ], + 0.5: ["$SHIPSOFT/data/result_0.1Bn_ecut_0.5.root"], + } + fnew = "pythia8_Geant4_total_Yandex.root" if Yandex2: - stats = {10.:[1E10]} - files = {10.:['$SHIPSOFT/data/result_10Bn_ecut_10.root']} - fnew = 'pythia8_Geant4_total_Yandex2.root' + stats = {10.0: [1e10]} + files = {10.0: ["$SHIPSOFT/data/result_10Bn_ecut_10.root"]} + fnew = "pythia8_Geant4_total_Yandex2.root" if Yandex3: - stats = {10.:[10.05E9]} - files = {10.:['/media/truf/Elements/Data/HNL/ShipSoft/data/Yandex-April2016_10.05B.root']} - fnew = 'pythia8_Geant4_total_Yandex3.root' + stats = {10.0: [10.05e9]} + files = { + 10.0: [ + "/media/truf/Elements/Data/HNL/ShipSoft/data/Yandex-April2016_10.05B.root" + ] + } + fnew = "pythia8_Geant4_total_Yandex3.root" if JPsi: - BR = 0.05961 - stats = {10.:[]} - files = {10.:[]} - jobs = {'b6276c506a_g4Ex_gap_':['53','54','55','56'],'b602f257b0_g4Ex_gap_':['52']} - nevts = 0 - ntot = 0 - tag = '#events=' - for job in jobs: - for run in jobs[job]: - for i in range(10): - path = job+run+str(i)+'/' - fl = open(path+'log'+run+str(i)) - for l in fl.readlines(): - k = l.find(tag) - if k<0: continue - nevts = int( l[k+len(tag):].replace(')','')) - fl.close() - files[10.].append(path+'pythia8_Geant4_'+run+str(i)+'_10.0.root') - stats[10.].append(nevts/BR) - ntot += nevts/BR - print(run+str(i),' --> nevts = ',nevts) - fnew = 'pythia8_Geant4_total_Jpsi.root' - print('total statistics ',ntot/1.E9,' *1E9') + BR = 0.05961 + stats = {10.0: []} + files = {10.0: []} + jobs = { + "b6276c506a_g4Ex_gap_": ["53", "54", "55", "56"], + "b602f257b0_g4Ex_gap_": ["52"], + } + nevts = 0 + ntot = 0 + tag = "#events=" + for job in jobs: + for run in jobs[job]: + for i in range(10): + path = job + run + str(i) + "/" + fl = open(path + "log" + run + str(i)) + for l in fl.readlines(): + k = l.find(tag) + if k < 0: + continue + nevts = int(l[k + len(tag) :].replace(")", "")) + fl.close() + files[10.0].append( + path + "pythia8_Geant4_" + run + str(i) + "_10.0.root" + ) + stats[10.0].append(nevts / BR) + ntot += nevts / BR + print(run + str(i), " --> nevts = ", nevts) + fnew = "pythia8_Geant4_total_Jpsi.root" + print("total statistics ", ntot / 1.0e9, " *1E9") # if Tau: - BR = 0.0554 - stats = {0.:[]} - files = {0.:[]} - jobs = {'b63edb1b12_g4Ex_gap_':['13']} - nevts = 0 - ntot = 0 - tag = '#events=' - for job in jobs: - for run in jobs[job]: - for i in range(10): - path = job+run+str(i)+'/' - if not 'log'+run+str(i) in os.listdir(path): continue - fl = open(path+'log'+run+str(i)) - for l in fl.readlines(): - k = l.find(tag) - if k<0: continue - nevts = int( l[k+len(tag):].replace(')','')) - fl.close() - files[0.].append(path+'pythia8_Geant4_'+run+str(i)+'_0.0.root') - stats[0.].append(nevts/BR) - ntot += nevts/BR - print(run+str(i),' --> nevts = ',nevts) - fnew = 'pythia8_Geant4_total_tauOnly_MoTarget_E0.root' - print('total statistics ',ntot/1.E9,' *1E9') + BR = 0.0554 + stats = {0.0: []} + files = {0.0: []} + jobs = {"b63edb1b12_g4Ex_gap_": ["13"]} + nevts = 0 + ntot = 0 + tag = "#events=" + for job in jobs: + for run in jobs[job]: + for i in range(10): + path = job + run + str(i) + "/" + if not "log" + run + str(i) in os.listdir(path): + continue + fl = open(path + "log" + run + str(i)) + for l in fl.readlines(): + k = l.find(tag) + if k < 0: + continue + nevts = int(l[k + len(tag) :].replace(")", "")) + fl.close() + files[0.0].append(path + "pythia8_Geant4_" + run + str(i) + "_0.0.root") + stats[0.0].append(nevts / BR) + ntot += nevts / BR + print(run + str(i), " --> nevts = ", nevts) + fnew = "pythia8_Geant4_total_tauOnly_MoTarget_E0.root" + print("total statistics ", ntot / 1.0e9, " *1E9") # if MoTarget: - stats = {} - files = {} - jobs = {'b64a4b817c.cern.ch_g4Ex_gap_':['60','61','62','65','66'],'b63edb1b12_g4Ex_gap_':['63','75','77','78','81','83','85','87','90','93','95'],\ - 'b65dfad864_g4Ex_gap_':['70'],'b6276c506a_g4Ex_gap_':['71'],'b6e72959f6_g4Ex_gap_':['72'],\ - 'b6429e4f38.cern.ch_g4Ex_gap_':['73','74','76','79','80','82','84','86','88','89','91','94','96'] } - nevts = 0 - ntot = 0 - tag = '#events=' - for job in jobs: - for run in jobs[job]: - for i in range(10): - path = job+run+str(i)+'/' - fl = open(path+'log'+run+str(i)) + stats = {} + files = {} + jobs = { + "b64a4b817c.cern.ch_g4Ex_gap_": ["60", "61", "62", "65", "66"], + "b63edb1b12_g4Ex_gap_": [ + "63", + "75", + "77", + "78", + "81", + "83", + "85", + "87", + "90", + "93", + "95", + ], + "b65dfad864_g4Ex_gap_": ["70"], + "b6276c506a_g4Ex_gap_": ["71"], + "b6e72959f6_g4Ex_gap_": ["72"], + "b6429e4f38.cern.ch_g4Ex_gap_": [ + "73", + "74", + "76", + "79", + "80", + "82", + "84", + "86", + "88", + "89", + "91", + "94", + "96", + ], + } nevts = 0 - for l in fl.readlines(): - k = l.find(tag) - if k<0: continue - nevts = int( l[k+len(tag):].replace(')','')) - fl.close() - if nevts==0: continue - for r in os.listdir(path): - if r.find('.root')<0: continue - ecut = float(r.split('.root')[0].split('_')[3]) - if ecut not in stats: - stats[ecut] = [] - files[ecut] = [] - files[ecut].append(path+r) - stats[ecut].append(nevts) - ntot += nevts - print(run+str(i),' --> nevts = ',nevts) - fnew = 'pythia8_Geant4_total_MoTarget.root' - print('total statistics ',ntot/1.E9,' *1E9') + ntot = 0 + tag = "#events=" + for job in jobs: + for run in jobs[job]: + for i in range(10): + path = job + run + str(i) + "/" + fl = open(path + "log" + run + str(i)) + nevts = 0 + for l in fl.readlines(): + k = l.find(tag) + if k < 0: + continue + nevts = int(l[k + len(tag) :].replace(")", "")) + fl.close() + if nevts == 0: + continue + for r in os.listdir(path): + if r.find(".root") < 0: + continue + ecut = float(r.split(".root")[0].split("_")[3]) + if ecut not in stats: + stats[ecut] = [] + files[ecut] = [] + files[ecut].append(path + r) + stats[ecut].append(nevts) + ntot += nevts + print(run + str(i), " --> nevts = ", nevts) + fnew = "pythia8_Geant4_total_MoTarget.root" + print("total statistics ", ntot / 1.0e9, " *1E9") ntot = {} for ecut in stats: - ntot[ecut] = 0 - for s in stats[ecut]: ntot[ecut]+=s + ntot[ecut] = 0 + for s in stats[ecut]: + ntot[ecut] += s print(ntot) -h={} -def makeFinalNtuples(norm=5.E13,opt=''): - cuts = {'':'','_onlyMuons':'abs(id)==13','_onlyNeutrinos':'abs(id)==12||abs(id)==14||abs(id)==16'} - first = True - tuples = '' - fn = 1 - for ecut in stats: - for i in range(len(stats[ecut])): - h[fn] = ROOT.TFile(files[ecut][i]) - t = h[fn].FindObjectAny("pythia8-Geant4") - fn+=1 - if first: - first = False - for l in t.GetListOfLeaves(): tuples += l.GetName()+':' - tuples+='w:ecut' - fxx = fnew.replace('.root',opt+'.root') - if opt!='': fxx = fxx.replace('_total','') - h['N'] = ROOT.TFile(fxx, 'RECREATE') - print('new file created',fxx) - if afterHadronAbsorber: - h['ntuple'] = ROOT.TNtuple("pythia8-Geant4","flux after 3m hadron absorber",tuples) - else: - h['ntuple'] = ROOT.TNtuple("pythia8-Geant4","flux after 3m hadron absorber, position&momentum before",tuples) - gROOT.cd() - t.SetEventList(0) - t.Draw(">>temp",cuts[opt]) - temp = gROOT.FindObjectAny('temp') - t.SetEventList(temp) - nev = temp.GetN() - for iev in range(nev) : - rc = t.GetEntry(temp.GetEntry(iev)) - leaves = t.GetListOfLeaves() - vlist = array('f') - for x in range(leaves.GetEntries()): - vlist.append( leaves.At(x).GetValue() ) - # get kinetic energy "id:px:py:pz:x:y:z:ox:oy:oz:pythiaid:parentid" - # since 2016 "id:px:py:pz:x:y:z:opx:opy:opz:ox:oy:oz:pythiaid:parentid" - Psq = vlist[1]**2+vlist[2]**2+vlist[3]**2 - if abs(vlist[0])==13: Ekin = ROOT.TMath.Sqrt(Mmu2+Psq)-Mmu - else: Ekin = ROOT.TMath.Sqrt(Psq) - if Yandex: - if Ekin < ecut : continue - if Ekin > 5. : weight = norm/(ntot[5.] + ntot[0.5]) - else : weight = norm/(ntot[0.5]) - if Yandex2 or Yandex3: - if Ekin < ecut : continue - weight = norm/(ntot[10.]) - if JPsi : weight = norm/(ntot[10.]) - if Tau : weight = norm/(ntot[0.]) - if MoTarget: - if Ekin < ecut : continue - if Ekin > 50. : weight = norm/(ntot[0.5] + ntot[10.] + ntot[20.]+ ntot[50.]) - elif Ekin > 20. : weight = norm/(ntot[0.5] + ntot[10.] + ntot[20.]) - elif Ekin > 10. : weight = norm/(ntot[0.5] + ntot[10.]) - else : weight = norm/(ntot[0.5]) - vlist.append(weight) - vlist.append( float(ecut) ) - h['ntuple'].Fill(vlist) - h['N'].cd() - h['ntuple'].Write() +h = {} + + +def makeFinalNtuples(norm=5.0e13, opt=""): + cuts = { + "": "", + "_onlyMuons": "abs(id)==13", + "_onlyNeutrinos": "abs(id)==12||abs(id)==14||abs(id)==16", + } + first = True + tuples = "" + fn = 1 + for ecut in stats: + for i in range(len(stats[ecut])): + h[fn] = ROOT.TFile(files[ecut][i]) + t = h[fn].FindObjectAny("pythia8-Geant4") + fn += 1 + if first: + first = False + for l in t.GetListOfLeaves(): + tuples += l.GetName() + ":" + tuples += "w:ecut" + fxx = fnew.replace(".root", opt + ".root") + if opt != "": + fxx = fxx.replace("_total", "") + h["N"] = ROOT.TFile(fxx, "RECREATE") + print("new file created", fxx) + if afterHadronAbsorber: + h["ntuple"] = ROOT.TNtuple( + "pythia8-Geant4", "flux after 3m hadron absorber", tuples + ) + else: + h["ntuple"] = ROOT.TNtuple( + "pythia8-Geant4", + "flux after 3m hadron absorber, position&momentum before", + tuples, + ) + gROOT.cd() + t.SetEventList(0) + t.Draw(">>temp", cuts[opt]) + temp = gROOT.FindObjectAny("temp") + t.SetEventList(temp) + nev = temp.GetN() + for iev in range(nev): + rc = t.GetEntry(temp.GetEntry(iev)) + leaves = t.GetListOfLeaves() + vlist = array("f") + for x in range(leaves.GetEntries()): + vlist.append(leaves.At(x).GetValue()) + # get kinetic energy "id:px:py:pz:x:y:z:ox:oy:oz:pythiaid:parentid" + # since 2016 "id:px:py:pz:x:y:z:opx:opy:opz:ox:oy:oz:pythiaid:parentid" + Psq = vlist[1] ** 2 + vlist[2] ** 2 + vlist[3] ** 2 + if abs(vlist[0]) == 13: + Ekin = ROOT.TMath.Sqrt(Mmu2 + Psq) - Mmu + else: + Ekin = ROOT.TMath.Sqrt(Psq) + if Yandex: + if Ekin < ecut: + continue + if Ekin > 5.0: + weight = norm / (ntot[5.0] + ntot[0.5]) + else: + weight = norm / (ntot[0.5]) + if Yandex2 or Yandex3: + if Ekin < ecut: + continue + weight = norm / (ntot[10.0]) + if JPsi: + weight = norm / (ntot[10.0]) + if Tau: + weight = norm / (ntot[0.0]) + if MoTarget: + if Ekin < ecut: + continue + if Ekin > 50.0: + weight = norm / ( + ntot[0.5] + ntot[10.0] + ntot[20.0] + ntot[50.0] + ) + elif Ekin > 20.0: + weight = norm / (ntot[0.5] + ntot[10.0] + ntot[20.0]) + elif Ekin > 10.0: + weight = norm / (ntot[0.5] + ntot[10.0]) + else: + weight = norm / (ntot[0.5]) + vlist.append(weight) + vlist.append(float(ecut)) + h["ntuple"].Fill(vlist) + h["N"].cd() + h["ntuple"].Write() + def interactionRegion(): - import rootUtils as ut - import shipunit as u - f = ROOT.TFile('pythia8_Geant4_13_350.0.root') - sTree=f.FindObjectAny('pythia8-Geant4') - ut.bookHist(h,'originz','z',100,-50.5,-49.) - ut.bookHist(h,'originzr','r vs z',100,-50.5,-49.,100,0.,0.5) - ut.bookHist(h,'originxy','x vs y',100,-0.5,0.5,100,-0.5,0.5) - ROOT.gROOT.cd() - sTree.Draw('z>>originz') - sTree.Draw('1000*sqrt(x*x+y*y):z>>originzr') - sTree.Draw('1000*x:1000*y>>originxy') + import rootUtils as ut + import shipunit as u + + f = ROOT.TFile("pythia8_Geant4_13_350.0.root") + sTree = f.FindObjectAny("pythia8-Geant4") + ut.bookHist(h, "originz", "z", 100, -50.5, -49.0) + ut.bookHist(h, "originzr", "r vs z", 100, -50.5, -49.0, 100, 0.0, 0.5) + ut.bookHist(h, "originxy", "x vs y", 100, -0.5, 0.5, 100, -0.5, 0.5) + ROOT.gROOT.cd() + sTree.Draw("z>>originz") + sTree.Draw("1000*sqrt(x*x+y*y):z>>originzr") + sTree.Draw("1000*x:1000*y>>originxy") -makeFinalNtuples(norm=5.E13,opt='') -makeFinalNtuples(norm=5.E13,opt='_onlyMuons') -makeFinalNtuples(norm=5.E13,opt='_onlyNeutrinos') +makeFinalNtuples(norm=5.0e13, opt="") +makeFinalNtuples(norm=5.0e13, opt="_onlyMuons") +makeFinalNtuples(norm=5.0e13, opt="_onlyNeutrinos") diff --git a/muonShieldOptimization/makeMuonDIS.py b/muonShieldOptimization/makeMuonDIS.py index 7337abfeec..686ac35098 100644 --- a/muonShieldOptimization/makeMuonDIS.py +++ b/muonShieldOptimization/makeMuonDIS.py @@ -1,113 +1,137 @@ -import ROOT,time,os,sys -nJob = 2 -nMult = 10 # number of events / muon -muonIn = '$SHIPSOFT/data/muConcrete.root' +import os +import sys +import time + +import ROOT + +nJob = 2 +nMult = 10 # number of events / muon +muonIn = "$SHIPSOFT/data/muConcrete.root" nPerJob = 20000 -if len(sys.argv)>1: nJob = int(sys.argv[1]) -if len(sys.argv)>2: nMult = int(sys.argv[2]) -if len(sys.argv)>3: muonIn = sys.argv[3] -if len(sys.argv)>4: nPerJob = int(sys.argv[4]) +if len(sys.argv) > 1: + nJob = int(sys.argv[1]) +if len(sys.argv) > 2: + nMult = int(sys.argv[2]) +if len(sys.argv) > 3: + muonIn = sys.argv[3] +if len(sys.argv) > 4: + nPerJob = int(sys.argv[4]) # from array import array + PDG = ROOT.TDatabasePDG.Instance() myPythia = ROOT.TPythia6() -myPythia.SetMSEL(2) # msel 2 includes diffractive parts -myPythia.SetPARP(2,2) # To get below 10 GeV, you have to change PARP(2) -for kf in [211,321,130,310,3112,3122,3222,3312,3322,3334]: - kc = myPythia.Pycomp(kf) - myPythia.SetMDCY(kc,1,0) +myPythia.SetMSEL(2) # msel 2 includes diffractive parts +myPythia.SetPARP(2, 2) # To get below 10 GeV, you have to change PARP(2) +for kf in [211, 321, 130, 310, 3112, 3122, 3222, 3312, 3322, 3334]: + kc = myPythia.Pycomp(kf) + myPythia.SetMDCY(kc, 1, 0) masssq = {} + def getMasssq(pid): - apid = abs(int(pid)) - if not apid in masssq: - masssq[apid] = PDG.GetParticle(apid).Mass()**2 - return masssq[apid] + apid = abs(int(pid)) + if not apid in masssq: + masssq[apid] = PDG.GetParticle(apid).Mass() ** 2 + return masssq[apid] -R = int(time.time()%900000000) -myPythia.SetMRPY(1,R) -mutype = {-13:'gamma/mu+',13:'gamma/mu-'} + +R = int(time.time() % 900000000) +myPythia.SetMRPY(1, R) +mutype = {-13: "gamma/mu+", 13: "gamma/mu-"} # DIS event # incoming muon, id:px:py:pz:x:y:z:w # outgoing particles, id:px:py:pz -fout = ROOT.TFile('muonDis_'+str(nJob)+'.root','recreate') -dTree = ROOT.TTree('DIS','muon DIS') -iMuon = ROOT.TClonesArray("TVectorD") -iMuonBranch = dTree.Branch("InMuon",iMuon,32000,-1) -dPart = ROOT.TClonesArray("TVectorD") -dPartBranch = dTree.Branch("Particles",dPart,32000,-1) +fout = ROOT.TFile("muonDis_" + str(nJob) + ".root", "recreate") +dTree = ROOT.TTree("DIS", "muon DIS") +iMuon = ROOT.TClonesArray("TVectorD") +iMuonBranch = dTree.Branch("InMuon", iMuon, 32000, -1) +dPart = ROOT.TClonesArray("TVectorD") +dPartBranch = dTree.Branch("Particles", dPart, 32000, -1) # read file with muons hitting concrete wall -fin = ROOT.TFile(muonIn) # id:px:py:pz:x:y:z:w +fin = ROOT.TFile(muonIn) # id:px:py:pz:x:y:z:w sTree = fin.muons -def rotate(ctheta,stheta,cphi,sphi,px,py,pz): - #rotate around y-axis - px1=ctheta*px+stheta*pz - pzr=-stheta*px+ctheta*pz - #rotate around z-axis - pxr=cphi*px1-sphi*py - pyr=sphi*px1+cphi*py - return pxr,pyr,pzr + +def rotate(ctheta, stheta, cphi, sphi, px, py, pz): + # rotate around y-axis + px1 = ctheta * px + stheta * pz + pzr = -stheta * px + ctheta * pz + # rotate around z-axis + pxr = cphi * px1 - sphi * py + pyr = sphi * px1 + cphi * py + return pxr, pyr, pzr + nTOT = sTree.GetEntries() -nStart = nPerJob*nJob -nEnd = min(nTOT,nStart + nPerJob) -if muonIn.find('Concrete')<0: - nStart = 0 - nEnd = nTOT +nStart = nPerJob * nJob +nEnd = min(nTOT, nStart + nPerJob) +if muonIn.find("Concrete") < 0: + nStart = 0 + nEnd = nTOT # stop pythia printout during loop myPythia.SetMSTU(11, 11) -print("start production ",nStart,nEnd) +print("start production ", nStart, nEnd) nMade = 0 -for k in range(nStart,nEnd): - rc = sTree.GetEvent(k) - # make n events / muon - px,py,pz = sTree.px,sTree.py,sTree.pz - x,y,z = sTree.x,sTree.y,sTree.z - pid,w = sTree.id,sTree.w - p = ROOT.TMath.Sqrt(px*px+py*py+pz*pz) - E = ROOT.TMath.Sqrt(getMasssq(pid)+p*p) - # px=p*sin(theta)cos(phi),py=p*sin(theta)sin(phi),pz=p*cos(theta) - theta = ROOT.TMath.ACos(pz/p) - phi = ROOT.TMath.ATan2(py,px) - ctheta,stheta = ROOT.TMath.Cos(theta),ROOT.TMath.Sin(theta) - cphi,sphi = ROOT.TMath.Cos(phi),ROOT.TMath.Sin(phi) - mu = array('d',[pid,px,py,pz,E,x,y,z,w]) - myPythia.Initialize('FIXT',mutype[pid],'p+',p) - for n in range(nMult): - dPart.Clear() - iMuon.Clear() - tca_vec = iMuon.ConstructedAt(0) - muPart = ROOT.TVectorD(9, mu) - tca_vec.ResizeTo(muPart) - ROOT.std.swap(tca_vec, muPart) - myPythia.GenerateEvent() -# remove all unnecessary stuff - myPythia.Pyedit(2) - for itrk in range(1,myPythia.GetN()+1): - did = myPythia.GetK(itrk,2) - dpx,dpy,dpz = rotate(ctheta,stheta,cphi,sphi,myPythia.GetP(itrk,1),myPythia.GetP(itrk,2),myPythia.GetP(itrk,3)) - psq = dpx**2+dpy**2+dpz**2 - E = ROOT.TMath.Sqrt(getMasssq(did)+psq) - m = array('d',[did,dpx,dpy,dpz,E]) - part = ROOT.TVectorD(5,m) -# copy to branch - nPart = dPart.GetEntries() - if dPart.GetSize() == nPart: dPart.Expand(nPart+10) - tca_vec = dPart.ConstructedAt(nPart) - tca_vec.ResizeTo(part) - ROOT.std.swap(tca_vec, part) - nMade+=1 - if nMade%10000==0: print('made so far ',nMade) - dTree.Fill() +for k in range(nStart, nEnd): + rc = sTree.GetEvent(k) + # make n events / muon + px, py, pz = sTree.px, sTree.py, sTree.pz + x, y, z = sTree.x, sTree.y, sTree.z + pid, w = sTree.id, sTree.w + p = ROOT.TMath.Sqrt(px * px + py * py + pz * pz) + E = ROOT.TMath.Sqrt(getMasssq(pid) + p * p) + # px=p*sin(theta)cos(phi),py=p*sin(theta)sin(phi),pz=p*cos(theta) + theta = ROOT.TMath.ACos(pz / p) + phi = ROOT.TMath.ATan2(py, px) + ctheta, stheta = ROOT.TMath.Cos(theta), ROOT.TMath.Sin(theta) + cphi, sphi = ROOT.TMath.Cos(phi), ROOT.TMath.Sin(phi) + mu = array("d", [pid, px, py, pz, E, x, y, z, w]) + myPythia.Initialize("FIXT", mutype[pid], "p+", p) + for n in range(nMult): + dPart.Clear() + iMuon.Clear() + tca_vec = iMuon.ConstructedAt(0) + muPart = ROOT.TVectorD(9, mu) + tca_vec.ResizeTo(muPart) + ROOT.std.swap(tca_vec, muPart) + myPythia.GenerateEvent() + # remove all unnecessary stuff + myPythia.Pyedit(2) + for itrk in range(1, myPythia.GetN() + 1): + did = myPythia.GetK(itrk, 2) + dpx, dpy, dpz = rotate( + ctheta, + stheta, + cphi, + sphi, + myPythia.GetP(itrk, 1), + myPythia.GetP(itrk, 2), + myPythia.GetP(itrk, 3), + ) + psq = dpx**2 + dpy**2 + dpz**2 + E = ROOT.TMath.Sqrt(getMasssq(did) + psq) + m = array("d", [did, dpx, dpy, dpz, E]) + part = ROOT.TVectorD(5, m) + # copy to branch + nPart = dPart.GetEntries() + if dPart.GetSize() == nPart: + dPart.Expand(nPart + 10) + tca_vec = dPart.ConstructedAt(nPart) + tca_vec.ResizeTo(part) + ROOT.std.swap(tca_vec, part) + nMade += 1 + if nMade % 10000 == 0: + print("made so far ", nMade) + dTree.Fill() fout.cd() dTree.Write() myPythia.SetMSTU(11, 6) -print("created nJob ",nJob,':',nStart,' - ',nEnd," events") +print("created nJob ", nJob, ":", nStart, " - ", nEnd, " events") diff --git a/muonShieldOptimization/makeMuonEM.py b/muonShieldOptimization/makeMuonEM.py index bdbdc4246d..a66b4ffc9a 100644 --- a/muonShieldOptimization/makeMuonEM.py +++ b/muonShieldOptimization/makeMuonEM.py @@ -1,51 +1,63 @@ -import ROOT,time,os,sys -nJob = 1 -nMult = 1000 # 100000 # number of events / muon -muonIn = '/media/Data/HNL/muVetoDIS/muDISVetoCounter.root' +import os +import sys +import time + +import ROOT + +nJob = 1 +nMult = 1000 # 100000 # number of events / muon +muonIn = "/media/Data/HNL/muVetoDIS/muDISVetoCounter.root" # from array import array + PDG = ROOT.TDatabasePDG.Instance() masssq = {} + def getMasssq(pid): - apid = abs(int(pid)) - if not apid in masssq: - masssq[apid] = PDG.GetParticle(apid).Mass()**2 - return masssq[apid] + apid = abs(int(pid)) + if not apid in masssq: + masssq[apid] = PDG.GetParticle(apid).Mass() ** 2 + return masssq[apid] + # prepare muon input for FairShip/Geant4 processing # incoming muon, id:px:py:pz:x:y:z:ox:oy:oz:pythiaid:parentid:ecut:w # just duplicate muon n times, rather stupid job -fout = ROOT.TFile('muonEm_'+str(nJob)+'.root','recreate') -dTree = ROOT.TNtuple("pythia8-Geant4","muons for EM studies","id:px:py:pz:x:y:z:ox:oy:oz:pythiaid:parentid:ecut:w") +fout = ROOT.TFile("muonEm_" + str(nJob) + ".root", "recreate") +dTree = ROOT.TNtuple( + "pythia8-Geant4", + "muons for EM studies", + "id:px:py:pz:x:y:z:ox:oy:oz:pythiaid:parentid:ecut:w", +) # read file with muons hitting concrete wall -fin = ROOT.TFile(muonIn) # id:px:py:pz:x:y:z:w +fin = ROOT.TFile(muonIn) # id:px:py:pz:x:y:z:w sTree = fin.muons for k in range(sTree.GetEntries()): - rc = sTree.GetEvent(k) - # make n events / muon - px,py,pz = sTree.px,sTree.py,sTree.pz - x,y,z = sTree.x,sTree.y,sTree.z - pid,w = sTree.id,sTree.w - p = ROOT.TMath.Sqrt(px*px+py*py+pz*pz) - E = ROOT.TMath.Sqrt(getMasssq(pid)+p*p) - mu = array('d',[pid,px,py,pz,E,x,y,z,w]) - muPart = ROOT.TVectorD(9,mu) - for n in range(nMult): - dPart.Clear() - iMuon.Clear() - iMuon[0] = muPart - m = array('d',[pid,px,py,pz,E]) - part = ROOT.TVectorD(5,m) -# copy to branch - nPart = dPart.GetEntries() - dPart[nPart] = part - dTree.Fill() + rc = sTree.GetEvent(k) + # make n events / muon + px, py, pz = sTree.px, sTree.py, sTree.pz + x, y, z = sTree.x, sTree.y, sTree.z + pid, w = sTree.id, sTree.w + p = ROOT.TMath.Sqrt(px * px + py * py + pz * pz) + E = ROOT.TMath.Sqrt(getMasssq(pid) + p * p) + mu = array("d", [pid, px, py, pz, E, x, y, z, w]) + muPart = ROOT.TVectorD(9, mu) + for n in range(nMult): + dPart.Clear() + iMuon.Clear() + iMuon[0] = muPart + m = array("d", [pid, px, py, pz, E]) + part = ROOT.TVectorD(5, m) + # copy to branch + nPart = dPart.GetEntries() + dPart[nPart] = part + dTree.Fill() fout.cd() dTree.Write() -print("created",sTree.GetEntries()*nMult," events") +print("created", sTree.GetEntries() * nMult, " events") diff --git a/muonShieldOptimization/muDIS_mergeFiles.py b/muonShieldOptimization/muDIS_mergeFiles.py index c44372d0d0..3038bb7bb7 100644 --- a/muonShieldOptimization/muDIS_mergeFiles.py +++ b/muonShieldOptimization/muDIS_mergeFiles.py @@ -1,54 +1,68 @@ -import ROOT,os +import os + +import ROOT import rootUtils as ut -h={} + +h = {} + + def merge(): - sTree = ROOT.TChain('DIS') - for i in range(0,12): - fn = "muonDis_"+str(i)+".root" - sTree.AddFile(fn) - fm = ROOT.TFile("test.root","recreate") - nTree = ROOT.TTree('DIS','muon DIS') - iMuon = ROOT.TClonesArray("TVectorD") - iMuonBranch = nTree.Branch("InMuon",iMuon,32000,-1) - dPart = ROOT.TClonesArray("TVectorD") - dPartBranch = nTree.Branch("Particles",dPart,32000,-1) - for n in range(sTree.GetEntries()): - sTree.GetEvent(n) - dPart.Clear() - iMuon.Clear() - tca_vec = iMuon.ConstructedAt(0) - tca_vec.ResizeTo(sTree.InMuon[0]) - ROOT.std.swap(tca_vec, sTree.InMuon[0]) - for part in sTree.Particles: - nPart = dPart.GetEntries() - if dPart.GetSize() == nPart: dPart.Expand(nPart+10) - tca_vec = dPart.ConstructedAt(nPart) - tca_vec.ResizeTo(part) - ROOT.std.swap(tca_vec, part) - dPartBranch.Fill() - iMuonBranch.Fill() - nTree.Fill() - fm.cd() - nTree.Write() - fm.Close() + sTree = ROOT.TChain("DIS") + for i in range(0, 12): + fn = "muonDis_" + str(i) + ".root" + sTree.AddFile(fn) + fm = ROOT.TFile("test.root", "recreate") + nTree = ROOT.TTree("DIS", "muon DIS") + iMuon = ROOT.TClonesArray("TVectorD") + iMuonBranch = nTree.Branch("InMuon", iMuon, 32000, -1) + dPart = ROOT.TClonesArray("TVectorD") + dPartBranch = nTree.Branch("Particles", dPart, 32000, -1) + for n in range(sTree.GetEntries()): + sTree.GetEvent(n) + dPart.Clear() + iMuon.Clear() + tca_vec = iMuon.ConstructedAt(0) + tca_vec.ResizeTo(sTree.InMuon[0]) + ROOT.std.swap(tca_vec, sTree.InMuon[0]) + for part in sTree.Particles: + nPart = dPart.GetEntries() + if dPart.GetSize() == nPart: + dPart.Expand(nPart + 10) + tca_vec = dPart.ConstructedAt(nPart) + tca_vec.ResizeTo(part) + ROOT.std.swap(tca_vec, part) + dPartBranch.Fill() + iMuonBranch.Fill() + nTree.Fill() + fm.cd() + nTree.Write() + fm.Close() + + def hadd(): - cmd = 'hadd -f muonDIS.root ' - for i in range(0,12): - cmd+= " muonDis_"+str(i)+".root " - os.system(cmd) + cmd = "hadd -f muonDIS.root " + for i in range(0, 12): + cmd += " muonDis_" + str(i) + ".root " + os.system(cmd) + + def makePlots(sTree): - ut.bookHist(h,'muP','muon mom',100,0.,400.) - ut.bookHist(h,'nOut','outgoing part',100,-0.5,99.5) - ut.bookHist(h,'pos','position',100,-25.,100.,100,-12.,12.,100,-13.,13.) - for n in range(sTree.GetEntries()): - rc = sTree.GetEvent(n) - inMu = sTree.InMuon[0] - w = inMu[8] - P = ROOT.TMath.Sqrt(inMu[1]**2+inMu[2]**2+inMu[3]**2) - rc = h['muP'].Fill(P,w) - rc = h['nOut'].Fill(sTree.Particles.GetEntries() ) - rc = h['pos'].Fill(inMu[7],inMu[5],inMu[6] ) -def test(fn = "test.root"): - fm = ROOT.TFile(fn) - sTree = fm.DIS - makePlots(sTree) + ut.bookHist(h, "muP", "muon mom", 100, 0.0, 400.0) + ut.bookHist(h, "nOut", "outgoing part", 100, -0.5, 99.5) + ut.bookHist( + h, "pos", "position", 100, -25.0, 100.0, 100, -12.0, 12.0, 100, -13.0, 13.0 + ) + for n in range(sTree.GetEntries()): + rc = sTree.GetEvent(n) + inMu = sTree.InMuon[0] + w = inMu[8] + P = ROOT.TMath.Sqrt(inMu[1] ** 2 + inMu[2] ** 2 + inMu[3] ** 2) + rc = h["muP"].Fill(P, w) + rc = h["nOut"].Fill(sTree.Particles.GetEntries()) + rc = h["pos"].Fill(inMu[7], inMu[5], inMu[6]) + + +def test(fn="test.root"): + fm = ROOT.TFile(fn) + sTree = fm.DIS + makePlots(sTree) diff --git a/muonShieldOptimization/pyFairModule.cxx b/muonShieldOptimization/pyFairModule.cxx index 4bef96400c..472c25b24b 100644 --- a/muonShieldOptimization/pyFairModule.cxx +++ b/muonShieldOptimization/pyFairModule.cxx @@ -1,16 +1,22 @@ -#include "Python.h" // Needs to be included first to avoid redefinition of _POSIX_C_SOURCE #include "pyFairModule.h" + +#include "Python.h" // Needs to be included first to avoid redefinition of _POSIX_C_SOURCE #include "TObject.h" void call_python_method(PyObject* self, const char* method) { - // check arguments - if ( 0 == self || 0 == method ) { throw std::runtime_error("Invalid Python object and method"); } - // call Python - PyObject* r = PyObject_CallMethod(self, const_cast(method), const_cast("")); - if ( 0 == r ) { PyErr_Print(); return;} - // release used objects - Py_XDECREF( r ) ; - // - return; + // check arguments + if (0 == self || 0 == method) { + throw std::runtime_error("Invalid Python object and method"); + } + // call Python + PyObject* r = PyObject_CallMethod(self, const_cast(method), const_cast("")); + if (0 == r) { + PyErr_Print(); + return; + } + // release used objects + Py_XDECREF(r); + // + return; } diff --git a/muonShieldOptimization/pyFairModule.h b/muonShieldOptimization/pyFairModule.h index d3ac3237a2..2be522c97d 100644 --- a/muonShieldOptimization/pyFairModule.h +++ b/muonShieldOptimization/pyFairModule.h @@ -5,13 +5,16 @@ typedef _object PyObject; #include void call_python_method(PyObject* self, const char* method); +class pyFairModule : public FairModule +{ + public: + pyFairModule(PyObject* self) + : fSelf(self) + {} + virtual ~pyFairModule() {} + virtual void ConstructGeometry() { call_python_method(fSelf, "ConstructGeometry"); } -class pyFairModule : public FairModule { -public: - pyFairModule(PyObject* self) : fSelf(self) {} - virtual ~pyFairModule() {} - virtual void ConstructGeometry() { call_python_method(fSelf,"ConstructGeometry"); } -private: - PyObject* fSelf; -ClassDef(pyFairModule, 0) + private: + PyObject* fSelf; + ClassDef(pyFairModule, 0) }; diff --git a/muonShieldOptimization/radio.py b/muonShieldOptimization/radio.py index 9547ee3ed5..49eb0df0c0 100644 --- a/muonShieldOptimization/radio.py +++ b/muonShieldOptimization/radio.py @@ -1,38 +1,39 @@ import ROOT + path = "./" -fs = ['ship.10.0.nuRadiography-TGeant4.root'] +fs = ["ship.10.0.nuRadiography-TGeant4.root"] ROOT.gROOT.cd() -myHist = ROOT.TH3F('myh','radio',500,-10000,10000,100,-300,300,100,-600,600) -myHist2 = ROOT.TH3F('myh2','radio',500,-3000,3000,100,-300,300,100,-600,600) +myHist = ROOT.TH3F("myh", "radio", 500, -10000, 10000, 100, -300, 300, 100, -600, 600) +myHist2 = ROOT.TH3F("myh2", "radio", 500, -3000, 3000, 100, -300, 300, 100, -600, 600) for x in fs: - fl = ROOT.TFile(path+x) - sTree=fl.cbmsim - ROOT.gROOT.cd() - for n in range(sTree.GetEntries()): - rc=sTree.GetEvent(n) - nu = sTree.MCTrack[0] - myHist.Fill(nu.GetStartZ(),nu.GetStartX(),nu.GetStartY(),nu.GetWeight()) - myHist2.Fill(nu.GetStartZ(),nu.GetStartX(),nu.GetStartY(),nu.GetWeight()) - fl.Close() + fl = ROOT.TFile(path + x) + sTree = fl.cbmsim + ROOT.gROOT.cd() + for n in range(sTree.GetEntries()): + rc = sTree.GetEvent(n) + nu = sTree.MCTrack[0] + myHist.Fill(nu.GetStartZ(), nu.GetStartX(), nu.GetStartY(), nu.GetWeight()) + myHist2.Fill(nu.GetStartZ(), nu.GetStartX(), nu.GetStartY(), nu.GetWeight()) + fl.Close() myHist.SetStats(0) -myHist.SetXTitle('Z [m]') -myHist.SetZTitle('Y [m]') -myHist.SetYTitle('X [m]') +myHist.SetXTitle("Z [m]") +myHist.SetZTitle("Y [m]") +myHist.SetYTitle("X [m]") -c1 = ROOT.gROOT.FindObject('c1') -myHist.Draw('box') -c1.Print('radio.png') -myHistxy = myHist.Project3D('xy') -myHistxz = myHist.Project3D('xz') -myHistyz = myHist.Project3D('yz') +c1 = ROOT.gROOT.FindObject("c1") +myHist.Draw("box") +c1.Print("radio.png") +myHistxy = myHist.Project3D("xy") +myHistxz = myHist.Project3D("xz") +myHistyz = myHist.Project3D("yz") myHistxy.SetStats(0) myHistxz.SetStats(0) myHistyz.SetStats(0) -myHistxy.SetTitle('radio xz projection') -myHistxy.Draw('colz') -c1.Print('radioxz.png') -myHistxz.SetTitle('radio yz projection') -myHistxz.Draw('colz') -c1.Print('radioyz.png') +myHistxy.SetTitle("radio xz projection") +myHistxy.Draw("colz") +c1.Print("radioxz.png") +myHistxz.SetTitle("radio yz projection") +myHistxz.Draw("colz") +c1.Print("radioyz.png") diff --git a/muonShieldOptimization/runCharmHadProd.py b/muonShieldOptimization/runCharmHadProd.py index 2847599872..5f2f744d3f 100644 --- a/muonShieldOptimization/runCharmHadProd.py +++ b/muonShieldOptimization/runCharmHadProd.py @@ -1,14 +1,18 @@ -import sys,os,ROOT +import os +import sys + +import ROOT + ncpus = 20 msel = "4" # msel = "5" if msel == "4": - nev = 2000000 # 0.1s / event - path = "/afs/cern.ch/project/lbcern/vol1/truf/charm/" + nev = 2000000 # 0.1s / event + path = "/afs/cern.ch/project/lbcern/vol1/truf/charm/" else: - nev = 1000000 - path = "/afs/cern.ch/project/lbcern/vol1/truf/beauty/" + nev = 1000000 + path = "/afs/cern.ch/project/lbcern/vol1/truf/beauty/" # path = "/home/truf/charm/" @@ -20,138 +24,273 @@ # pot = nrcpot / chicc # nrcpot=((TH1F*)fin->Get("2"))->GetBinContent(1)/2.; // pot are counted double, i.e. for each signal, i.e. pot/2. + def makeHadrons(run): - for n in range(ncpus): - s = x.Rndm()*1000000000. - os.system('mkdir run'+str(run)) - os.chdir('run'+str(run)) - cmd = "python $FAIRSHIP/macro/makeCascade.py -m "+msel+" -n " + str(nev) + " -t Cascade-run"+str(run)+"-parp16-MSTP82-1-MSEL"+msel+".root" - # if not run in runList: - os.system(cmd+ " >log"+str(run)+" &") - os.chdir('../') - run+=1 - -def makeBackground(run,cycle=0): - for n in range(ncpus): - orun = run+cycle*1000 - os.chdir('run'+str(run)) - inputFile = path+"run"+str(run)+"/Cascade-run"+str(run)+"-parp16-MSTP82-1-MSEL"+msel+".root" - f=ROOT.TFile(inputFile) - nt = f.pythia6 - N = nt.GetEntries() - f.Close() - if msel == "4": - cmd = "python $FAIRSHIP/muonShieldOptimization/run_fixedTarget.py --force --charm -V -e 10 -P -n "+str(N)+" -r "+str(orun)+" -b 100 -X 100 -I "+inputFile - else: - cmd = "python $FAIRSHIP/muonShieldOptimization/run_fixedTarget.py --force --beauty -V -e 10 -P -n "+str(N)+" -r "+str(orun)+" -b 100 -X 100 -I "+inputFile - os.system(cmd+ " >logFT"+str(orun)+" &") - os.chdir('../') - run+=1 + for n in range(ncpus): + s = x.Rndm() * 1000000000.0 + os.system("mkdir run" + str(run)) + os.chdir("run" + str(run)) + cmd = ( + "python $FAIRSHIP/macro/makeCascade.py -m " + + msel + + " -n " + + str(nev) + + " -t Cascade-run" + + str(run) + + "-parp16-MSTP82-1-MSEL" + + msel + + ".root" + ) + # if not run in runList: + os.system(cmd + " >log" + str(run) + " &") + os.chdir("../") + run += 1 + + +def makeBackground(run, cycle=0): + for n in range(ncpus): + orun = run + cycle * 1000 + os.chdir("run" + str(run)) + inputFile = ( + path + + "run" + + str(run) + + "/Cascade-run" + + str(run) + + "-parp16-MSTP82-1-MSEL" + + msel + + ".root" + ) + f = ROOT.TFile(inputFile) + nt = f.pythia6 + N = nt.GetEntries() + f.Close() + if msel == "4": + cmd = ( + "python $FAIRSHIP/muonShieldOptimization/run_fixedTarget.py --force --charm -V -e 10 -P -n " + + str(N) + + " -r " + + str(orun) + + " -b 100 -X 100 -I " + + inputFile + ) + else: + cmd = ( + "python $FAIRSHIP/muonShieldOptimization/run_fixedTarget.py --force --beauty -V -e 10 -P -n " + + str(N) + + " -r " + + str(orun) + + " -b 100 -X 100 -I " + + inputFile + ) + os.system(cmd + " >logFT" + str(orun) + " &") + os.chdir("../") + run += 1 + cycle = 2 -runList = [20,28,30,33] -def makeBackgroundX(runList,cycle=0): - for run in runList: - orun = run+cycle*1000 - os.chdir('run'+str(run)) - inputFile = path+"run"+str(run)+"/Cascade-run"+str(run)+"-parp16-MSTP82-1-MSEL"+msel+".root" - f=ROOT.TFile(inputFile) - nt = f.pythia6 - N = nt.GetEntries() - f.Close() - cmd = "python $FAIRSHIP/muonShieldOptimization/run_fixedTarget.py --force --charm -V -e 10 -P -n "+str(N)+" -r "+str(orun)+" -b 100 -X 100 -I "+inputFile - if run in runList: os.system(cmd+ " >logFT"+str(orun)+" &") - os.chdir('../') - -def merge(run,cycle=0): - fname = "pythia8_Geant4_XX_10.0.root" - cmd = " " - for n in range(ncpus): - for x in os.listdir(path+'/run'+str(run+n)): - orun = run+cycle*1000 - if not x.find('run_fixedTarget_'+str(orun+n)) < 0: - if cycle == 0 and run == 0 and not x.find('1001') < 0: continue - if cycle == 0 and run == 0 and not x.find('1010') < 0: continue - cmd += path+'/run'+str(run+n)+'/'+x+'/'+fname.replace('XX',str(orun+n))+' ' - if msel == "4": outFile = fname.replace('XX', 'charm_'+str(orun)+'-'+str(orun+ncpus-1) ) - else: outFile = fname.replace('XX', 'beauty_'+str(orun)+'-'+str(orun+ncpus-1) ) - rc = os.system("hadd -O "+outFile + " " +cmd) - if rc != 0: - print("hadd failed, stop",outFile) - else: - rc = os.system("xrdcp "+outFile+" $EOSSHIP/eos/experiment/ship/data/Mbias/background-prod-2018/"+outFile) - if rc != 0: - print("copy to EOS failed, stop",outFile) - else: - rc = os.system("rm "+outFile) +runList = [20, 28, 30, 33] + + +def makeBackgroundX(runList, cycle=0): + for run in runList: + orun = run + cycle * 1000 + os.chdir("run" + str(run)) + inputFile = ( + path + + "run" + + str(run) + + "/Cascade-run" + + str(run) + + "-parp16-MSTP82-1-MSEL" + + msel + + ".root" + ) + f = ROOT.TFile(inputFile) + nt = f.pythia6 + N = nt.GetEntries() + f.Close() + cmd = ( + "python $FAIRSHIP/muonShieldOptimization/run_fixedTarget.py --force --charm -V -e 10 -P -n " + + str(N) + + " -r " + + str(orun) + + " -b 100 -X 100 -I " + + inputFile + ) + if run in runList: + os.system(cmd + " >logFT" + str(orun) + " &") + os.chdir("../") + + +def merge(run, cycle=0): + fname = "pythia8_Geant4_XX_10.0.root" + cmd = " " + for n in range(ncpus): + for x in os.listdir(path + "/run" + str(run + n)): + orun = run + cycle * 1000 + if not x.find("run_fixedTarget_" + str(orun + n)) < 0: + if cycle == 0 and run == 0 and not x.find("1001") < 0: + continue + if cycle == 0 and run == 0 and not x.find("1010") < 0: + continue + cmd += ( + path + + "/run" + + str(run + n) + + "/" + + x + + "/" + + fname.replace("XX", str(orun + n)) + + " " + ) + if msel == "4": + outFile = fname.replace( + "XX", "charm_" + str(orun) + "-" + str(orun + ncpus - 1) + ) + else: + outFile = fname.replace( + "XX", "beauty_" + str(orun) + "-" + str(orun + ncpus - 1) + ) + rc = os.system("hadd -O " + outFile + " " + cmd) + if rc != 0: + print("hadd failed, stop", outFile) + else: + rc = os.system( + "xrdcp " + + outFile + + " $EOSSHIP/eos/experiment/ship/data/Mbias/background-prod-2018/" + + outFile + ) + if rc != 0: + print("copy to EOS failed, stop", outFile) + else: + rc = os.system("rm " + outFile) + def mergeAll(): - cmd = "hadd pythia8_Geant4_charm_153.3B_10.0_mu.root " - tmp = "/eos/experiment/ship/data/Mbias/background-prod-2018/pythia8_Geant4_charm_XX_10.0_mu.root" - for x in ["0-19","20-39","40-59","60-79","80-99",\ - "1000-1019","1020-1039","1040-1059","1060-1079","1080-1099",\ - "2000-2019","2020-2039","2040-2059","2060-2079","2080-2099"]: - cmd+=tmp.replace('XX',x)+" " - os.system(cmd) + cmd = "hadd pythia8_Geant4_charm_153.3B_10.0_mu.root " + tmp = "/eos/experiment/ship/data/Mbias/background-prod-2018/pythia8_Geant4_charm_XX_10.0_mu.root" + for x in [ + "0-19", + "20-39", + "40-59", + "60-79", + "80-99", + "1000-1019", + "1020-1039", + "1040-1059", + "1060-1079", + "1080-1099", + "2000-2019", + "2020-2039", + "2040-2059", + "2060-2079", + "2080-2099", + ]: + cmd += tmp.replace("XX", x) + " " + os.system(cmd) + def compactifyCascade(run): - ncpus = 20 - cmd = '' - Ntot = 0 - NperJob = nev - for i in range(run,+ncpus): - fName = path+"run"+str(i)+"/Cascade-run"+str(i)+"-parp16-MSTP82-1-MSEL"+msel+".root" - f=open(path+"run"+str(i)+"/log"+str(i)) - success = False - for l in f.readlines(): - if not l.find('Macro finished succesfully')<0: success = True - if not success: - print("job not finished properly",fName) - continue - cmd += fName +" " - f.close() - Ntot+= NperJob - if cmd.find('root')<0: - print('no file found, exit') - else: - stat = str( int(Ntot/1E6))+'Mpot' - outFile = "Cascade-run"+str(run)+"-"+str(run+ncpus-1)+"-parp16-MSTP82-1-MSEL"+msel+"-"+stat+".root" - rc = os.system("hadd -O "+outFile + " " +cmd) - f = ROOT.TFile(outFile) - Npot = f.Get("2").GetBinContent(1)/2./chicc - f.Close() - stat = str( int(Npot/1E9))+'Bpot' - oldOutFile = outFile - outFile = "Cascade-run"+str(run)+"-"+str(run+ncpus-1)+"-parp16-MSTP82-1-MSEL"+msel+"-"+stat+".root" - os.system("mv "+oldOutFile+" "+outFile) - rc = os.system("xrdcp "+outFile+" $EOSSHIP/eos/experiment/ship/data/Mbias/background-prod-2018/"+outFile) - if rc != 0: - print("copy to EOS failed, stop",outFile) - else: - rc = os.system("rm "+outFile) + ncpus = 20 + cmd = "" + Ntot = 0 + NperJob = nev + for i in range(run, +ncpus): + fName = ( + path + + "run" + + str(i) + + "/Cascade-run" + + str(i) + + "-parp16-MSTP82-1-MSEL" + + msel + + ".root" + ) + f = open(path + "run" + str(i) + "/log" + str(i)) + success = False + for l in f.readlines(): + if not l.find("Macro finished succesfully") < 0: + success = True + if not success: + print("job not finished properly", fName) + continue + cmd += fName + " " + f.close() + Ntot += NperJob + if cmd.find("root") < 0: + print("no file found, exit") + else: + stat = str(int(Ntot / 1e6)) + "Mpot" + outFile = ( + "Cascade-run" + + str(run) + + "-" + + str(run + ncpus - 1) + + "-parp16-MSTP82-1-MSEL" + + msel + + "-" + + stat + + ".root" + ) + rc = os.system("hadd -O " + outFile + " " + cmd) + f = ROOT.TFile(outFile) + Npot = f.Get("2").GetBinContent(1) / 2.0 / chicc + f.Close() + stat = str(int(Npot / 1e9)) + "Bpot" + oldOutFile = outFile + outFile = ( + "Cascade-run" + + str(run) + + "-" + + str(run + ncpus - 1) + + "-parp16-MSTP82-1-MSEL" + + msel + + "-" + + stat + + ".root" + ) + os.system("mv " + oldOutFile + " " + outFile) + rc = os.system( + "xrdcp " + + outFile + + " $EOSSHIP/eos/experiment/ship/data/Mbias/background-prod-2018/" + + outFile + ) + if rc != 0: + print("copy to EOS failed, stop", outFile) + else: + rc = os.system("rm " + outFile) + def statistics(): - chicc=1.7e-3 - if msel=='5': chicc = 1.6e-7 - path = os.environ['EOSSHIP']+"/eos/experiment/ship/data/Mbias/background-prod-2018/" - fname = "Cascade-runAA-BB-parp16-MSTP82-1-MSEL4-40Mpot.root" - nPot = 0 - nhadrons = 0 - for x in [0,20,40,60,80]: - fn = fname.replace('AA',str(x)).replace('BB',str(x+19)) - f=ROOT.TFile.Open(path+fn) - nPot += f.Get("2").GetBinContent(1)/2. - nhadrons += f.Get('pythia6').GetEntries() - print("total nr of hadrons:",nhadrons,nPot/chicc/1.E9,'Billion') + chicc = 1.7e-3 + if msel == "5": + chicc = 1.6e-7 + path = ( + os.environ["EOSSHIP"] + "/eos/experiment/ship/data/Mbias/background-prod-2018/" + ) + fname = "Cascade-runAA-BB-parp16-MSTP82-1-MSEL4-40Mpot.root" + nPot = 0 + nhadrons = 0 + for x in [0, 20, 40, 60, 80]: + fn = fname.replace("AA", str(x)).replace("BB", str(x + 19)) + f = ROOT.TFile.Open(path + fn) + nPot += f.Get("2").GetBinContent(1) / 2.0 + nhadrons += f.Get("pythia6").GetEntries() + print("total nr of hadrons:", nhadrons, nPot / chicc / 1.0e9, "Billion") + def potFromFileHeader(): - pot = 0 - for x in f.GetListOfKeys(): - if x.GetName()=='FileHeader': - pot += float(x.GetTitle().split(' ')[3]) - print("PoT = ",pot) + pot = 0 + for x in f.GetListOfKeys(): + if x.GetName() == "FileHeader": + pot += float(x.GetTitle().split(" ")[3]) + print("PoT = ", pot) + -x=ROOT.TRandom3() +x = ROOT.TRandom3() x.SetSeed(0) run = int(sys.argv[1]) diff --git a/muonShieldOptimization/run_fixedTarget.py b/muonShieldOptimization/run_fixedTarget.py index 53bc7ddd87..f607fa3d98 100644 --- a/muonShieldOptimization/run_fixedTarget.py +++ b/muonShieldOptimization/run_fixedTarget.py @@ -1,37 +1,45 @@ #!/usr/bin/env python -import ROOT,os,sys,time,shipRoot_conf +import os +import sys +import time + +import ROOT +import shipRoot_conf import shipunit as u from ShipGeoConfig import ConfigRegistry -mcEngine = "TGeant4" -simEngine = "Pythia8" -runnr = 1 -nev = 1000 +mcEngine = "TGeant4" +simEngine = "Pythia8" +runnr = 1 +nev = 1000 checkOverlap = True -G4only = False +G4only = False storeOnlyMuons = False -skipNeutrinos = False -withEvtGen = True -boostDiMuon = 1. -boostFactor = 1. -charm = False -beauty = False +skipNeutrinos = False +withEvtGen = True +boostDiMuon = 1.0 +boostFactor = 1.0 +charm = False +beauty = False chicc = 1.7e-3 chibb = 1.6e-7 -npot = 5E13 +npot = 5e13 nStart = 0 -charmInputFile = ROOT.gSystem.Getenv("EOSSHIP")+"/eos/experiment/ship/data/Charm/Cascade-parp16-MSTP82-1-MSEL4-76Mpot_1.root" +charmInputFile = ( + ROOT.gSystem.Getenv("EOSSHIP") + + "/eos/experiment/ship/data/Charm/Cascade-parp16-MSTP82-1-MSEL4-76Mpot_1.root" +) nStart = 0 -outputDir = "." -work_dir = "./" -ecut = 0.5 # GeV with 1 : ~1sec / event, with 2: 0.4sec / event, 10: 0.13sec +outputDir = "." +work_dir = "./" +ecut = 0.5 # GeV with 1 : ~1sec / event, with 2: 0.4sec / event, 10: 0.13sec -dy = 10. -dv = 6 # 4=TP elliptical tank design, 5 = optimized conical rectangular design, 6=5 without segment-1 -ds = 9 # 5=TP muon shield, 6=magnetized hadron, 7=short magnet design, 9=optimised with T4 as constraint, 8=requires config file -nud = 3 # 0=TP, 1=new magnet option for short muon shield, 2= no magnet surrounding neutrino detector +dy = 10.0 +dv = 6 # 4=TP elliptical tank design, 5 = optimized conical rectangular design, 6=5 without segment-1 +ds = 9 # 5=TP muon shield, 6=magnetized hadron, 7=short magnet design, 9=optimised with T4 as constraint, 8=requires config file +nud = 3 # 0=TP, 1=new magnet option for short muon shield, 2= no magnet surrounding neutrino detector # example for primary interaction, nobias: python $FAIRSHIP/muonShieldOptimization/run_fixedTarget.py -n 10000 -e 10 -f -r 10 # 10000 events, energy cut 10GeV, run nr 10, override existing output folder @@ -39,124 +47,299 @@ # 10000 events, charm decays, energy cut 10GeV, run nr 60, override existing output folder # increase di-muon BRs for resonances < 1.1GeV by a factor 50 -#----------------------------- Yandex production ------------------------------ -import shutil import argparse import logging +# ----------------------------- Yandex production ------------------------------ +import shutil + logging.info("") logger = logging.getLogger(os.path.splitext(os.path.basename(os.sys.argv[0]))[0]) logger.setLevel(logging.INFO) -def get_work_dir(run_number,tag=None): - import socket - host = socket.gethostname() - job_base_name = os.path.splitext(os.path.basename(os.sys.argv[0]))[0] - if tag: out_dir = "{host}_{base}_{runnr}_{comment}".format(host=host, base=job_base_name, runnr=run_number, comment=tag) - else: out_dir = "{host}_{base}_{runnr}".format(host=host, base=job_base_name, runnr=run_number) - return out_dir +def get_work_dir(run_number, tag=None): + import socket + + host = socket.gethostname() + job_base_name = os.path.splitext(os.path.basename(os.sys.argv[0]))[0] + if tag: + out_dir = "{host}_{base}_{runnr}_{comment}".format( + host=host, base=job_base_name, runnr=run_number, comment=tag + ) + else: + out_dir = "{host}_{base}_{runnr}".format( + host=host, base=job_base_name, runnr=run_number + ) + return out_dir def init(): - global runnr, nev, ecut, G4only, tauOnly,JpsiMainly, work_dir,Debug,withEvtGen,boostDiMuon,\ - boostFactor,charm,beauty,charmInputFile,nStart,storeOnlyMuons,chicc,chibb,npot,nStart,skipNeutrinos,FourDP - logger.info("SHiP proton-on-taget simulator (C) Thomas Ruf, 2017") - - ap = argparse.ArgumentParser( - description='Run SHiP "pot" simulation') - ap.add_argument('-d', '--debug', action='store_true', dest='debug') - ap.add_argument('-f', '--force', action='store_true', help="force overwriting output directory") - ap.add_argument('-r', '--run-number', type=int, dest='runnr', default=runnr) - ap.add_argument('-e', '--ecut', type=float, help="energy cut", dest='ecut', default=ecut) - ap.add_argument('-n', '--num-events', type=int, help="number of events to generate", dest='nev', default=nev) - ap.add_argument('-G', '--G4only', action='store_true', dest='G4only', default=False, help="use Geant4 directly, no Pythia8") - ap.add_argument('-P', '--PythiaDecay', action='store_true', dest='pythiaDecay', default=False, help="use Pythia8 for decays") - ap.add_argument('-V', '--EvtGen', action='store_true', dest='withEvtGen', default=withEvtGen, help="use EvtGen for decays") - ap.add_argument('-t', '--tau-only', action='store_true', dest='tauOnly', default=False) - ap.add_argument('-J', '--Jpsi-mainly', action='store_true', dest='JpsiMainly', default=False) - ap.add_argument('-b', '--boostDiMuon', type=float, dest='boostDiMuon', default=boostDiMuon, help="boost Di-muon branching ratios") - ap.add_argument('-X', '--boostFactor', type=float, dest='boostFactor', default=boostFactor, help="boost Di-muon prod cross sections") - ap.add_argument('-C', '--charm', action='store_true', dest='charm', default=charm, help="generate charm decays") - ap.add_argument('-B', '--beauty', action='store_true', dest='beauty', default=beauty, help="generate beauty decays") - ap.add_argument('-M', '--storeOnlyMuons', action='store_true', dest='storeOnlyMuons', default=storeOnlyMuons, help="store only muons, ignore neutrinos") - ap.add_argument('-N', '--skipNeutrinos', action='store_true', dest='skipNeutrinos', default=False, help="skip neutrinos") - ap.add_argument('-D', '--4darkPhoton', action='store_true', dest='FourDP', default=False, help="enable ntuple production") -# for charm production - ap.add_argument('-cc','--chicc',action='store_true', dest='chicc', default=chicc, help="ccbar over mbias cross section") - ap.add_argument('-bb','--chibb',action='store_true', dest='chibb', default=chibb, help="bbbar over mbias cross section") - ap.add_argument('-p','--pot',action='store_true', dest='npot', default=npot, help="number of protons on target per spill to normalize on") - ap.add_argument('-S', '--nStart', type=int, help="first event of input file to start", dest='nStart', default=nStart) - ap.add_argument('-I', '--InputFile', type=str, dest='charmInputFile', default=charmInputFile, help="input file for charm/beauty decays") - ap.add_argument('-o','--output' , type=str, help="output directory", dest='work_dir', default=None) - ap.add_argument('-rs','--seed', type=int, help="random seed; default value is 0, see TRrandom::SetSeed documentation", dest='seed', default=0) - args = ap.parse_args() - if args.debug: - logger.setLevel(logging.DEBUG) - runnr = args.runnr - nev = args.nev - ecut = args.ecut - tauOnly = args.tauOnly - JpsiMainly = args.JpsiMainly - G4only = args.G4only - boostFactor = args.boostFactor - boostDiMuon = args.boostDiMuon - storeOnlyMuons = args.storeOnlyMuons - skipNeutrinos = args.skipNeutrinos - FourDP = args.FourDP - if G4only: - args.charm = False - args.beauty = False - args.withEvtGen = False - args.pythiaDecay = False - elif args.pythiaDecay: - withEvtGen = False - args.withEvtGen = False - logger.info("use Pythia8 as primary decayer") - else: - withEvtGen = True - logger.info("use EvtGen as primary decayer") - withEvtGen = args.withEvtGen - charm = args.charm - beauty = args.beauty - if charm and beauty: - logger.warn("charm and beauty decays are set! Beauty gets priority") - charm = False - charmInputFile = args.charmInputFile - nStart = int(args.nStart) - Debug = args.debug - if args.work_dir is None: - if charm: args.work_dir = get_work_dir(runnr,"charm") - if beauty: args.work_dir = get_work_dir(runnr,"beauty") - else: args.work_dir = get_work_dir(runnr) - work_dir = args.work_dir - logger.debug("work_dir: %s" % work_dir) - logger.debug("command line arguments: %s", args) - if os.path.exists(work_dir): - logger.warn("output directory '%s' already exists." % work_dir) - if args.force: - logger.warn("...cleaning") - for root, dirs, files in os.walk(work_dir): - for f in files: - os.unlink(os.path.join(root, f)) - for d in dirs: - shutil.rmtree(os.path.join(root, d)) + global \ + runnr, \ + nev, \ + ecut, \ + G4only, \ + tauOnly, \ + JpsiMainly, \ + work_dir, \ + Debug, \ + withEvtGen, \ + boostDiMuon, \ + boostFactor, \ + charm, \ + beauty, \ + charmInputFile, \ + nStart, \ + storeOnlyMuons, \ + chicc, \ + chibb, \ + npot, \ + nStart, \ + skipNeutrinos, \ + FourDP + logger.info("SHiP proton-on-taget simulator (C) Thomas Ruf, 2017") + + ap = argparse.ArgumentParser(description='Run SHiP "pot" simulation') + ap.add_argument("-d", "--debug", action="store_true", dest="debug") + ap.add_argument( + "-f", "--force", action="store_true", help="force overwriting output directory" + ) + ap.add_argument("-r", "--run-number", type=int, dest="runnr", default=runnr) + ap.add_argument( + "-e", "--ecut", type=float, help="energy cut", dest="ecut", default=ecut + ) + ap.add_argument( + "-n", + "--num-events", + type=int, + help="number of events to generate", + dest="nev", + default=nev, + ) + ap.add_argument( + "-G", + "--G4only", + action="store_true", + dest="G4only", + default=False, + help="use Geant4 directly, no Pythia8", + ) + ap.add_argument( + "-P", + "--PythiaDecay", + action="store_true", + dest="pythiaDecay", + default=False, + help="use Pythia8 for decays", + ) + ap.add_argument( + "-V", + "--EvtGen", + action="store_true", + dest="withEvtGen", + default=withEvtGen, + help="use EvtGen for decays", + ) + ap.add_argument( + "-t", "--tau-only", action="store_true", dest="tauOnly", default=False + ) + ap.add_argument( + "-J", "--Jpsi-mainly", action="store_true", dest="JpsiMainly", default=False + ) + ap.add_argument( + "-b", + "--boostDiMuon", + type=float, + dest="boostDiMuon", + default=boostDiMuon, + help="boost Di-muon branching ratios", + ) + ap.add_argument( + "-X", + "--boostFactor", + type=float, + dest="boostFactor", + default=boostFactor, + help="boost Di-muon prod cross sections", + ) + ap.add_argument( + "-C", + "--charm", + action="store_true", + dest="charm", + default=charm, + help="generate charm decays", + ) + ap.add_argument( + "-B", + "--beauty", + action="store_true", + dest="beauty", + default=beauty, + help="generate beauty decays", + ) + ap.add_argument( + "-M", + "--storeOnlyMuons", + action="store_true", + dest="storeOnlyMuons", + default=storeOnlyMuons, + help="store only muons, ignore neutrinos", + ) + ap.add_argument( + "-N", + "--skipNeutrinos", + action="store_true", + dest="skipNeutrinos", + default=False, + help="skip neutrinos", + ) + ap.add_argument( + "-D", + "--4darkPhoton", + action="store_true", + dest="FourDP", + default=False, + help="enable ntuple production", + ) + # for charm production + ap.add_argument( + "-cc", + "--chicc", + action="store_true", + dest="chicc", + default=chicc, + help="ccbar over mbias cross section", + ) + ap.add_argument( + "-bb", + "--chibb", + action="store_true", + dest="chibb", + default=chibb, + help="bbbar over mbias cross section", + ) + ap.add_argument( + "-p", + "--pot", + action="store_true", + dest="npot", + default=npot, + help="number of protons on target per spill to normalize on", + ) + ap.add_argument( + "-S", + "--nStart", + type=int, + help="first event of input file to start", + dest="nStart", + default=nStart, + ) + ap.add_argument( + "-I", + "--InputFile", + type=str, + dest="charmInputFile", + default=charmInputFile, + help="input file for charm/beauty decays", + ) + ap.add_argument( + "-o", + "--output", + type=str, + help="output directory", + dest="work_dir", + default=None, + ) + ap.add_argument( + "-rs", + "--seed", + type=int, + help="random seed; default value is 0, see TRrandom::SetSeed documentation", + dest="seed", + default=0, + ) + args = ap.parse_args() + if args.debug: + logger.setLevel(logging.DEBUG) + runnr = args.runnr + nev = args.nev + ecut = args.ecut + tauOnly = args.tauOnly + JpsiMainly = args.JpsiMainly + G4only = args.G4only + boostFactor = args.boostFactor + boostDiMuon = args.boostDiMuon + storeOnlyMuons = args.storeOnlyMuons + skipNeutrinos = args.skipNeutrinos + FourDP = args.FourDP + if G4only: + args.charm = False + args.beauty = False + args.withEvtGen = False + args.pythiaDecay = False + elif args.pythiaDecay: + withEvtGen = False + args.withEvtGen = False + logger.info("use Pythia8 as primary decayer") else: - logger.warn("...use '-f' option to overwrite it") - else: - os.makedirs(work_dir) - return args + withEvtGen = True + logger.info("use EvtGen as primary decayer") + withEvtGen = args.withEvtGen + charm = args.charm + beauty = args.beauty + if charm and beauty: + logger.warn("charm and beauty decays are set! Beauty gets priority") + charm = False + charmInputFile = args.charmInputFile + nStart = int(args.nStart) + Debug = args.debug + if args.work_dir is None: + if charm: + args.work_dir = get_work_dir(runnr, "charm") + if beauty: + args.work_dir = get_work_dir(runnr, "beauty") + else: + args.work_dir = get_work_dir(runnr) + work_dir = args.work_dir + logger.debug("work_dir: %s" % work_dir) + logger.debug("command line arguments: %s", args) + if os.path.exists(work_dir): + logger.warn("output directory '%s' already exists." % work_dir) + if args.force: + logger.warn("...cleaning") + for root, dirs, files in os.walk(work_dir): + for f in files: + os.unlink(os.path.join(root, f)) + for d in dirs: + shutil.rmtree(os.path.join(root, d)) + else: + logger.warn("...use '-f' option to overwrite it") + else: + os.makedirs(work_dir) + return args + args = init() os.chdir(work_dir) # ------------------------------------------------------------------- -ROOT.gRandom.SetSeed(args.seed) # this should be propagated via ROOT to Pythia8 and Geant4VMC -shipRoot_conf.configure() # load basic libraries, prepare atexit for python -ship_geo = ConfigRegistry.loadpy("$FAIRSHIP/geometry/geometry_config.py", Yheight = dy, tankDesign = dv, muShieldDesign = ds, nuTauTargetDesign=nud) +ROOT.gRandom.SetSeed( + args.seed +) # this should be propagated via ROOT to Pythia8 and Geant4VMC +shipRoot_conf.configure() # load basic libraries, prepare atexit for python +ship_geo = ConfigRegistry.loadpy( + "$FAIRSHIP/geometry/geometry_config.py", + Yheight=dy, + tankDesign=dv, + muShieldDesign=ds, + nuTauTargetDesign=nud, +) -txt = 'pythia8_Geant4_' -if withEvtGen: txt = 'pythia8_evtgen_Geant4_' -outFile = outputDir+'/'+txt+str(runnr)+'_'+str(ecut)+'.root' -parFile = outputDir+'/ship.params.'+txt+str(runnr)+'_'+str(ecut)+'.root' +txt = "pythia8_Geant4_" +if withEvtGen: + txt = "pythia8_evtgen_Geant4_" +outFile = outputDir + "/" + txt + str(runnr) + "_" + str(ecut) + ".root" +parFile = outputDir + "/ship.params." + txt + str(runnr) + "_" + str(ecut) + ".root" # -----Timer-------------------------------------------------------- timer = ROOT.TStopwatch() @@ -166,61 +349,95 @@ def init(): run = ROOT.FairRunSim() run.SetName(mcEngine) # Transport engine run.SetOutputFile(outFile) # Output file -run.SetUserConfig("g4Config.C") # user configuration file default g4Config.C +run.SetUserConfig("g4Config.C") # user configuration file default g4Config.C rtdb = run.GetRuntimeDb() # -----Materials---------------------------------------------- run.SetMaterials("media.geo") # -----Create geometry---------------------------------------------- -cave= ROOT.ShipCave("CAVE") +cave = ROOT.ShipCave("CAVE") cave.SetGeometryFileName("caveWithAir.geo") run.AddModule(cave) -TargetStation = ROOT.ShipTargetStation("TargetStation",ship_geo.target.length,ship_geo.hadronAbsorber.length, - ship_geo.target.z,ship_geo.hadronAbsorber.z,ship_geo.targetOpt,ship_geo.target.sl) -slices_length = ROOT.std.vector('float')() -slices_material = ROOT.std.vector('std::string')() -for i in range(1,ship_geo.targetOpt+1): - slices_length.push_back( eval("ship_geo.target.L"+str(i))) - slices_material.push_back(eval("ship_geo.target.M"+str(i))) -TargetStation.SetLayerPosMat(ship_geo.target.xy,slices_length,slices_material) +TargetStation = ROOT.ShipTargetStation( + "TargetStation", + ship_geo.target.length, + ship_geo.hadronAbsorber.length, + ship_geo.target.z, + ship_geo.hadronAbsorber.z, + ship_geo.targetOpt, + ship_geo.target.sl, +) +slices_length = ROOT.std.vector("float")() +slices_material = ROOT.std.vector("std::string")() +for i in range(1, ship_geo.targetOpt + 1): + slices_length.push_back(eval("ship_geo.target.L" + str(i))) + slices_material.push_back(eval("ship_geo.target.M" + str(i))) +TargetStation.SetLayerPosMat(ship_geo.target.xy, slices_length, slices_material) run.AddModule(TargetStation) -MuonShield = ROOT.ShipMuonShield("MuonShield",ship_geo.muShieldDesign,"ShipMuonShield",ship_geo.muShield.z,ship_geo.muShield.dZ0,ship_geo.muShield.dZ1,\ - ship_geo.muShield.dZ2,ship_geo.muShield.dZ3,ship_geo.muShield.dZ4,ship_geo.muShield.dZ5,ship_geo.muShield.dZ6,\ - ship_geo.muShield.dZ7,ship_geo.muShield.dZ8,ship_geo.muShield.dXgap,ship_geo.muShield.LE,ship_geo.Yheight*4./10.,0.) -MuonShield.SetSupports(False) # otherwise overlap with sensitive Plane -run.AddModule(MuonShield) # needs to be added because of magn hadron shield. +MuonShield = ROOT.ShipMuonShield( + "MuonShield", + ship_geo.muShieldDesign, + "ShipMuonShield", + ship_geo.muShield.z, + ship_geo.muShield.dZ0, + ship_geo.muShield.dZ1, + ship_geo.muShield.dZ2, + ship_geo.muShield.dZ3, + ship_geo.muShield.dZ4, + ship_geo.muShield.dZ5, + ship_geo.muShield.dZ6, + ship_geo.muShield.dZ7, + ship_geo.muShield.dZ8, + ship_geo.muShield.dXgap, + ship_geo.muShield.LE, + ship_geo.Yheight * 4.0 / 10.0, + 0.0, +) +MuonShield.SetSupports(False) # otherwise overlap with sensitive Plane +run.AddModule(MuonShield) # needs to be added because of magn hadron shield. sensPlane = ROOT.exitHadronAbsorber() -sensPlane.SetEnergyCut(ecut*u.GeV) -if storeOnlyMuons: sensPlane.SetOnlyMuons() -if skipNeutrinos: sensPlane.SkipNeutrinos() -if FourDP: sensPlane.SetOpt4DP() # in case a ntuple should be filled with pi0,etas,omega +sensPlane.SetEnergyCut(ecut * u.GeV) +if storeOnlyMuons: + sensPlane.SetOnlyMuons() +if skipNeutrinos: + sensPlane.SkipNeutrinos() +if FourDP: + sensPlane.SetOpt4DP() # in case a ntuple should be filled with pi0,etas,omega # sensPlane.SetZposition(0.*u.cm) # if not using automatic positioning behind default magnetized hadron absorber run.AddModule(sensPlane) # -----Create PrimaryGenerator-------------------------------------- primGen = ROOT.FairPrimaryGenerator() P8gen = ROOT.FixedTargetGenerator() -P8gen.SetTarget("/TargetArea_1",0.,0.) # will distribute PV inside target, beam offset x=y=0. -P8gen.SetMom(400.*u.GeV) -P8gen.SetEnergyCut(ecut*u.GeV) +P8gen.SetTarget( + "/TargetArea_1", 0.0, 0.0 +) # will distribute PV inside target, beam offset x=y=0. +P8gen.SetMom(400.0 * u.GeV) +P8gen.SetEnergyCut(ecut * u.GeV) P8gen.SetDebug(Debug) P8gen.SetHeartBeat(100000) -if G4only: P8gen.SetG4only() -if JpsiMainly: P8gen.SetJpsiMainly() -if tauOnly: P8gen.SetTauOnly() -if withEvtGen: P8gen.WithEvtGen() +if G4only: + P8gen.SetG4only() +if JpsiMainly: + P8gen.SetJpsiMainly() +if tauOnly: + P8gen.SetTauOnly() +if withEvtGen: + P8gen.WithEvtGen() if boostDiMuon > 1: - P8gen.SetBoost(boostDiMuon) # will increase BR for rare eta,omega,rho ... mesons decaying to 2 muons in Pythia8 - # and later copied to Geant4 + P8gen.SetBoost( + boostDiMuon + ) # will increase BR for rare eta,omega,rho ... mesons decaying to 2 muons in Pythia8 + # and later copied to Geant4 P8gen.SetSeed(args.seed) # for charm/beauty # print ' for experts: p pot= number of protons on target per spill to normalize on' # print ' : c chicc= ccbar over mbias cross section' if charm or beauty: - print("--- process heavy flavours ---") - P8gen.InitForCharmOrBeauty(charmInputFile,nev,npot,nStart) + print("--- process heavy flavours ---") + P8gen.InitForCharmOrBeauty(charmInputFile, nev, npot, nStart) primGen.AddGenerator(P8gen) # run.SetGenerator(primGen) @@ -230,21 +447,26 @@ def init(): gMC = ROOT.TVirtualMC.GetMC() fStack = gMC.GetStack() fStack.SetMinPoints(1) -fStack.SetEnergyCut(-1.) +fStack.SetEnergyCut(-1.0) # import AddDiMuonDecayChannelsToG4 + AddDiMuonDecayChannelsToG4.Initialize(P8gen.GetPythia()) # boost gamma2muon conversion if boostFactor > 1: - ROOT.gROOT.ProcessLine('#include "Geant4/G4ProcessTable.hh"') - ROOT.gROOT.ProcessLine('#include "Geant4/G4AnnihiToMuPair.hh"') - ROOT.gROOT.ProcessLine('#include "Geant4/G4GammaConversionToMuons.hh"') - gProcessTable = ROOT.G4ProcessTable.GetProcessTable() - procAnnihil = gProcessTable.FindProcess(ROOT.G4String('AnnihiToMuPair'),ROOT.G4String('e+')) - procGMuPair = gProcessTable.FindProcess(ROOT.G4String('GammaToMuPair'),ROOT.G4String('gamma')) - procGMuPair.SetCrossSecFactor(boostFactor) - procAnnihil.SetCrossSecFactor(boostFactor) + ROOT.gROOT.ProcessLine('#include "Geant4/G4ProcessTable.hh"') + ROOT.gROOT.ProcessLine('#include "Geant4/G4AnnihiToMuPair.hh"') + ROOT.gROOT.ProcessLine('#include "Geant4/G4GammaConversionToMuons.hh"') + gProcessTable = ROOT.G4ProcessTable.GetProcessTable() + procAnnihil = gProcessTable.FindProcess( + ROOT.G4String("AnnihiToMuPair"), ROOT.G4String("e+") + ) + procGMuPair = gProcessTable.FindProcess( + ROOT.G4String("GammaToMuPair"), ROOT.G4String("gamma") + ) + procGMuPair.SetCrossSecFactor(boostFactor) + procAnnihil.SetCrossSecFactor(boostFactor) # -----Start run---------------------------------------------------- run.Run(nev) @@ -253,81 +475,87 @@ def init(): timer.Stop() rtime = timer.RealTime() ctime = timer.CpuTime() -print(' ') +print(" ") print("Macro finished succesfully.") -print("Output file is ", outFile) -print("Real time ",rtime, " s, CPU time ",ctime,"s") +print("Output file is ", outFile) +print("Real time ", rtime, " s, CPU time ", ctime, "s") # ---post processing--- remove empty events --- save histograms -tmpFile = outFile+"tmp" -if ROOT.gROOT.GetListOfFiles().GetEntries()>0: - fin = ROOT.gROOT.GetListOfFiles()[0] +tmpFile = outFile + "tmp" +if ROOT.gROOT.GetListOfFiles().GetEntries() > 0: + fin = ROOT.gROOT.GetListOfFiles()[0] else: - fin = ROOT.TFile.Open(outFile) + fin = ROOT.TFile.Open(outFile) fHeader = fin.FileHeader fHeader.SetRunId(runnr) if charm or beauty: -# normalization for charm - poteq = P8gen.GetPotForCharm() - info = "POT equivalent = %7.3G"%(poteq) + # normalization for charm + poteq = P8gen.GetPotForCharm() + info = "POT equivalent = %7.3G" % (poteq) else: - info = "POT = "+str(nev) + info = "POT = " + str(nev) -conditions = " with ecut="+str(ecut) -if JpsiMainly: conditions+=" J" -if tauOnly: conditions+=" T" -if withEvtGen: conditions+=" V" -if boostDiMuon > 1: conditions+=" diMu"+str(boostDiMuon) -if boostFactor > 1: conditions+=" X"+str(boostFactor) +conditions = " with ecut=" + str(ecut) +if JpsiMainly: + conditions += " J" +if tauOnly: + conditions += " T" +if withEvtGen: + conditions += " V" +if boostDiMuon > 1: + conditions += " diMu" + str(boostDiMuon) +if boostFactor > 1: + conditions += " X" + str(boostFactor) info += conditions fHeader.SetTitle(info) print("Data generated ", fHeader.GetTitle()) -nt = fin.Get('4DP') +nt = fin.Get("4DP") if nt: - tf = ROOT.TFile('FourDP.root','recreate') - tnt = nt.CloneTree(0) - for i in range(nt.GetEntries()): - rc = nt.GetEvent(i) - rc = tnt.Fill(nt.id,nt.px,nt.py,nt.pz,nt.x,nt.y,nt.z) - tnt.Write() - tf.Close() - -t = fin.cbmsim -fout = ROOT.TFile(tmpFile,'recreate' ) + tf = ROOT.TFile("FourDP.root", "recreate") + tnt = nt.CloneTree(0) + for i in range(nt.GetEntries()): + rc = nt.GetEvent(i) + rc = tnt.Fill(nt.id, nt.px, nt.py, nt.pz, nt.x, nt.y, nt.z) + tnt.Write() + tf.Close() + +t = fin.cbmsim +fout = ROOT.TFile(tmpFile, "recreate") sTree = t.CloneTree(0) nEvents = 0 for n in range(t.GetEntries()): - rc = t.GetEvent(n) - if t.vetoPoint.GetEntries()>0: - rc = sTree.Fill() - nEvents+=1 - #t.Clear() + rc = t.GetEvent(n) + if t.vetoPoint.GetEntries() > 0: + rc = sTree.Fill() + nEvents += 1 + # t.Clear() fout.cd() for k in fin.GetListOfKeys(): - x = fin.Get(k.GetName()) - className = x.Class().GetName() - if className.find('TTree')<0 and className.find('TNtuple')<0: - xcopy = x.Clone() - rc = xcopy.Write() + x = fin.Get(k.GetName()) + className = x.Class().GetName() + if className.find("TTree") < 0 and className.find("TNtuple") < 0: + xcopy = x.Clone() + rc = xcopy.Write() sTree.AutoSave() -ff = fin.FileHeader.Clone(fout.GetName()) +ff = fin.FileHeader.Clone(fout.GetName()) fout.cd() ff.Write("FileHeader", ROOT.TObject.kSingleKey) sTree.Write() fout.Close() -rc1 = os.system("rm "+outFile) -rc2 = os.system("mv "+tmpFile+" "+outFile) -print("removed out file, moved tmpFile to out file",rc1,rc2) -fin.SetWritable(False) # bpyass flush error +rc1 = os.system("rm " + outFile) +rc2 = os.system("mv " + tmpFile + " " + outFile) +print("removed out file, moved tmpFile to out file", rc1, rc2) +fin.SetWritable(False) # bpyass flush error -print("Number of events produced with activity after hadron absorber:",nEvents) +print("Number of events produced with activity after hadron absorber:", nEvents) if checkOverlap: - sGeo = ROOT.gGeoManager - sGeo.CheckOverlaps() - sGeo.PrintOverlaps() - run.CreateGeometryFile("%s/geofile_full.root" % (outputDir)) - import saveBasicParameters - saveBasicParameters.execute("%s/geofile_full.root" % (outputDir),ship_geo) + sGeo = ROOT.gGeoManager + sGeo.CheckOverlaps() + sGeo.PrintOverlaps() + run.CreateGeometryFile("%s/geofile_full.root" % (outputDir)) + import saveBasicParameters + + saveBasicParameters.execute("%s/geofile_full.root" % (outputDir), ship_geo) diff --git a/muonShieldOptimization/run_prod.py b/muonShieldOptimization/run_prod.py index 0766029e61..6453ae0355 100755 --- a/muonShieldOptimization/run_prod.py +++ b/muonShieldOptimization/run_prod.py @@ -1,43 +1,68 @@ -import os,time,ROOT -def makeProd(prefix,DY,y=False,phiRandom=False,X=None): - ncpu = 9 - shipsoft = os.environ['SHIPSOFT'].replace('/dev','') - if not y: - f = shipsoft+'/data/pythia8_Geant4_onlyMuons.root' - cmd = "python $FAIRSHIP/macro/run_simScript.py --MuonBack -f " + f + " -Y "+str(float(DY)) # --display" - elif y=='Jpsi': - f = shipsoft+'/data/pythia8_Geant4_Jpsi_onlyMuons.root' - cmd = "python $FAIRSHIP/macro/run_simScript.py --MuonBack -f " + f + " -Y "+str(float(DY)) # --display" - else: - f = shipsoft+'/data/pythia8_Geant4_Yandex_onlyMuons.root' - cmd = "python $FAIRSHIP/macro/run_simScript.py --MuonBack -f " + f + " -Y "+str(float(DY)) # --display" - if phiRandom: cmd = cmd +' --phiRandom' - fn = ROOT.TFile(f) - sTree = fn.FindObjectAny('pythia8-Geant4') - ntot = sTree.GetEntries() - fn.Close() - ns = 0 - n3 = int(ntot/ncpu) - for i in range(1,ncpu+1): - d = prefix+str(i) - if d not in os.listdir('.'): os.system('mkdir '+d) - os.chdir('./'+prefix+'1') - for i in range(1,ncpu+1): - if i==ncpu: n3 = ntot - (i-1)*n3 - if X: - if X==i: - os.system('cp $FAIRSHIP/macro/run_simScript.py .') - os.system(cmd+" -n "+str(n3)+" -i "+str(ns) + " > log &") - else: - os.system('cp $FAIRSHIP/macro/run_simScript.py .') - os.system(cmd+" -n "+str(n3)+" -i "+str(ns) + " > log &") - time.sleep(5) - #print " -n "+str(n3)+" -i "+str(ns) - ns += n3 - if i==ncpu: - os.chdir('../') - break - os.chdir('../'+prefix+str(i+1)) +import os +import time + +import ROOT + + +def makeProd(prefix, DY, y=False, phiRandom=False, X=None): + ncpu = 9 + shipsoft = os.environ["SHIPSOFT"].replace("/dev", "") + if not y: + f = shipsoft + "/data/pythia8_Geant4_onlyMuons.root" + cmd = ( + "python $FAIRSHIP/macro/run_simScript.py --MuonBack -f " + + f + + " -Y " + + str(float(DY)) + ) # --display" + elif y == "Jpsi": + f = shipsoft + "/data/pythia8_Geant4_Jpsi_onlyMuons.root" + cmd = ( + "python $FAIRSHIP/macro/run_simScript.py --MuonBack -f " + + f + + " -Y " + + str(float(DY)) + ) # --display" + else: + f = shipsoft + "/data/pythia8_Geant4_Yandex_onlyMuons.root" + cmd = ( + "python $FAIRSHIP/macro/run_simScript.py --MuonBack -f " + + f + + " -Y " + + str(float(DY)) + ) # --display" + if phiRandom: + cmd = cmd + " --phiRandom" + fn = ROOT.TFile(f) + sTree = fn.FindObjectAny("pythia8-Geant4") + ntot = sTree.GetEntries() + fn.Close() + ns = 0 + n3 = int(ntot / ncpu) + for i in range(1, ncpu + 1): + d = prefix + str(i) + if d not in os.listdir("."): + os.system("mkdir " + d) + os.chdir("./" + prefix + "1") + for i in range(1, ncpu + 1): + if i == ncpu: + n3 = ntot - (i - 1) * n3 + if X: + if X == i: + os.system("cp $FAIRSHIP/macro/run_simScript.py .") + os.system(cmd + " -n " + str(n3) + " -i " + str(ns) + " > log &") + else: + os.system("cp $FAIRSHIP/macro/run_simScript.py .") + os.system(cmd + " -n " + str(n3) + " -i " + str(ns) + " > log &") + time.sleep(5) + # print " -n "+str(n3)+" -i "+str(ns) + ns += n3 + if i == ncpu: + os.chdir("../") + break + os.chdir("../" + prefix + str(i + 1)) + + # # 11-19 with QGSP_BERT_EMV instead of QGSP_BERT_HP_PEN # 51-59 passive shielding @@ -88,10 +113,10 @@ def makeProd(prefix,DY,y=False,phiRandom=False,X=None): # # 630-639 10m height, change RPC width 4.5->3.6m # 640-649 6m height, change RPC width 4.5->3.6m -#makeProd("muon59",6,False) # -#makeProd("muon60",6,True) # -#makeProd("muon61",10,False) # -#makeProd("muon62",10,True) # +# makeProd("muon59",6,False) # +# makeProd("muon60",6,True) # +# makeProd("muon61",10,False) # +# makeProd("muon62",10,True) # # makeProd("muon63",10,False) # # makeProd("muon64",10,True) # @@ -99,139 +124,168 @@ def makeProd(prefix,DY,y=False,phiRandom=False,X=None): # makeProd("muon66",6,True) # # run more statistics, 61, 62 -#makeProd("muon611",10,False,True) -#makeProd("muon621",10,True,True) -#makeProd("muon612",10,False,True) -#makeProd("muon622",10,True,True) -#makeProd("muon613",10,False,True) -#makeProd("muon623",10,True,True) -#makeProd("muon614",10,False,True) -#makeProd("muon624",10,True,True) -#makeProd("muon615",10,False,True) -#makeProd("muon625",10,True,True) -#makeProd("muon616",10,False,True) -#makeProd("muon626",10,True,True) -#makeProd("muon617",10,False,True) -#makeProd("muon627",10,True,True) -#makeProd("muon618",10,False,True) -#makeProd("muon628",10,True,True) -#makeProd("muon619",10,False,True) -#makeProd("muon629",10,True,True) -#makeProd("muon700",10,False,False) # switch off field of active shielding # prefix,DY,y=False,phiRandom=False,X=None -#makeProd("muon710",10,False,False) # start production with beam smeared on r=3cm disk -#makeProd("muon720",10,True,False) -#makeProd("muon711",10,False,True) # start production with beam smeared on r=3cm disk -#makeProd("muon721",10,True,True) -#makeProd("muon712",10,False,True) # start production with beam smeared on r=3cm disk -#makeProd("muon722",10,True,True) -#makeProd("muon713",10,False,True) # start production with beam smeared on r=3cm disk -#makeProd("muon723",10,True,True) -#makeProd("muon714",10,False,True) # start production with beam smeared on r=3cm disk -#makeProd("muon724",10,True,True) -#makeProd("muon715",10,False,True) # start production with beam smeared on r=3cm disk -#makeProd("muon725",10,True,True) -#makeProd("muon716",10,False,True) # start production with beam smeared on r=3cm disk -#makeProd("muon726",10,True,True) -#makeProd("muon717",10,False,True) # start production with beam smeared on r=3cm disk -#makeProd("muon777",10,False,True) # in case the other one does not work 717 -#makeProd("muon727",10,True,True) # ? -#makeProd("muon718",10,False,True) # start production with beam smeared on r=3cm disk -#makeProd("muon728",10,True,True) -#makeProd("muon719",10,False,True) # start production with beam smeared on r=3cm disk -#makeProd("muon729",10,True,True) # -#makeProd("muon730",10,'Jpsi',False) # made with E50 -#makeProd("muon731",10,'Jpsi',True) # made with E50 -#makeProd("muon732",10,'Jpsi',True) # made with E50 -#makeProd("muon733",10,'Jpsi',True) # back to pencil beam -#makeProd("muon630",10,False,True) # test with new muonShield code, 3cm smearing -#makeProd("muon631",10,False,True) # run with concrete wall enabled as sensitive -#makeProd("muon632",10,False,True) # run with concrete wall enabled as sensitive, active shielding polarity fixed - # but wrong geometry -#makeProd("muon810",10,False,False) # start production with latest geometry -#makeProd("muon820",10,True,False) -#makeProd("muon811",10,False,True) # -#makeProd("muon821",10,True,True) +# makeProd("muon611",10,False,True) +# makeProd("muon621",10,True,True) +# makeProd("muon612",10,False,True) +# makeProd("muon622",10,True,True) +# makeProd("muon613",10,False,True) +# makeProd("muon623",10,True,True) +# makeProd("muon614",10,False,True) +# makeProd("muon624",10,True,True) +# makeProd("muon615",10,False,True) +# makeProd("muon625",10,True,True) +# makeProd("muon616",10,False,True) +# makeProd("muon626",10,True,True) +# makeProd("muon617",10,False,True) +# makeProd("muon627",10,True,True) +# makeProd("muon618",10,False,True) +# makeProd("muon628",10,True,True) +# makeProd("muon619",10,False,True) +# makeProd("muon629",10,True,True) +# makeProd("muon700",10,False,False) # switch off field of active shielding # prefix,DY,y=False,phiRandom=False,X=None +# makeProd("muon710",10,False,False) # start production with beam smeared on r=3cm disk +# makeProd("muon720",10,True,False) +# makeProd("muon711",10,False,True) # start production with beam smeared on r=3cm disk +# makeProd("muon721",10,True,True) +# makeProd("muon712",10,False,True) # start production with beam smeared on r=3cm disk +# makeProd("muon722",10,True,True) +# makeProd("muon713",10,False,True) # start production with beam smeared on r=3cm disk +# makeProd("muon723",10,True,True) +# makeProd("muon714",10,False,True) # start production with beam smeared on r=3cm disk +# makeProd("muon724",10,True,True) +# makeProd("muon715",10,False,True) # start production with beam smeared on r=3cm disk +# makeProd("muon725",10,True,True) +# makeProd("muon716",10,False,True) # start production with beam smeared on r=3cm disk +# makeProd("muon726",10,True,True) +# makeProd("muon717",10,False,True) # start production with beam smeared on r=3cm disk +# makeProd("muon777",10,False,True) # in case the other one does not work 717 +# makeProd("muon727",10,True,True) # ? +# makeProd("muon718",10,False,True) # start production with beam smeared on r=3cm disk +# makeProd("muon728",10,True,True) +# makeProd("muon719",10,False,True) # start production with beam smeared on r=3cm disk +# makeProd("muon729",10,True,True) # +# makeProd("muon730",10,'Jpsi',False) # made with E50 +# makeProd("muon731",10,'Jpsi',True) # made with E50 +# makeProd("muon732",10,'Jpsi',True) # made with E50 +# makeProd("muon733",10,'Jpsi',True) # back to pencil beam +# makeProd("muon630",10,False,True) # test with new muonShield code, 3cm smearing +# makeProd("muon631",10,False,True) # run with concrete wall enabled as sensitive +# makeProd("muon632",10,False,True) # run with concrete wall enabled as sensitive, active shielding polarity fixed +# but wrong geometry +# makeProd("muon810",10,False,False) # start production with latest geometry +# makeProd("muon820",10,True,False) +# makeProd("muon811",10,False,True) # +# makeProd("muon821",10,True,True) ##makeProd("muon812",10,False,True) # --< 831 copied back, done 16.3.2015 -#makeProd("muon822",10,True,True) -#makeProd("muon821",10,True,True) -#makeProd("muon822",10,True,True) +# makeProd("muon822",10,True,True) +# makeProd("muon821",10,True,True) +# makeProd("muon822",10,True,True) # -#makeProd("muon813",10,False,True) # -#makeProd("muon823",10,True,True) - -#makeProd("muon814",10,False,True) # -#makeProd("muon824",10,True,True) -#makeProd("muon815",10,False,True) -#makeProd("muon825",10,True,True) -#makeProd("muon816",10,False,True) -#makeProd("muon826",10,True,True) -#makeProd("muon817",10,False,True) -#makeProd("muon827",10,True,True) -#makeProd("muon818",10,False,True) -#makeProd("muon828",10,True,True) -#makeProd("muon819",10,False,True) -#makeProd("muon829",10,True,True) -#makeProd("muon910",10,False,True) -#makeProd("muon920",10,True,True) -#makeProd("muon911",10,False,True) -#makeProd("muon921",10,True,True) - -#makeProd("muon912",10,False,True) -#makeProd("muon922",10,True,True) - -#makeProd("muon913",10,False,True) -#makeProd("muon923",10,True,True) -#makeProd("muon914",10,False,True) -#makeProd("muon924",10,True,True) -#makeProd("muon915",10,False,True) -#makeProd("muon925",10,True,True) -#makeProd("muon916",10,False,True) -#makeProd("muon926",10,True,True) -#makeProd("muon917",10,False,True) -#makeProd("muon927",10,True,True) -#makeProd("muon927",10,True,True,8) -#makeProd("muon918",10,False,True) -#makeProd("muon928",10,True,True) -#makeProd("muon919",10,False,True) -#makeProd("muon929",10,True,True) -#makeProd("muon1019",10,False,True) -#makeProd("muon1029",10,True,True) -#makeProd("muon1018",10,False,True) -#makeProd("muon1028",10,True,True) -#makeProd("muon1017",10,False,True) -#makeProd("muon1027",10,True,True) -#makeProd("muon1016",10,False,True) -#makeProd("muon1026",10,True,True) -#makeProd("muon1015",10,False,True) -#makeProd("muon1025",10,True,True) -#makeProd("muon1014",10,False,True) -#makeProd("muon1024",10,True,True) -#makeProd("muon1013",10,False,True) -#makeProd("muon1023",10,True,True) -#makeProd("muon1012",10,False,True) -#makeProd("muon1022",10,True,True) +# makeProd("muon813",10,False,True) # +# makeProd("muon823",10,True,True) + +# makeProd("muon814",10,False,True) # +# makeProd("muon824",10,True,True) +# makeProd("muon815",10,False,True) +# makeProd("muon825",10,True,True) +# makeProd("muon816",10,False,True) +# makeProd("muon826",10,True,True) +# makeProd("muon817",10,False,True) +# makeProd("muon827",10,True,True) +# makeProd("muon818",10,False,True) +# makeProd("muon828",10,True,True) +# makeProd("muon819",10,False,True) +# makeProd("muon829",10,True,True) +# makeProd("muon910",10,False,True) +# makeProd("muon920",10,True,True) +# makeProd("muon911",10,False,True) +# makeProd("muon921",10,True,True) + +# makeProd("muon912",10,False,True) +# makeProd("muon922",10,True,True) + +# makeProd("muon913",10,False,True) +# makeProd("muon923",10,True,True) +# makeProd("muon914",10,False,True) +# makeProd("muon924",10,True,True) +# makeProd("muon915",10,False,True) +# makeProd("muon925",10,True,True) +# makeProd("muon916",10,False,True) +# makeProd("muon926",10,True,True) +# makeProd("muon917",10,False,True) +# makeProd("muon927",10,True,True) +# makeProd("muon927",10,True,True,8) +# makeProd("muon918",10,False,True) +# makeProd("muon928",10,True,True) +# makeProd("muon919",10,False,True) +# makeProd("muon929",10,True,True) +# makeProd("muon1019",10,False,True) +# makeProd("muon1029",10,True,True) +# makeProd("muon1018",10,False,True) +# makeProd("muon1028",10,True,True) +# makeProd("muon1017",10,False,True) +# makeProd("muon1027",10,True,True) +# makeProd("muon1016",10,False,True) +# makeProd("muon1026",10,True,True) +# makeProd("muon1015",10,False,True) +# makeProd("muon1025",10,True,True) +# makeProd("muon1014",10,False,True) +# makeProd("muon1024",10,True,True) +# makeProd("muon1013",10,False,True) +# makeProd("muon1023",10,True,True) +# makeProd("muon1012",10,False,True) +# makeProd("muon1022",10,True,True) + def copy2EOS(): - import os - eos = "/afs/cern.ch/project/eos/installation/0.3.15/bin/eos.select" - for prod in [610,620]: - for run in range(0,10): - prefix = 'muon'+str(prod+run) - if prod in [610,620] and run == 0: prefix = 'muon'+str(int(prod/100)) - for i in range(1,10): - # requires full path - cmd = eos+' cp -r '+os.path.abspath('.')+'/'+prefix+str(i)+'/ /eos/experiment/ship/data/muonBackground/'+prefix+str(i)+'/' - print(cmd) - os.system(cmd) + import os + + eos = "/afs/cern.ch/project/eos/installation/0.3.15/bin/eos.select" + for prod in [610, 620]: + for run in range(0, 10): + prefix = "muon" + str(prod + run) + if prod in [610, 620] and run == 0: + prefix = "muon" + str(int(prod / 100)) + for i in range(1, 10): + # requires full path + cmd = ( + eos + + " cp -r " + + os.path.abspath(".") + + "/" + + prefix + + str(i) + + "/ /eos/experiment/ship/data/muonBackground/" + + prefix + + str(i) + + "/" + ) + print(cmd) + os.system(cmd) + + def copyFromEOS(): - import os - eos = "/afs/cern.ch/project/eos/installation/0.3.15/bin/eos.select" - for prod in [610,620]: - for run in range(0,10): - prefix = 'muon'+str(prod+run) - if prod in [610,620] and run == 0: prefix = 'muon'+str(int(prod/100)) - for i in range(1,10): - # requires full path - cmd = eos+' cp -r /eos/experiment/ship/data/muonBackground/'+prefix+str(i)+'/ ' +os.path.abspath('.')+'/'+prefix+str(i)+'/' - print(cmd) - os.system(cmd) + import os + + eos = "/afs/cern.ch/project/eos/installation/0.3.15/bin/eos.select" + for prod in [610, 620]: + for run in range(0, 10): + prefix = "muon" + str(prod + run) + if prod in [610, 620] and run == 0: + prefix = "muon" + str(int(prod / 100)) + for i in range(1, 10): + # requires full path + cmd = ( + eos + + " cp -r /eos/experiment/ship/data/muonBackground/" + + prefix + + str(i) + + "/ " + + os.path.abspath(".") + + "/" + + prefix + + str(i) + + "/" + ) + print(cmd) + os.system(cmd) diff --git a/muonShieldOptimization/run_reco.py b/muonShieldOptimization/run_reco.py index 69208525bf..27bcd6539a 100755 --- a/muonShieldOptimization/run_reco.py +++ b/muonShieldOptimization/run_reco.py @@ -1,330 +1,454 @@ -import os, subprocess,ROOT,time,getpass,multiprocessing +import getpass +import multiprocessing +import os +import subprocess +import time + +import ROOT import rootUtils as ut -ncores = min(multiprocessing.cpu_count(),4) -user = getpass.getuser() + +ncores = min(multiprocessing.cpu_count(), 4) +user = getpass.getuser() # support for eos, assume: eosmount $HOME/eos h = {} -def fitSingleGauss(x,ba=None,be=None): - name = 'myGauss_'+x + +def fitSingleGauss(x, ba=None, be=None): + name = "myGauss_" + x myGauss = h[x].GetListOfFunctions().FindObject(name) if not myGauss: - if not ba : ba = h[x].GetBinCenter(1) - if not be : be = h[x].GetBinCenter(h[x].GetNbinsX()) - bw = h[x].GetBinWidth(1) - mean = h[x].GetMean() - sigma = h[x].GetRMS() - norm = h[x].GetEntries()*0.3 - myGauss = ROOT.TF1(name,'[0]*'+str(bw)+'/([2]*sqrt(2*pi))*exp(-0.5*((x-[1])/[2])**2)+[3]',4) - myGauss.SetParameter(0,norm) - myGauss.SetParameter(1,mean) - myGauss.SetParameter(2,sigma) - myGauss.SetParameter(3,1.) - myGauss.SetParName(0,'Signal') - myGauss.SetParName(1,'Mean') - myGauss.SetParName(2,'Sigma') - myGauss.SetParName(3,'bckgr') - h[x].Fit(myGauss,'','',ba,be) - -cmd = os.environ["FAIRSHIP"]+"/macro/ShipReco.py" -cmdAna = os.environ["FAIRSHIP"]+"/macro/ShipAna.py" -def execute( ncpu = 4 ): - cpus = {} - log = {} - for i in range(ncpu): cpus[i]={} - jobs = [] - for x in os.listdir('.'): - if not x.find(prefix)<0: - if os.path.isdir(x) : - jobs.append(x) - k = 0 - print(jobs) - for x in jobs: - if k==ncpu: k = 0 - if 'child' in cpus[k]: - rc = child.communicate()[0] - log[k]['log'].close() - print("change to directory ",k,x) - os.chdir('./'+x) - for f in os.listdir('.'): - if not f.find("geofile_full")<0: - inputfile = f.replace("geofile_full","ship") - log[k] = open("logRec",'w') - cpus[k] = subprocess.Popen(["python",cmd,"-n 9999999 -f "+inputfile], stdout=log[k],) - k+=1 - os.chdir('../') - break - return cpus,log + if not ba: + ba = h[x].GetBinCenter(1) + if not be: + be = h[x].GetBinCenter(h[x].GetNbinsX()) + bw = h[x].GetBinWidth(1) + mean = h[x].GetMean() + sigma = h[x].GetRMS() + norm = h[x].GetEntries() * 0.3 + myGauss = ROOT.TF1( + name, + "[0]*" + str(bw) + "/([2]*sqrt(2*pi))*exp(-0.5*((x-[1])/[2])**2)+[3]", + 4, + ) + myGauss.SetParameter(0, norm) + myGauss.SetParameter(1, mean) + myGauss.SetParameter(2, sigma) + myGauss.SetParameter(3, 1.0) + myGauss.SetParName(0, "Signal") + myGauss.SetParName(1, "Mean") + myGauss.SetParName(2, "Sigma") + myGauss.SetParName(3, "bckgr") + h[x].Fit(myGauss, "", "", ba, be) + + +cmd = os.environ["FAIRSHIP"] + "/macro/ShipReco.py" +cmdAna = os.environ["FAIRSHIP"] + "/macro/ShipAna.py" + + +def execute(ncpu=4): + cpus = {} + log = {} + for i in range(ncpu): + cpus[i] = {} + jobs = [] + for x in os.listdir("."): + if not x.find(prefix) < 0: + if os.path.isdir(x): + jobs.append(x) + k = 0 + print(jobs) + for x in jobs: + if k == ncpu: + k = 0 + if "child" in cpus[k]: + rc = child.communicate()[0] + log[k]["log"].close() + print("change to directory ", k, x) + os.chdir("./" + x) + for f in os.listdir("."): + if not f.find("geofile_full") < 0: + inputfile = f.replace("geofile_full", "ship") + log[k] = open("logRec", "w") + cpus[k] = subprocess.Popen( + ["python", cmd, "-n 9999999 -f " + inputfile], + stdout=log[k], + ) + k += 1 + os.chdir("../") + break + return cpus, log + def getJobs(prefix): - jobs = [] - for x in os.listdir('.'): - if not x.find(prefix)<0: - if os.path.isdir(x) : - jobs.append(x) - return jobs + jobs = [] + for x in os.listdir("."): + if not x.find(prefix) < 0: + if os.path.isdir(x): + jobs.append(x) + return jobs + + def checkRunningProcesses(): - processoutput = os.popen("ps -u "+user).read() - nproc = 0 - for x in processoutput.split('\n'): - if not x.find('python')<0 and x.find('defunct')<0 : - nproc+=1 - return nproc + processoutput = os.popen("ps -u " + user).read() + nproc = 0 + for x in processoutput.split("\n"): + if not x.find("python") < 0 and x.find("defunct") < 0: + nproc += 1 + return nproc + + def killAll(): - processoutput = os.popen("ps -u "+user).read() - for x in processoutput.split('\n'): - if not x.find('python')<0: - pid = int(x[:5]) - print('kill '+str(pid)) - os.system('kill '+str(pid)) -def executeSimple(prefixes,reset=False): - proc = {} - for prefix in prefixes: - jobs = getJobs(prefix) - for x in jobs: - print("change to directory ",x) - os.chdir('./'+x) - geofile = None - for f in os.listdir('.'): - if not f.find("geofile_full")<0: - geofile = f - break - if not geofile: - print("ERROR: no geofile found",x) - os.chdir('../') - continue - else: - inputfile = geofile.replace("geofile_full","ship") - nproc = 100 - while nproc > ncores : - nproc = checkRunningProcesses() - if nproc > ncores: - print('wait a minute') - time.sleep(100) - print('launch reco',x) - proc[x] = 1 - try: os.system("rm logRec") - except: pass - if reset: os.system("python "+cmd+" -n 9999999 -f "+inputfile + " --saveDisk >> logRec &") - else: os.system("python "+cmd+" -n 9999999 -f "+inputfile + " >> logRec &") - os.chdir('../') - time.sleep(10) - nJobs = len(proc) - while nJobs > 0: - nJobs = len(proc) - print('debug ',nJobs) - for p in sorted(proc.keys()): - os.chdir('./'+p) - nproc = 100 - while nproc > ncores : - nproc = checkRunningProcesses() - if nproc > ncores: - print('wait a minute') - time.sleep(100) - log = open('logRec') - completed = False - rl = log.readlines() - log.close() - if "finishing" in rl[len(rl)-1] : completed = True - if completed: - print('analyze ',p,nproc) - try: os.system("rm logAna") - except: pass - os.system("python "+cmdAna+" -n 9999999 -f "+inputfile.replace('.root','_rec.root')+ " >> logAna &") - rc = proc.pop(p) - time.sleep(10) - else: - print('Rec job not finished yet',p) - nproc = checkRunningProcesses() - if nproc == 1 : print("rec job probably failed, only when python process running") - time.sleep(100) - os.chdir('../') + processoutput = os.popen("ps -u " + user).read() + for x in processoutput.split("\n"): + if not x.find("python") < 0: + pid = int(x[:5]) + print("kill " + str(pid)) + os.system("kill " + str(pid)) + + +def executeSimple(prefixes, reset=False): + proc = {} + for prefix in prefixes: + jobs = getJobs(prefix) + for x in jobs: + print("change to directory ", x) + os.chdir("./" + x) + geofile = None + for f in os.listdir("."): + if not f.find("geofile_full") < 0: + geofile = f + break + if not geofile: + print("ERROR: no geofile found", x) + os.chdir("../") + continue + else: + inputfile = geofile.replace("geofile_full", "ship") + nproc = 100 + while nproc > ncores: + nproc = checkRunningProcesses() + if nproc > ncores: + print("wait a minute") + time.sleep(100) + print("launch reco", x) + proc[x] = 1 + try: + os.system("rm logRec") + except: + pass + if reset: + os.system( + "python " + + cmd + + " -n 9999999 -f " + + inputfile + + " --saveDisk >> logRec &" + ) + else: + os.system( + "python " + cmd + " -n 9999999 -f " + inputfile + " >> logRec &" + ) + os.chdir("../") + time.sleep(10) + nJobs = len(proc) + while nJobs > 0: + nJobs = len(proc) + print("debug ", nJobs) + for p in sorted(proc.keys()): + os.chdir("./" + p) + nproc = 100 + while nproc > ncores: + nproc = checkRunningProcesses() + if nproc > ncores: + print("wait a minute") + time.sleep(100) + log = open("logRec") + completed = False + rl = log.readlines() + log.close() + if "finishing" in rl[len(rl) - 1]: + completed = True + if completed: + print("analyze ", p, nproc) + try: + os.system("rm logAna") + except: + pass + os.system( + "python " + + cmdAna + + " -n 9999999 -f " + + inputfile.replace(".root", "_rec.root") + + " >> logAna &" + ) + rc = proc.pop(p) + time.sleep(10) + else: + print("Rec job not finished yet", p) + nproc = checkRunningProcesses() + if nproc == 1: + print("rec job probably failed, only when python process running") + time.sleep(100) + os.chdir("../") + def executeAna(prefixes): - cpus = {} - log = {} - for prefix in prefixes: - jobs = getJobs(prefix) - for x in jobs: - print("change to directory ",x) - os.chdir('./'+x) - for f in os.listdir('.'): - if not f.find("geofile_full")<0: - inputfile = f.replace("geofile_full","ship") - log[x] = open("logAna",'w') - process = subprocess.Popen(["python",cmdAna,"-n 9999999", "-f "+inputfile.replace('.root','_rec.root')], stdout=log[x]) - process.wait() - print('finished ',process.returncode) - log[x].close() - os.chdir('../') - break - -h={} + cpus = {} + log = {} + for prefix in prefixes: + jobs = getJobs(prefix) + for x in jobs: + print("change to directory ", x) + os.chdir("./" + x) + for f in os.listdir("."): + if not f.find("geofile_full") < 0: + inputfile = f.replace("geofile_full", "ship") + log[x] = open("logAna", "w") + process = subprocess.Popen( + [ + "python", + cmdAna, + "-n 9999999", + "-f " + inputfile.replace(".root", "_rec.root"), + ], + stdout=log[x], + ) + process.wait() + print("finished ", process.returncode) + log[x].close() + os.chdir("../") + break + + +h = {} + + def mergeHistosMakePlots(p): - if not type(p)==type([]): pl=[p] - else: pl = p - hlist = '' - for p in pl: - prefix = str(p) - for x in os.listdir('.'): - if not x.find(prefix)<0: - if os.path.isdir(x) : - hlist += x+'/ShipAna.root ' - print("-->",hlist) - os.system('hadd -f ShipAna.root '+hlist) - ut.readHists(h,"ShipAna.root") - print(h['meanhits'].GetEntries()) - if 1>0: - ut.bookCanvas(h,key='strawanalysis',title='Distance to wire and mean nr of hits',nx=1200,ny=600,cx=2,cy=1) -# - cv = h['strawanalysis'].cd(1) - h['disty'].DrawCopy() - h['distu'].DrawCopy('same') - h['distv'].DrawCopy('same') - cv = h['strawanalysis'].cd(2) - h['meanhits'].DrawCopy() - print(h['meanhits'].GetEntries()) - - ut.bookCanvas(h,key='fitresults',title='Fit Results',nx=1600,ny=1200,cx=2,cy=2) - cv = h['fitresults'].cd(1) - h['delPOverP'].Draw('box') - cv = h['fitresults'].cd(2) - cv.SetLogy(1) - h['chi2'].Draw() - cv = h['fitresults'].cd(3) - h['delPOverP_proj'] = h['delPOverP'].ProjectionY() - ROOT.gStyle.SetOptFit(11111) - h['delPOverP_proj'].Draw() - h['delPOverP_proj'].Fit('gaus') - cv = h['fitresults'].cd(4) - h['delPOverP2_proj'] = h['delPOverP2'].ProjectionY() - h['delPOverP2_proj'].Draw() - fitSingleGauss('delPOverP2_proj') - h['fitresults'].Print('fitresults.gif') - ut.bookCanvas(h,key='fitresults2',title='Fit Results',nx=1600,ny=1200,cx=2,cy=2) - print('finished with first canvas') - cv = h['fitresults2'].cd(1) - h['Doca'].Draw() - cv = h['fitresults2'].cd(2) - h['IP0'].Draw() - cv = h['fitresults2'].cd(3) - h['HNL'].Draw() - fitSingleGauss('HNL',0.,2.) - cv = h['fitresults2'].cd(4) - h['IP0/mass'].Draw('box') - h['fitresults2'].Print('fitresults2.gif') - h['strawanalysis'].Print('strawanalysis.gif') - print('finished making plots') + if not type(p) == type([]): + pl = [p] + else: + pl = p + hlist = "" + for p in pl: + prefix = str(p) + for x in os.listdir("."): + if not x.find(prefix) < 0: + if os.path.isdir(x): + hlist += x + "/ShipAna.root " + print("-->", hlist) + os.system("hadd -f ShipAna.root " + hlist) + ut.readHists(h, "ShipAna.root") + print(h["meanhits"].GetEntries()) + if 1 > 0: + ut.bookCanvas( + h, + key="strawanalysis", + title="Distance to wire and mean nr of hits", + nx=1200, + ny=600, + cx=2, + cy=1, + ) + # + cv = h["strawanalysis"].cd(1) + h["disty"].DrawCopy() + h["distu"].DrawCopy("same") + h["distv"].DrawCopy("same") + cv = h["strawanalysis"].cd(2) + h["meanhits"].DrawCopy() + print(h["meanhits"].GetEntries()) + + ut.bookCanvas( + h, key="fitresults", title="Fit Results", nx=1600, ny=1200, cx=2, cy=2 + ) + cv = h["fitresults"].cd(1) + h["delPOverP"].Draw("box") + cv = h["fitresults"].cd(2) + cv.SetLogy(1) + h["chi2"].Draw() + cv = h["fitresults"].cd(3) + h["delPOverP_proj"] = h["delPOverP"].ProjectionY() + ROOT.gStyle.SetOptFit(11111) + h["delPOverP_proj"].Draw() + h["delPOverP_proj"].Fit("gaus") + cv = h["fitresults"].cd(4) + h["delPOverP2_proj"] = h["delPOverP2"].ProjectionY() + h["delPOverP2_proj"].Draw() + fitSingleGauss("delPOverP2_proj") + h["fitresults"].Print("fitresults.gif") + ut.bookCanvas( + h, key="fitresults2", title="Fit Results", nx=1600, ny=1200, cx=2, cy=2 + ) + print("finished with first canvas") + cv = h["fitresults2"].cd(1) + h["Doca"].Draw() + cv = h["fitresults2"].cd(2) + h["IP0"].Draw() + cv = h["fitresults2"].cd(3) + h["HNL"].Draw() + fitSingleGauss("HNL", 0.0, 2.0) + cv = h["fitresults2"].cd(4) + h["IP0/mass"].Draw("box") + h["fitresults2"].Print("fitresults2.gif") + h["strawanalysis"].Print("strawanalysis.gif") + print("finished making plots") + def mergeNtuples(prefixes): - for prefix in prefixes: - jobs = getJobs(prefix) - haddCommand = '' - for x in jobs: - for f in os.listdir(x): - if not f.find("geofile_full")<0: - inputfile = (f.replace("geofile_full","ship")).replace('.root','_rec.root') - haddCommand+= ' '+ x + '/' + inputfile - break - cmd = 'hadd -f '+inputfile.replace('.root','_'+prefix+'.root') + haddCommand - os.system(cmd) -def checkProd(prefixes,quiet=False): - summary = {'Sim':{},'Rec':{},'Ana':{}} - for prefix in prefixes: - jobs = getJobs(prefix) - for x in jobs: - try: log = open( x+'/log') - except: - if not quiet: print('no log file for ',x) - summary['Sim'][x] = -1 - continue - rl = log.readlines() - log.close() - if len(rl)<1 : - if not quiet: print("simulation failed log file 0",x) - summary['Sim'][x] = 0 - continue - elif "Real time" in rl[len(rl)-1] : - if not quiet: print('simulation step OK ',x) - summary['Sim'][x] = 1 - else: - if not quiet: print("simulation failed ",x) - summary['Sim'][x] = 0 - continue - try: log = open( x+'/logRec') - except: - if not quiet: print('no logRec file for ',x) - summary['Rec'][x] = -1 - continue - rl = log.readlines() - log.close() - if "finishing" in rl[len(rl)-1] : - if not quiet: print('reconstruction step OK ',x) - summary['Rec'][x] = 1 - else: - if not quiet: print("reconstruction failed ",x) - summary['Rec'][x] = 0 - continue - try: log = open( x+'/logAna') - except: - if not quiet: print('no logAna file for ',x) - summary['Ana'][x] = -1 - continue - rl = log.readlines() - log.close() - if "finished" in rl[len(rl)-1] : - if not quiet: print('analysis step OK ',x) - summary['Ana'][x] = 1 - else: - if not quiet: print("analysis failed ",x) - summary['Ana'][x] = 0 - continue - return summary + for prefix in prefixes: + jobs = getJobs(prefix) + haddCommand = "" + for x in jobs: + for f in os.listdir(x): + if not f.find("geofile_full") < 0: + inputfile = (f.replace("geofile_full", "ship")).replace( + ".root", "_rec.root" + ) + haddCommand += " " + x + "/" + inputfile + break + cmd = ( + "hadd -f " + + inputfile.replace(".root", "_" + prefix + ".root") + + haddCommand + ) + os.system(cmd) + + +def checkProd(prefixes, quiet=False): + summary = {"Sim": {}, "Rec": {}, "Ana": {}} + for prefix in prefixes: + jobs = getJobs(prefix) + for x in jobs: + try: + log = open(x + "/log") + except: + if not quiet: + print("no log file for ", x) + summary["Sim"][x] = -1 + continue + rl = log.readlines() + log.close() + if len(rl) < 1: + if not quiet: + print("simulation failed log file 0", x) + summary["Sim"][x] = 0 + continue + elif "Real time" in rl[len(rl) - 1]: + if not quiet: + print("simulation step OK ", x) + summary["Sim"][x] = 1 + else: + if not quiet: + print("simulation failed ", x) + summary["Sim"][x] = 0 + continue + try: + log = open(x + "/logRec") + except: + if not quiet: + print("no logRec file for ", x) + summary["Rec"][x] = -1 + continue + rl = log.readlines() + log.close() + if "finishing" in rl[len(rl) - 1]: + if not quiet: + print("reconstruction step OK ", x) + summary["Rec"][x] = 1 + else: + if not quiet: + print("reconstruction failed ", x) + summary["Rec"][x] = 0 + continue + try: + log = open(x + "/logAna") + except: + if not quiet: + print("no logAna file for ", x) + summary["Ana"][x] = -1 + continue + rl = log.readlines() + log.close() + if "finished" in rl[len(rl) - 1]: + if not quiet: + print("analysis step OK ", x) + summary["Ana"][x] = 1 + else: + if not quiet: + print("analysis failed ", x) + summary["Ana"][x] = 0 + continue + return summary + + def printFailedJobs(pl): - result = checkProd(pl,quiet=True) - for p in result: - for x in result[p]: - if result[p][x]<1 : print(p,x,result[p][x]) + result = checkProd(pl, quiet=True) + for p in result: + for x in result[p]: + if result[p][x] < 1: + print(p, x, result[p][x]) def execute(): - executeSimple(pl,reset=True) - mergeHistosMakePlots(pl) - mergeNtuples(pl) + executeSimple(pl, reset=True) + mergeHistosMakePlots(pl) + mergeNtuples(pl) + + def removeIntermediateFiles(prefixes): - for prefix in prefixes: - jobs = getJobs(prefix) - for x in jobs: - for f in os.listdir(x): - if not f.find("geofile_full")<0: - inputfile = (f.replace("geofile_full","ship")).replace('.root','_rec.root') - os.system('rm '+x+'/' + inputfile ) + for prefix in prefixes: + jobs = getJobs(prefix) + for x in jobs: + for f in os.listdir(x): + if not f.find("geofile_full") < 0: + inputfile = (f.replace("geofile_full", "ship")).replace( + ".root", "_rec.root" + ) + os.system("rm " + x + "/" + inputfile) + def copyRecoToEos(pl): - result = checkProd(pl,quiet=True) - eos = "/afs/cern.ch/project/eos/installation/0.3.15/bin/eos.select" - for x in result['Rec']: - if result['Rec'][x]<1 : print('Reco failed !',x,result['Rec'][x]) - else: - cmd = eos+' cp -r '+os.path.abspath('.')+'/'+x+'/ /eos/experiment/ship/data/DAFreco/muonBackground/'+x+'/' - os.system(cmd) - print('copied to eos',x) - -pl=[] -for p in os.sys.argv[1].split(','): - pref = 'muon' - xx = os.path.abspath('.').lower() - if not xx.find('neutrino')<0: pref='neutrino' - if not xx.find('vdis')<0 or not xx.find('vetodis')<0: pref='disV' - elif not xx.find('clby')<0: pref='disCLBY' - elif not xx.find('dis')<0: pref='dis' - pl.append(pref+p) -print(" execute() input comma separated production nr, performs Simple/mergeHistos/mergeNtuples ") + result = checkProd(pl, quiet=True) + eos = "/afs/cern.ch/project/eos/installation/0.3.15/bin/eos.select" + for x in result["Rec"]: + if result["Rec"][x] < 1: + print("Reco failed !", x, result["Rec"][x]) + else: + cmd = ( + eos + + " cp -r " + + os.path.abspath(".") + + "/" + + x + + "/ /eos/experiment/ship/data/DAFreco/muonBackground/" + + x + + "/" + ) + os.system(cmd) + print("copied to eos", x) + + +pl = [] +for p in os.sys.argv[1].split(","): + pref = "muon" + xx = os.path.abspath(".").lower() + if not xx.find("neutrino") < 0: + pref = "neutrino" + if not xx.find("vdis") < 0 or not xx.find("vetodis") < 0: + pref = "disV" + elif not xx.find("clby") < 0: + pref = "disCLBY" + elif not xx.find("dis") < 0: + pref = "dis" + pl.append(pref + p) +print( + " execute() input comma separated production nr, performs Simple/mergeHistos/mergeNtuples " +) print(" executeSimple(pl,reset=True) ") print(" checkProd(pl)") print(" executeAna(pl) ") print(" mergeNtuples(pl) ") print(" removeIntermediateFiles(pl) only _rec ") print(" checkRunningProcesses() ") -#61,611,612,613,614,615,616,62,621,622,623,624,625,626 +# 61,611,612,613,614,615,616,62,621,622,623,624,625,626 diff --git a/muonShieldOptimization/simpleTarget.cxx b/muonShieldOptimization/simpleTarget.cxx index f9d3d6e0ed..c138e7a640 100644 --- a/muonShieldOptimization/simpleTarget.cxx +++ b/muonShieldOptimization/simpleTarget.cxx @@ -1,162 +1,175 @@ #include "simpleTarget.h" -#include -#include "vetoPoint.h" -#include "FairLogger.h" // for FairLogger, MESSAGE_ORIGIN -#include "FairVolume.h" -#include "FairGeoVolume.h" -#include "FairGeoNode.h" -#include "FairRootManager.h" -#include "FairGeoLoader.h" +#include "FairGeoBuilder.h" #include "FairGeoInterface.h" +#include "FairGeoLoader.h" #include "FairGeoMedia.h" -#include "FairGeoBuilder.h" +#include "FairGeoNode.h" +#include "FairGeoVolume.h" +#include "FairLogger.h" // for FairLogger, MESSAGE_ORIGIN +#include "FairRootManager.h" #include "FairRun.h" #include "FairRuntimeDb.h" +#include "FairVolume.h" #include "ShipDetectorList.h" #include "ShipStack.h" - #include "TClonesArray.h" -#include "TVirtualMC.h" -#include "TGeoManager.h" #include "TGeoBBox.h" -#include "TGeoEltu.h" #include "TGeoBoolNode.h" +#include "TGeoEltu.h" +#include "TGeoManager.h" #include "TGeoMaterial.h" -#include "TParticle.h" -#include "TROOT.h" #include "TH1D.h" #include "TH2D.h" +#include "TParticle.h" +#include "TROOT.h" +#include "TVirtualMC.h" +#include "vetoPoint.h" #include +#include using std::cout; using std::endl; simpleTarget::simpleTarget() - : FairDetector("simpleTarget", kTRUE, kVETO), - fTrackID(-1), - fVolumeID(-1), - fPos(), - fMom(), - fTime(-1.), - fLength(-1.), - fThick(-1.), - fOnlyMuons(kFALSE), - fFastMuon(kFALSE), - fzPos(3E8), - fTotalEloss(0), - fsimpleTargetPointCollection(new TClonesArray("vetoPoint")) + : FairDetector("simpleTarget", kTRUE, kVETO) + , fTrackID(-1) + , fVolumeID(-1) + , fPos() + , fMom() + , fTime(-1.) + , fLength(-1.) + , fThick(-1.) + , fOnlyMuons(kFALSE) + , fFastMuon(kFALSE) + , fzPos(3E8) + , fTotalEloss(0) + , fsimpleTargetPointCollection(new TClonesArray("vetoPoint")) {} simpleTarget::~simpleTarget() { - if (fsimpleTargetPointCollection) { - fsimpleTargetPointCollection->Delete(); - delete fsimpleTargetPointCollection; - } + if (fsimpleTargetPointCollection) { + fsimpleTargetPointCollection->Delete(); + delete fsimpleTargetPointCollection; + } } -Bool_t simpleTarget::ProcessHits(FairVolume* vol) +Bool_t simpleTarget::ProcessHits(FairVolume* vol) { - /** This method is called from the MC stepping */ - //Set parameters at entrance of volume. Reset ELoss. - if ( gMC->IsTrackEntering() ) { - fELoss = 0.; - fTime = gMC->TrackTime() * 1.0e09; - fLength = gMC->TrackLength(); - gMC->TrackPosition(fPos); - gMC->TrackMomentum(fMom); - } - // Sum energy loss for all steps in the active volume - fELoss += gMC->Edep(); - - // Create vetoPoint at exit of active volume - if ( gMC->IsTrackExiting() || - gMC->IsTrackStop() || - gMC->IsTrackDisappeared() ) { - if (fELoss == 0. ) { return kFALSE; } - // if (fOnlyMuons and fPos.Z()<140){ used for LiquidKrypton study - if (fOnlyMuons){ - fTotalEloss+=fELoss; - TClonesArray& clref = *fsimpleTargetPointCollection; - new (clref[0]) vetoPoint(0, 0, TVector3(0, 0, 0), TVector3(0, 0, 0), - 0, 0, fTotalEloss, 0,TVector3(0, 0, 0), TVector3(0, 0, 0)); - return kTRUE;} - - fTrackID = gMC->GetStack()->GetCurrentTrackNumber(); - - Int_t veto_uniqueId; - gMC->CurrentVolID(veto_uniqueId); - - TParticle* p=gMC->GetStack()->GetCurrentTrack(); - Int_t pdgCode = p->GetPdgCode(); - TLorentzVector Pos; - gMC->TrackPosition(Pos); - TLorentzVector Mom; - gMC->TrackMomentum(Mom); - Double_t xmean = (fPos.X()+Pos.X())/2. ; - Double_t ymean = (fPos.Y()+Pos.Y())/2. ; - Double_t zmean = (fPos.Z()+Pos.Z())/2. ; - //cout << veto_uniqueId << " :(" << xmean << ", " << ymean << ", " << zmean << "): " << fELoss << endl; - AddHit(fTrackID, veto_uniqueId, TVector3(xmean, ymean, zmean), - TVector3(fMom.Px(), fMom.Py(), fMom.Pz()), fTime, fLength, - fELoss,pdgCode,TVector3(Pos.X(), Pos.Y(), Pos.Z()),TVector3(Mom.Px(), Mom.Py(), Mom.Pz()) ); - - // Increment number of veto det points in TParticle - ShipStack* stack = (ShipStack*) gMC->GetStack(); - stack->AddPoint(kVETO); - } - - return kTRUE; -} + /** This method is called from the MC stepping */ + // Set parameters at entrance of volume. Reset ELoss. + if (gMC->IsTrackEntering()) { + fELoss = 0.; + fTime = gMC->TrackTime() * 1.0e09; + fLength = gMC->TrackLength(); + gMC->TrackPosition(fPos); + gMC->TrackMomentum(fMom); + } + // Sum energy loss for all steps in the active volume + fELoss += gMC->Edep(); + + // Create vetoPoint at exit of active volume + if (gMC->IsTrackExiting() || gMC->IsTrackStop() || gMC->IsTrackDisappeared()) { + if (fELoss == 0.) { + return kFALSE; + } + // if (fOnlyMuons and fPos.Z()<140){ used for LiquidKrypton study + if (fOnlyMuons) { + fTotalEloss += fELoss; + TClonesArray& clref = *fsimpleTargetPointCollection; + new (clref[0]) vetoPoint( + 0, 0, TVector3(0, 0, 0), TVector3(0, 0, 0), 0, 0, fTotalEloss, 0, TVector3(0, 0, 0), TVector3(0, 0, 0)); + return kTRUE; + } + + fTrackID = gMC->GetStack()->GetCurrentTrackNumber(); + + Int_t veto_uniqueId; + gMC->CurrentVolID(veto_uniqueId); + + TParticle* p = gMC->GetStack()->GetCurrentTrack(); + Int_t pdgCode = p->GetPdgCode(); + TLorentzVector Pos; + gMC->TrackPosition(Pos); + TLorentzVector Mom; + gMC->TrackMomentum(Mom); + Double_t xmean = (fPos.X() + Pos.X()) / 2.; + Double_t ymean = (fPos.Y() + Pos.Y()) / 2.; + Double_t zmean = (fPos.Z() + Pos.Z()) / 2.; + // cout << veto_uniqueId << " :(" << xmean << ", " << ymean << ", " << zmean << "): " << fELoss << endl; + AddHit(fTrackID, + veto_uniqueId, + TVector3(xmean, ymean, zmean), + TVector3(fMom.Px(), fMom.Py(), fMom.Pz()), + fTime, + fLength, + fELoss, + pdgCode, + TVector3(Pos.X(), Pos.Y(), Pos.Z()), + TVector3(Mom.Px(), Mom.Py(), Mom.Pz())); + + // Increment number of veto det points in TParticle + ShipStack* stack = (ShipStack*)gMC->GetStack(); + stack->AddPoint(kVETO); + } + return kTRUE; +} void simpleTarget::Initialize() { - FairDetector::Initialize(); - TSeqCollection* fileList=gROOT->GetListOfFiles(); - fout = ((TFile*)fileList->At(0)); + FairDetector::Initialize(); + TSeqCollection* fileList = gROOT->GetListOfFiles(); + fout = ((TFile*)fileList->At(0)); } void simpleTarget::EndOfEvent() { - fsimpleTargetPointCollection->Clear(); - fTotalEloss=0; + fsimpleTargetPointCollection->Clear(); + fTotalEloss = 0; } - void simpleTarget::ConstructGeometry() { - static FairGeoLoader *geoLoad=FairGeoLoader::Instance(); - static FairGeoInterface *geoFace=geoLoad->getGeoInterface(); - static FairGeoMedia *media=geoFace->getMedia(); - static FairGeoBuilder *geoBuild=geoLoad->getGeoBuilder(); - - FairGeoMedium *ShipMedium=media->getMedium(fMaterial); - TGeoMedium* mat=gGeoManager->GetMedium(fMaterial); - if (mat==NULL) - geoBuild->createMedium(ShipMedium); - mat =gGeoManager->GetMedium(fMaterial); - TGeoVolume *top=gGeoManager->GetTopVolume(); - TGeoVolume *target = gGeoManager->MakeBox("target",mat,10.*100.,10.*100.,fThick); - top->AddNode(target, 1, new TGeoTranslation(0, 0, fzPos)); - AddSensitiveVolume(target); + static FairGeoLoader* geoLoad = FairGeoLoader::Instance(); + static FairGeoInterface* geoFace = geoLoad->getGeoInterface(); + static FairGeoMedia* media = geoFace->getMedia(); + static FairGeoBuilder* geoBuild = geoLoad->getGeoBuilder(); + + FairGeoMedium* ShipMedium = media->getMedium(fMaterial); + TGeoMedium* mat = gGeoManager->GetMedium(fMaterial); + if (mat == NULL) + geoBuild->createMedium(ShipMedium); + mat = gGeoManager->GetMedium(fMaterial); + TGeoVolume* top = gGeoManager->GetTopVolume(); + TGeoVolume* target = gGeoManager->MakeBox("target", mat, 10. * 100., 10. * 100., fThick); + top->AddNode(target, 1, new TGeoTranslation(0, 0, fzPos)); + AddSensitiveVolume(target); } -vetoPoint* simpleTarget::AddHit(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t time, Double_t length, - Double_t eLoss, Int_t pdgCode,TVector3 Lpos, TVector3 Lmom) +vetoPoint* simpleTarget::AddHit(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t time, + Double_t length, + Double_t eLoss, + Int_t pdgCode, + TVector3 Lpos, + TVector3 Lmom) { - TClonesArray& clref = *fsimpleTargetPointCollection; - Int_t size = clref.GetEntriesFast(); - return new(clref[size]) vetoPoint(trackID, detID, pos, mom, - time, length, eLoss, pdgCode,Lpos,Lmom); + TClonesArray& clref = *fsimpleTargetPointCollection; + Int_t size = clref.GetEntriesFast(); + return new (clref[size]) vetoPoint(trackID, detID, pos, mom, time, length, eLoss, pdgCode, Lpos, Lmom); } -void simpleTarget::PreTrack(){ - if (!fFastMuon){return;} - if (TMath::Abs(gMC->TrackPid())!=13){ +void simpleTarget::PreTrack() +{ + if (!fFastMuon) { + return; + } + if (TMath::Abs(gMC->TrackPid()) != 13) { gMC->StopTrack(); } } @@ -164,16 +177,18 @@ void simpleTarget::PreTrack(){ void simpleTarget::Register() { - FairRootManager::Instance()->Register("vetoPoint", "veto", - fsimpleTargetPointCollection, kTRUE); + FairRootManager::Instance()->Register("vetoPoint", "veto", fsimpleTargetPointCollection, kTRUE); } TClonesArray* simpleTarget::GetCollection(Int_t iColl) const { - if (iColl == 0) { return fsimpleTargetPointCollection; } - else { return NULL; } + if (iColl == 0) { + return fsimpleTargetPointCollection; + } else { + return NULL; + } } void simpleTarget::Reset() { - fsimpleTargetPointCollection->Clear(); + fsimpleTargetPointCollection->Clear(); } diff --git a/muonShieldOptimization/simpleTarget.h b/muonShieldOptimization/simpleTarget.h index beb603e42a..f9ec341fc2 100644 --- a/muonShieldOptimization/simpleTarget.h +++ b/muonShieldOptimization/simpleTarget.h @@ -2,24 +2,24 @@ #define simpleTarget_H #include "FairDetector.h" -#include "TVector3.h" -#include "TLorentzVector.h" #include "TGeoVolume.h" +#include "TLorentzVector.h" +#include "TVector3.h" #include "vetoPoint.h" + #include class FairVolume; class TClonesArray; -class simpleTarget: public FairDetector +class simpleTarget : public FairDetector { public: - /** Name : Detector Name * Active: kTRUE for active detectors (ProcessHits() will be called) * kFALSE for inactive detectors - */ + */ simpleTarget(const char* Name, Bool_t Active); /** default constructor */ @@ -29,72 +29,81 @@ class simpleTarget: public FairDetector virtual ~simpleTarget(); /** Initialization of the detector is done here */ - virtual void Initialize(); + virtual void Initialize(); /** this method is called for each step during simulation * (see FairMCApplication::Stepping()) - */ - virtual Bool_t ProcessHits( FairVolume* v=0); + */ + virtual Bool_t ProcessHits(FairVolume* v = 0); /** Registers the produced collections in FAIRRootManager. */ - virtual void Register(); + virtual void Register(); /** Gets the produced collections */ - virtual TClonesArray* GetCollection(Int_t iColl) const ; + virtual TClonesArray* GetCollection(Int_t iColl) const; /** has to be called after each event to reset the containers */ - virtual void Reset(); + virtual void Reset(); /** Create the detector geometry */ void ConstructGeometry(); /** The following methods can be implemented if you need to make * any optional action in your detector during the transport. - */ - - virtual void CopyClones( TClonesArray* cl1, TClonesArray* cl2 , - Int_t offset) {;} - virtual void SetSpecialPhysicsCuts() {;} - virtual void EndOfEvent(); - virtual void FinishPrimary() {;} - virtual void FinishRun() {;} - virtual void BeginPrimary() {;} - virtual void PostTrack() {;} - virtual void PreTrack(); - virtual void BeginEvent() {;} - - vetoPoint* AddHit(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t time, Double_t length, - Double_t eLoss,Int_t pdgcode,TVector3 Lpos, TVector3 Lmom); - inline void SetEnergyCut(Float_t emax) {EMax=emax;}// min energy to be copied to Geant4 - inline void SetOnlyMuons(){fOnlyMuons=kTRUE;} - inline void SetFastMuon(){fFastMuon=kTRUE;} - inline void SetParameters(TString m,Float_t l,Float_t z){fMaterial=m;fThick=l;fzPos=z;} + */ + + virtual void CopyClones(TClonesArray* cl1, TClonesArray* cl2, Int_t offset) { ; } + virtual void SetSpecialPhysicsCuts() { ; } + virtual void EndOfEvent(); + virtual void FinishPrimary() { ; } + virtual void FinishRun() { ; } + virtual void BeginPrimary() { ; } + virtual void PostTrack() { ; } + virtual void PreTrack(); + virtual void BeginEvent() { ; } + + vetoPoint* AddHit(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t time, + Double_t length, + Double_t eLoss, + Int_t pdgcode, + TVector3 Lpos, + TVector3 Lmom); + inline void SetEnergyCut(Float_t emax) { EMax = emax; } // min energy to be copied to Geant4 + inline void SetOnlyMuons() { fOnlyMuons = kTRUE; } + inline void SetFastMuon() { fFastMuon = kTRUE; } + inline void SetParameters(TString m, Float_t l, Float_t z) + { + fMaterial = m; + fThick = l; + fzPos = z; + } private: - /** Track information to be stored until the track leaves the active volume. */ - Int_t fTrackID; //! track index - Int_t fVolumeID; //! volume id - TLorentzVector fPos; //! position at entrance - TLorentzVector fMom; //! momentum at entrance - Double_t fTime; //! time - Double_t fLength; //! length - Double_t fzPos; //! zPos - Double_t fThick; //! thickness - Double_t fELoss; //! - Double_t fTotalEloss; //! - TString fMaterial; //! material - Float_t EMax; //! max energy to transport - Bool_t fOnlyMuons; //! - Bool_t fFastMuon; //! for fast processing + Int_t fTrackID; //! track index + Int_t fVolumeID; //! volume id + TLorentzVector fPos; //! position at entrance + TLorentzVector fMom; //! momentum at entrance + Double_t fTime; //! time + Double_t fLength; //! length + Double_t fzPos; //! zPos + Double_t fThick; //! thickness + Double_t fELoss; //! + Double_t fTotalEloss; //! + TString fMaterial; //! material + Float_t EMax; //! max energy to transport + Bool_t fOnlyMuons; //! + Bool_t fFastMuon; //! for fast processing TFile* fout; /** container for data points */ - TClonesArray* fsimpleTargetPointCollection; + TClonesArray* fsimpleTargetPointCollection; ClassDef(simpleTarget, 0) }; -#endif //simpleTarget_H +#endif // simpleTarget_H diff --git a/muonShieldOptimization/study_GammaConv.py b/muonShieldOptimization/study_GammaConv.py index f9a5c561a9..443b71074e 100644 --- a/muonShieldOptimization/study_GammaConv.py +++ b/muonShieldOptimization/study_GammaConv.py @@ -1,38 +1,52 @@ #!/usr/bin/env python -import ROOT,os,sys,time,shipRoot_conf +import os +import sys +import time + +import ROOT +import shipRoot_conf + ROOT.gROOT.ProcessLine('#include "FairModule.h"') time.sleep(20) import shipunit as u from ShipGeoConfig import ConfigRegistry -mcEngine = "TGeant4" -runnr = 1 -nev = 10# 000000 +mcEngine = "TGeant4" +runnr = 1 +nev = 10 # 000000 setup = {} -setup['10'] = {'thickness': 2*u.cm, 'material':'aluminium','momentum': 10*u.GeV} -setup['100'] = {'thickness': 2*u.cm, 'material':'aluminium','momentum': 100*u.GeV} -setup['200'] = {'thickness': 2*u.cm, 'material':'aluminium','momentum': 200*u.GeV} +setup["10"] = {"thickness": 2 * u.cm, "material": "aluminium", "momentum": 10 * u.GeV} +setup["100"] = {"thickness": 2 * u.cm, "material": "aluminium", "momentum": 100 * u.GeV} +setup["200"] = {"thickness": 2 * u.cm, "material": "aluminium", "momentum": 200 * u.GeV} # 8cm = 0.9X0 s = sys.argv[1] -thickness = setup[s]['thickness'] -material = setup[s]['material'] -momentum = setup[s]['momentum'] +thickness = setup[s]["thickness"] +material = setup[s]["material"] +momentum = setup[s]["momentum"] checkOverlap = True -outFile = "gconv"+s+".root" -theSeed = int(10000 * time.time() % 10000000) -ecut = 0.0 +outFile = "gconv" + s + ".root" +theSeed = int(10000 * time.time() % 10000000) +ecut = 0.0 # ------------------------------------------------------------------- -ROOT.gRandom.SetSeed(theSeed) # this should be propagated via ROOT to Pythia8 and Geant4VMC -shipRoot_conf.configure() # load basic libraries, prepare atexit for python -ship_geo = ConfigRegistry.loadpy("$FAIRSHIP/geometry/geometry_config.py", Yheight = 10, tankDesign = 5, muShieldDesign = 7, nuTauTargetDesign=1) +ROOT.gRandom.SetSeed( + theSeed +) # this should be propagated via ROOT to Pythia8 and Geant4VMC +shipRoot_conf.configure() # load basic libraries, prepare atexit for python +ship_geo = ConfigRegistry.loadpy( + "$FAIRSHIP/geometry/geometry_config.py", + Yheight=10, + tankDesign=5, + muShieldDesign=7, + nuTauTargetDesign=1, +) # -----Timer-------------------------------------------------------- timer = ROOT.TStopwatch() @@ -42,55 +56,64 @@ run = ROOT.FairRunSim() run.SetName(mcEngine) # Transport engine run.SetOutputFile(outFile) # Output file -run.SetUserConfig("g4Config.C") # user configuration file default g4Config.C +run.SetUserConfig("g4Config.C") # user configuration file default g4Config.C rtdb = run.GetRuntimeDb() # -----Materials---------------------------------------------- run.SetMaterials("media.geo") # -----Create geometry---------------------------------------------- -cave= ROOT.ShipCave("CAVE") +cave = ROOT.ShipCave("CAVE") cave.SetGeometryFileName("cave.geo") run.AddModule(cave) + class Block(ROOT.pyFairModule): - "block of material" - def __init__(self): - ROOT.pyFairModule.__init__(self,self) - self.sensPlane = None - def ConstructGeometry(self): - print("Construct Block") - top=ROOT.gGeoManager.GetTopVolume() - geoLoad=ROOT.FairGeoLoader.Instance() - geoFace=geoLoad.getGeoInterface() - media=geoFace.getMedia() - geoBuild=geoLoad.getGeoBuilder() - ShipMedium=media.getMedium(material) - W = ROOT.gGeoManager.GetMedium(material) - if not W: - rc = geoBuild.createMedium(ShipMedium) + "block of material" + + def __init__(self): + ROOT.pyFairModule.__init__(self, self) + self.sensPlane = None + + def ConstructGeometry(self): + print("Construct Block") + top = ROOT.gGeoManager.GetTopVolume() + geoLoad = ROOT.FairGeoLoader.Instance() + geoFace = geoLoad.getGeoInterface() + media = geoFace.getMedia() + geoBuild = geoLoad.getGeoBuilder() + ShipMedium = media.getMedium(material) W = ROOT.gGeoManager.GetMedium(material) - aBox = ROOT.gGeoManager.MakeBox("target", W, 100.*u.cm, 100.*u.cm, thickness) - top.AddNode(aBox, 1, ROOT.TGeoTranslation(0, 0, 0 )) - if self.sensPlane: self.sensPlane.AddSensitiveVolume(aBox) - def InitParContainers(): - print("not implemented!") - def makeSensitive(self,sensPlane): - self.sensPlane = sensPlane + if not W: + rc = geoBuild.createMedium(ShipMedium) + W = ROOT.gGeoManager.GetMedium(material) + aBox = ROOT.gGeoManager.MakeBox( + "target", W, 100.0 * u.cm, 100.0 * u.cm, thickness + ) + top.AddNode(aBox, 1, ROOT.TGeoTranslation(0, 0, 0)) + if self.sensPlane: + self.sensPlane.AddSensitiveVolume(aBox) + + def InitParContainers(): + print("not implemented!") + + def makeSensitive(self, sensPlane): + self.sensPlane = sensPlane + sensPlane = ROOT.exitHadronAbsorber() -sensPlane.SetEnergyCut(ecut*u.GeV) -sensPlane.SetZposition(thickness+10*u.cm) +sensPlane.SetEnergyCut(ecut * u.GeV) +sensPlane.SetZposition(thickness + 10 * u.cm) run.AddModule(sensPlane) target = Block() target.makeSensitive(sensPlane) run.AddModule(target) primGen = ROOT.FairPrimaryGenerator() -myPgun = ROOT.FairBoxGenerator(22,1) # pdg id and multiplicity -myPgun.SetPRange(momentum-0.01,momentum+0.01) -myPgun.SetPhiRange(0,0) # // Azimuth angle range [degree] -myPgun.SetThetaRange(0,0) # // Polar angle in lab system range [degree] -myPgun.SetXYZ(0.*u.cm, 0.*u.cm, -10.*u.cm - (thickness) ) +myPgun = ROOT.FairBoxGenerator(22, 1) # pdg id and multiplicity +myPgun.SetPRange(momentum - 0.01, momentum + 0.01) +myPgun.SetPhiRange(0, 0) # // Azimuth angle range [degree] +myPgun.SetThetaRange(0, 0) # // Polar angle in lab system range [degree] +myPgun.SetXYZ(0.0 * u.cm, 0.0 * u.cm, -10.0 * u.cm - (thickness)) primGen.AddGenerator(myPgun) run.SetGenerator(primGen) # @@ -101,18 +124,22 @@ def makeSensitive(self,sensPlane): fStack = gMC.GetStack() fStack.SetMinPoints(1) -fStack.SetEnergyCut(-1.) +fStack.SetEnergyCut(-1.0) -boostFactor = 100. +boostFactor = 100.0 if boostFactor > 1: - ROOT.gROOT.ProcessLine('#include "Geant4/G4ProcessTable.hh"') - ROOT.gROOT.ProcessLine('#include "Geant4/G4AnnihiToMuPair.hh"') - ROOT.gROOT.ProcessLine('#include "Geant4/G4GammaConversionToMuons.hh"') - gProcessTable = ROOT.G4ProcessTable.GetProcessTable() - procAnnihil = gProcessTable.FindProcess(ROOT.G4String('AnnihiToMuPair'),ROOT.G4String('e+')) - procGMuPair = gProcessTable.FindProcess(ROOT.G4String('GammaToMuPair'),ROOT.G4String('gamma')) - procGMuPair.SetCrossSecFactor(boostFactor) - procAnnihil.SetCrossSecFactor(boostFactor) + ROOT.gROOT.ProcessLine('#include "Geant4/G4ProcessTable.hh"') + ROOT.gROOT.ProcessLine('#include "Geant4/G4AnnihiToMuPair.hh"') + ROOT.gROOT.ProcessLine('#include "Geant4/G4GammaConversionToMuons.hh"') + gProcessTable = ROOT.G4ProcessTable.GetProcessTable() + procAnnihil = gProcessTable.FindProcess( + ROOT.G4String("AnnihiToMuPair"), ROOT.G4String("e+") + ) + procGMuPair = gProcessTable.FindProcess( + ROOT.G4String("GammaToMuPair"), ROOT.G4String("gamma") + ) + procGMuPair.SetCrossSecFactor(boostFactor) + procAnnihil.SetCrossSecFactor(boostFactor) # -----Start run---------------------------------------------------- run.Run(nev) @@ -124,27 +151,29 @@ def makeSensitive(self,sensPlane): import rootUtils as ut -f=ROOT.gROOT.GetListOfFiles()[0] -h={} -ut.bookHist(h,'muons','muon mult',10,-0.5,9.5) -ut.bookHist(h,'electrons','e mult',10,-0.5,9.5) +f = ROOT.gROOT.GetListOfFiles()[0] +h = {} +ut.bookHist(h, "muons", "muon mult", 10, -0.5, 9.5) +ut.bookHist(h, "electrons", "e mult", 10, -0.5, 9.5) sTree = f.cbmsim for n in range(sTree.GetEntries()): - rc = sTree.GetEvent(n) - nMu = 0 - nEl = 0 - for aHit in sTree.vetoPoint: - if abs(sTree.MCTrack[aHit.GetTrackID()].GetPdgCode())==13: nMu+=1 - if abs(sTree.MCTrack[aHit.GetTrackID()].GetPdgCode())==11: nEl+=1 - rc = h['muons'].Fill(nMu) - rc = h['electrons'].Fill(nEl) -h['muons'].Draw() + rc = sTree.GetEvent(n) + nMu = 0 + nEl = 0 + for aHit in sTree.vetoPoint: + if abs(sTree.MCTrack[aHit.GetTrackID()].GetPdgCode()) == 13: + nMu += 1 + if abs(sTree.MCTrack[aHit.GetTrackID()].GetPdgCode()) == 11: + nEl += 1 + rc = h["muons"].Fill(nMu) + rc = h["electrons"].Fill(nEl) +h["muons"].Draw() # -----Finish------------------------------------------------------- timer.Stop() rtime = timer.RealTime() ctime = timer.CpuTime() -print(' ') +print(" ") print("Macro finished succesfully.") -print("Output file is ", outFile) -print("Real time ",rtime, " s, CPU time ",ctime,"s") +print("Output file is ", outFile) +print("Real time ", rtime, " s, CPU time ", ctime, "s") diff --git a/muonShieldOptimization/study_muEloss.py b/muonShieldOptimization/study_muEloss.py index 602032dfec..399af9342a 100644 --- a/muonShieldOptimization/study_muEloss.py +++ b/muonShieldOptimization/study_muEloss.py @@ -1,271 +1,379 @@ #!/usr/bin/env python -import ROOT,os,sys,time,shipRoot_conf +import os +import sys +import time + +import ROOT +import shipRoot_conf + ROOT.gROOT.ProcessLine('#include "FairModule.h"') time.sleep(20) import shipunit as u from ShipGeoConfig import ConfigRegistry -mcEngine = "TGeant4" -runnr = 1 -nev = 1000000 +mcEngine = "TGeant4" +runnr = 1 +nev = 1000000 setup = {} # -setup['NA62'] = {'thickness': 125*u.cm/2., 'material':'krypton','momentum': 10*u.GeV,'maxTheta':350*u.GeV} # 3000s for 5M +setup["NA62"] = { + "thickness": 125 * u.cm / 2.0, + "material": "krypton", + "momentum": 10 * u.GeV, + "maxTheta": 350 * u.GeV, +} # 3000s for 5M # rad length 4.71cm 125/4.71 = 27 # https://indico.in2p3.fr/event/420/contributions/29860/attachments/24033/29479/moriond.pdf -setup['ATLAS'] = {'thickness': 172*u.cm/2., 'material':'iron','momentum': 350*u.GeV,'maxTheta':350*u.GeV} # 3000s for 5M +setup["ATLAS"] = { + "thickness": 172 * u.cm / 2.0, + "material": "iron", + "momentum": 350 * u.GeV, + "maxTheta": 350 * u.GeV, +} # 3000s for 5M # atlas testbeam http://cds.cern.ch/record/1123152/files/CERN-THESIS-2008-070.pdf?version=1 # LArEM ~24X0 TileCal 4 compartments, same size LiqAr rad length 14cm # http://cds.cern.ch/record/1263861/files/ATL-CAL-PUB-2010-001.pdf tile cal mainly iron, LAr 1.35 DM 0.63 TileCal 8.18 # iron intlen 16.97 -> (1.35 + 0.63 + 8.18)*16.97 -setup['Fig3'] = {'thickness': 0.1*u.cm, 'material':'lead','momentum': 2*u.GeV,'maxTheta':0.2} -setup['Fig4'] = {'thickness': 0.1*u.cm, 'material':'lead','momentum': 8*u.GeV,'maxTheta':0.04} -setup['Fig5'] = {'thickness': 0.1*u.cm, 'material':'lead','momentum': 14*u.GeV,'maxTheta':0.02} +setup["Fig3"] = { + "thickness": 0.1 * u.cm, + "material": "lead", + "momentum": 2 * u.GeV, + "maxTheta": 0.2, +} +setup["Fig4"] = { + "thickness": 0.1 * u.cm, + "material": "lead", + "momentum": 8 * u.GeV, + "maxTheta": 0.04, +} +setup["Fig5"] = { + "thickness": 0.1 * u.cm, + "material": "lead", + "momentum": 14 * u.GeV, + "maxTheta": 0.02, +} -setup['Fig6'] = {'thickness': 1.44*u.cm, 'material':'copper','momentum': 11.7*u.GeV,'maxTheta':0.045} -setup['Fig7'] = {'thickness': 1.44*u.cm, 'material':'copper','momentum': 7.3*u.GeV,'maxTheta':0.045} +setup["Fig6"] = { + "thickness": 1.44 * u.cm, + "material": "copper", + "momentum": 11.7 * u.GeV, + "maxTheta": 0.045, +} +setup["Fig7"] = { + "thickness": 1.44 * u.cm, + "material": "copper", + "momentum": 7.3 * u.GeV, + "maxTheta": 0.045, +} s = sys.argv[1] -thickness = setup[s]['thickness'] -material = setup[s]['material'] -momentum = setup[s]['momentum'] -maxTheta = setup[s]['maxTheta'] +thickness = setup[s]["thickness"] +material = setup[s]["material"] +momentum = setup[s]["momentum"] +maxTheta = setup[s]["maxTheta"] checkOverlap = True storeOnlyMuons = True -outFile = "msc"+s+".root" -theSeed = 0 -ecut = 0.0 +outFile = "msc" + s + ".root" +theSeed = 0 +ecut = 0.0 import rootUtils as ut -h={} + +h = {} + def run(): -# ------------------------------------------------------------------- - ROOT.gRandom.SetSeed(theSeed) # this should be propagated via ROOT to Pythia8 and Geant4VMC - shipRoot_conf.configure() # load basic libraries, prepare atexit for python - # ship_geo = ConfigRegistry.loadpy("$FAIRSHIP/geometry/geometry_config.py", Yheight = 10, tankDesign = 5, muShieldDesign = 7, nuTauTargetDesign=1) -# -----Timer-------------------------------------------------------- - timer = ROOT.TStopwatch() - timer.Start() -# -----Create simulation run---------------------------------------- - gFairBaseContFact = ROOT.FairBaseContFact() # required by change to FairBaseContFact to avoid TList::Clear errors - run = ROOT.FairRunSim() - run.SetName(mcEngine) # Transport engine - if nev==0: run.SetOutputFile("dummy.root") - else: run.SetOutputFile(outFile) # Output file - run.SetUserConfig("g4Config.C") # user configuration file default g4Config.C - rtdb = run.GetRuntimeDb() -# -----Materials---------------------------------------------- - run.SetMaterials("media.geo") -# -----Create geometry---------------------------------------------- - cave= ROOT.ShipCave("CAVE") - cave.SetGeometryFileName("cave.geo") - run.AddModule(cave) -# - target = ROOT.simpleTarget() - material, thickness, 0 -# - target.SetEnergyCut(ecut*u.GeV) - if storeOnlyMuons: target.SetOnlyMuons() - target.SetParameters(material,thickness,0.) - run.AddModule(target) -# - primGen = ROOT.FairPrimaryGenerator() - myPgun = ROOT.FairBoxGenerator(13,1) # pdg id and multiplicity - if s=="NA62": myPgun.SetPRange(momentum,maxTheta) - else: myPgun.SetPRange(momentum-0.01,momentum+0.01) - myPgun.SetPhiRange(0,0) # // Azimuth angle range [degree] - myPgun.SetThetaRange(0,0) # // Polar angle in lab system range [degree] - myPgun.SetXYZ(0.*u.cm, 0.*u.cm, -1.*u.mm - (thickness) ) - primGen.AddGenerator(myPgun) -# - run.SetGenerator(primGen) -# -----Initialize simulation run------------------------------------ - run.Init() - if nev==0: return - gMC = ROOT.TVirtualMC.GetMC() + # ------------------------------------------------------------------- + ROOT.gRandom.SetSeed( + theSeed + ) # this should be propagated via ROOT to Pythia8 and Geant4VMC + shipRoot_conf.configure() # load basic libraries, prepare atexit for python + # ship_geo = ConfigRegistry.loadpy("$FAIRSHIP/geometry/geometry_config.py", Yheight = 10, tankDesign = 5, muShieldDesign = 7, nuTauTargetDesign=1) + # -----Timer-------------------------------------------------------- + timer = ROOT.TStopwatch() + timer.Start() + # -----Create simulation run---------------------------------------- + gFairBaseContFact = ( + ROOT.FairBaseContFact() + ) # required by change to FairBaseContFact to avoid TList::Clear errors + run = ROOT.FairRunSim() + run.SetName(mcEngine) # Transport engine + if nev == 0: + run.SetOutputFile("dummy.root") + else: + run.SetOutputFile(outFile) # Output file + run.SetUserConfig("g4Config.C") # user configuration file default g4Config.C + rtdb = run.GetRuntimeDb() + # -----Materials---------------------------------------------- + run.SetMaterials("media.geo") + # -----Create geometry---------------------------------------------- + cave = ROOT.ShipCave("CAVE") + cave.SetGeometryFileName("cave.geo") + run.AddModule(cave) + # + target = ROOT.simpleTarget() + material, thickness, 0 + # + target.SetEnergyCut(ecut * u.GeV) + if storeOnlyMuons: + target.SetOnlyMuons() + target.SetParameters(material, thickness, 0.0) + run.AddModule(target) + # + primGen = ROOT.FairPrimaryGenerator() + myPgun = ROOT.FairBoxGenerator(13, 1) # pdg id and multiplicity + if s == "NA62": + myPgun.SetPRange(momentum, maxTheta) + else: + myPgun.SetPRange(momentum - 0.01, momentum + 0.01) + myPgun.SetPhiRange(0, 0) # // Azimuth angle range [degree] + myPgun.SetThetaRange(0, 0) # // Polar angle in lab system range [degree] + myPgun.SetXYZ(0.0 * u.cm, 0.0 * u.cm, -1.0 * u.mm - (thickness)) + primGen.AddGenerator(myPgun) + # + run.SetGenerator(primGen) + # -----Initialize simulation run------------------------------------ + run.Init() + if nev == 0: + return + gMC = ROOT.TVirtualMC.GetMC() + + fStack = gMC.GetStack() + fStack.SetMinPoints(1) + fStack.SetEnergyCut(-1.0) - fStack = gMC.GetStack() - fStack.SetMinPoints(1) - fStack.SetEnergyCut(-1.) + # -----Start run---------------------------------------------------- + print("run for ", nev, "events") + run.Run(nev) -# -----Start run---------------------------------------------------- - print("run for ",nev,"events") - run.Run(nev) + # -----Start Analysis--------------- + ROOT.gROOT.ProcessLine('#include "Geant4/G4EmParameters.hh"') + emP = ROOT.G4EmParameters.Instance() + emP.Dump() + h["f"] = ROOT.gROOT.GetListOfFiles()[0].GetName() + # -----Finish------------------------------------------------------- + timer.Stop() + rtime = timer.RealTime() + ctime = timer.CpuTime() + print(" ") + print("Macro finished succesfully.") + print("Output file is ", outFile) + print("Real time ", rtime, " s, CPU time ", ctime, "s") -# -----Start Analysis--------------- - ROOT.gROOT.ProcessLine('#include "Geant4/G4EmParameters.hh"') - emP = ROOT.G4EmParameters.Instance() - emP.Dump() - h['f']= ROOT.gROOT.GetListOfFiles()[0].GetName() -# -----Finish------------------------------------------------------- - timer.Stop() - rtime = timer.RealTime() - ctime = timer.CpuTime() - print(' ') - print("Macro finished succesfully.") - print("Output file is ", outFile) - print("Real time ",rtime, " s, CPU time ",ctime,"s") -def makePlot(f,book=True): -# print interaction and radiation length of target - sGeo=ROOT.gGeoManager - if sGeo: - v = sGeo.FindVolumeFast('target') - m = v.GetMaterial() - length = v.GetShape().GetDZ()*2 - print("Material:",m.GetName(),'total interaction length=',length/m.GetIntLen(),'total rad length=',length/m.GetRadLen()) - else: - density= 2.413 - length= 125.0 - print("Use predefined values:",density,length) - if book: - ut.bookHist(h,'theta','scattering angle '+str(momentum)+'GeV/c;{Theta}(rad)',500,0,maxTheta) - ut.bookHist(h,'eloss','rel energy loss as function of momentum GeV/c',100,0,maxTheta,10000,0.,1.) - ut.bookHist(h,'elossRaw','energy loss as function of momentum GeV/c',100,0,maxTheta, 10000,0.,100.) - sTree = f.cbmsim - for n in range(sTree.GetEntries()): - rc = sTree.GetEvent(n) - Ein = sTree.MCTrack[0].GetEnergy() - M = sTree.MCTrack[0].GetMass() - Eloss = 0 - for aHit in sTree.vetoPoint: - Eloss+=aHit.GetEnergyLoss() - print(Ein,Eloss/Ein) - rc = h['eloss'].Fill(Ein,Eloss/Ein) - rc = h['elossRaw'].Fill(Ein,Eloss) - ut.bookCanvas(h,key=s,title=s,nx=900,ny=600,cx=1,cy=1) - tc = h[s].cd(1) - if s=="NA62": - h['eloss'].Draw() - h['95'] = h['eloss'].ProjectionX('95',96,100) - h['95'].Sumw2() - h['0'] = h['eloss'].ProjectionX('0',1,100) - h['0'].Sumw2() - rc = h['95'].Divide(h['0'] ) - h['95'].Draw() - h['meanEloss'] = h['elossRaw'].ProjectionX() - for n in range(1,h['elossRaw'].GetNbinsX()+1): - tmp = h['elossRaw'].ProjectionY('tmp',n,n) - eloss = tmp.GetMean() - h['meanEloss'].SetBinContent(n,eloss/density/length*1000) - h['meanEloss'].SetTitle('mean energy loss MeV cm2 / g') - h['meanEloss'].Draw() - elif s=="ATLAS": - h['eloss'].Draw() - h['>eloss']=h['eloss'].ProjectionY().Clone('>eloss') - cum = 0 - N = float(h['>eloss'].GetEntries()) - for n in range(h['>eloss'].GetNbinsX(),0,-1): - cum+=h['>eloss'].GetBinContent(n) - h['>eloss'].SetBinContent(n,cum/N) - print("Ethreshold event fraction in %") - for E in [15.,20.,30.,50.,80.]: - n = h['>eloss'].FindBin(E/350.) - print(" %5.0F %5.2F "%(E,h['>eloss'].GetBinContent(n)*100)) - else: - tc.SetLogy(1) - h['theta_100']=h['theta'].Clone('theta_100') - h['theta_100']=h['theta'].Rebin(5) - h['theta_100'].Scale(1./h['theta_100'].GetMaximum()) - h['theta_100'].Draw() - h[s].Print(s+'.png') - h[s].Print(s+'.root') - f.Write(h['theta'].GetName()) - f.Write(h['theta_100'].GetName()) +def makePlot(f, book=True): + # print interaction and radiation length of target + sGeo = ROOT.gGeoManager + if sGeo: + v = sGeo.FindVolumeFast("target") + m = v.GetMaterial() + length = v.GetShape().GetDZ() * 2 + print( + "Material:", + m.GetName(), + "total interaction length=", + length / m.GetIntLen(), + "total rad length=", + length / m.GetRadLen(), + ) + else: + density = 2.413 + length = 125.0 + print("Use predefined values:", density, length) + if book: + ut.bookHist( + h, + "theta", + "scattering angle " + str(momentum) + "GeV/c;{Theta}(rad)", + 500, + 0, + maxTheta, + ) + ut.bookHist( + h, + "eloss", + "rel energy loss as function of momentum GeV/c", + 100, + 0, + maxTheta, + 10000, + 0.0, + 1.0, + ) + ut.bookHist( + h, + "elossRaw", + "energy loss as function of momentum GeV/c", + 100, + 0, + maxTheta, + 10000, + 0.0, + 100.0, + ) + sTree = f.cbmsim + for n in range(sTree.GetEntries()): + rc = sTree.GetEvent(n) + Ein = sTree.MCTrack[0].GetEnergy() + M = sTree.MCTrack[0].GetMass() + Eloss = 0 + for aHit in sTree.vetoPoint: + Eloss += aHit.GetEnergyLoss() + print(Ein, Eloss / Ein) + rc = h["eloss"].Fill(Ein, Eloss / Ein) + rc = h["elossRaw"].Fill(Ein, Eloss) + ut.bookCanvas(h, key=s, title=s, nx=900, ny=600, cx=1, cy=1) + tc = h[s].cd(1) + if s == "NA62": + h["eloss"].Draw() + h["95"] = h["eloss"].ProjectionX("95", 96, 100) + h["95"].Sumw2() + h["0"] = h["eloss"].ProjectionX("0", 1, 100) + h["0"].Sumw2() + rc = h["95"].Divide(h["0"]) + h["95"].Draw() + h["meanEloss"] = h["elossRaw"].ProjectionX() + for n in range(1, h["elossRaw"].GetNbinsX() + 1): + tmp = h["elossRaw"].ProjectionY("tmp", n, n) + eloss = tmp.GetMean() + h["meanEloss"].SetBinContent(n, eloss / density / length * 1000) + h["meanEloss"].SetTitle("mean energy loss MeV cm2 / g") + h["meanEloss"].Draw() + elif s == "ATLAS": + h["eloss"].Draw() + h[">eloss"] = h["eloss"].ProjectionY().Clone(">eloss") + cum = 0 + N = float(h[">eloss"].GetEntries()) + for n in range(h[">eloss"].GetNbinsX(), 0, -1): + cum += h[">eloss"].GetBinContent(n) + h[">eloss"].SetBinContent(n, cum / N) + print("Ethreshold event fraction in %") + for E in [15.0, 20.0, 30.0, 50.0, 80.0]: + n = h[">eloss"].FindBin(E / 350.0) + print(" %5.0F %5.2F " % (E, h[">eloss"].GetBinContent(n) * 100)) + else: + tc.SetLogy(1) + h["theta_100"] = h["theta"].Clone("theta_100") + h["theta_100"] = h["theta"].Rebin(5) + h["theta_100"].Scale(1.0 / h["theta_100"].GetMaximum()) + h["theta_100"].Draw() + h[s].Print(s + ".png") + h[s].Print(s + ".root") + f.Write(h["theta"].GetName()) + f.Write(h["theta_100"].GetName()) + def readChain(): - tmp = "/mnt/hgfs/microDisk/Data/mscNA62_X.root" - for i in [0,1]: - f = ROOT.TFile(tmp.replace('X',str(i))) - if i==1: makePlot(f,False) - else: makePlot(f) + tmp = "/mnt/hgfs/microDisk/Data/mscNA62_X.root" + for i in [0, 1]: + f = ROOT.TFile(tmp.replace("X", str(i))) + if i == 1: + makePlot(f, False) + else: + makePlot(f) + def NA62(): - na62Points = open('NA62.points') - allPoints = na62Points.readlines() - N = int((len(allPoints)-1)/3.) - h['NA62']=ROOT.TGraphErrors(N) - for l in range(N): - tmp = allPoints[3*l].split(',') - x=float(tmp[0]) - y=float(tmp[1].replace('\n','')) - tmp = allPoints[3*l+1].split(',') - y1=float(tmp[1].replace('\n','')) - tmp = allPoints[3*l+2].split(',') - y2=float(tmp[1].replace('\n','')) - h['NA62'].SetPoint(l,x,y*1E-6) - h['NA62'].SetPointError(l,0,abs(y1-y2)/2.*1E-6) - h['NA62'].SetLineColor(ROOT.kRed) - h['NA62'].SetMarkerColor(ROOT.kRed) - h['NA62'].SetMarkerStyle(20) + na62Points = open("NA62.points") + allPoints = na62Points.readlines() + N = int((len(allPoints) - 1) / 3.0) + h["NA62"] = ROOT.TGraphErrors(N) + for l in range(N): + tmp = allPoints[3 * l].split(",") + x = float(tmp[0]) + y = float(tmp[1].replace("\n", "")) + tmp = allPoints[3 * l + 1].split(",") + y1 = float(tmp[1].replace("\n", "")) + tmp = allPoints[3 * l + 2].split(",") + y2 = float(tmp[1].replace("\n", "")) + h["NA62"].SetPoint(l, x, y * 1e-6) + h["NA62"].SetPointError(l, 0, abs(y1 - y2) / 2.0 * 1e-6) + h["NA62"].SetLineColor(ROOT.kRed) + h["NA62"].SetMarkerColor(ROOT.kRed) + h["NA62"].SetMarkerStyle(20) + def makeSummaryPlot(): -# using data in /mnt/hgfs/microDisk/Data/eloss/eloss_sum.root -# krypton total interaction length= 1.97246306079 total rad length= 26.5231000393 - pdg={10.0:1.914,14.0:1.978,20.0:2.055,30.0:2.164,40.0:2.263,80.0:2.630,100.:2.810,140.:3.170,200.:3.720,277.:4.420,300.:4.631,400.:5.561} - h['Gpdg'] = ROOT.TGraph(len(pdg)) - Gpdg = h['Gpdg'] - Gpdg.SetMarkerColor(ROOT.kRed) - Gpdg.SetMarkerStyle(20) - keys = sorted(pdg.keys()) - for n in range(len(keys)): - Gpdg.SetPoint(n,keys[n],pdg[keys[n]]) - density= 2.413 - length= 125.0 - ut.readHists(h,"/mnt/hgfs/microDisk/Data/eloss/eloss_sum.root") - ut.readHists(h,"/mnt/hgfs/microDisk/Data/eloss/eloss_withRaw.root") - ut.bookCanvas(h,key='summary',title=" ",nx=1200,ny=600,cx=2,cy=1) - tc = h['summary'].cd(1) - h['0'] = h['eloss'].ProjectionX('0',1,h['eloss'].GetNbinsY()) - h['0'].Sumw2() - NA62() - for t in [93,95]: - h[t] = h['eloss'].ProjectionX(str(t),int(h['eloss'].GetNbinsY()*t/100.),h['eloss'].GetNbinsY()) - h[t].Sumw2() - h[t].SetStats(0) - h[t].SetMarkerStyle(24) - rc = h[t].Divide(h['0'] ) - h[t].Rebin(2) - h[t].Scale(1./2.) - if t!=93: - h[t].SetMarkerColor(ROOT.kBlue) - h[t].Draw('same') - else: - h[t].SetMaximum(1E-5) - h[t].SetMarkerColor(ROOT.kMagenta) - h[t].SetXTitle('incoming muon momentum [GeV/c]') - h[t].SetYTitle('prob #DeltaE>X%') - h[t].SetTitle('') - h[t].Draw() - h['NA62'].Draw('sameP') - h['lg'] = ROOT.TLegend(0.53,0.79,0.98,0.94) - h['lg'].AddEntry(h['NA62'],'NA62 measurement >95%','PL') - h['lg'].AddEntry(h[95],'FairShip >95%','PL') - h['lg'].AddEntry(h[93],'FairShip >93%','PL') - h['lg'].Draw() - tc = h['summary'].cd(2) - h['meanEloss'] = h['elossRaw'].ProjectionX() - for n in range(1,h['elossRaw'].GetNbinsX()+1): - tmp = h['elossRaw'].ProjectionY('tmp',n,n) - eloss = tmp.GetMean() - h['meanEloss'].SetBinContent(n,eloss/density/length*1000) - h['meanEloss'].SetBinError(n,0) - h['meanEloss'].SetTitle('mean energy loss MeV cm^{2}/g') - h['meanEloss'].SetStats(0) - h['meanEloss'].SetMaximum(7.) - h['meanEloss'].SetXTitle('incoming muon momentum [GeV/c]') - h['meanEloss'].SetYTitle('mean energy loss [MeV cm^[2]]/g') - h['meanEloss'].SetTitle('') - h['meanEloss'].Draw() - Gpdg.Draw('sameP') - h['lg2'] = ROOT.TLegend(0.53,0.79,0.98,0.94) - h['lg2'].AddEntry(h['Gpdg'],'muon dE/dx, PDG ','PL') - h['lg2'].AddEntry(h['meanEloss'],'energy deposited in krypton, FairShip','PL') - h['lg2'].Draw() - h['summary'].Print('catastrophicEnergyLoss.png') + # using data in /mnt/hgfs/microDisk/Data/eloss/eloss_sum.root + # krypton total interaction length= 1.97246306079 total rad length= 26.5231000393 + pdg = { + 10.0: 1.914, + 14.0: 1.978, + 20.0: 2.055, + 30.0: 2.164, + 40.0: 2.263, + 80.0: 2.630, + 100.0: 2.810, + 140.0: 3.170, + 200.0: 3.720, + 277.0: 4.420, + 300.0: 4.631, + 400.0: 5.561, + } + h["Gpdg"] = ROOT.TGraph(len(pdg)) + Gpdg = h["Gpdg"] + Gpdg.SetMarkerColor(ROOT.kRed) + Gpdg.SetMarkerStyle(20) + keys = sorted(pdg.keys()) + for n in range(len(keys)): + Gpdg.SetPoint(n, keys[n], pdg[keys[n]]) + density = 2.413 + length = 125.0 + ut.readHists(h, "/mnt/hgfs/microDisk/Data/eloss/eloss_sum.root") + ut.readHists(h, "/mnt/hgfs/microDisk/Data/eloss/eloss_withRaw.root") + ut.bookCanvas(h, key="summary", title=" ", nx=1200, ny=600, cx=2, cy=1) + tc = h["summary"].cd(1) + h["0"] = h["eloss"].ProjectionX("0", 1, h["eloss"].GetNbinsY()) + h["0"].Sumw2() + NA62() + for t in [93, 95]: + h[t] = h["eloss"].ProjectionX( + str(t), int(h["eloss"].GetNbinsY() * t / 100.0), h["eloss"].GetNbinsY() + ) + h[t].Sumw2() + h[t].SetStats(0) + h[t].SetMarkerStyle(24) + rc = h[t].Divide(h["0"]) + h[t].Rebin(2) + h[t].Scale(1.0 / 2.0) + if t != 93: + h[t].SetMarkerColor(ROOT.kBlue) + h[t].Draw("same") + else: + h[t].SetMaximum(1e-5) + h[t].SetMarkerColor(ROOT.kMagenta) + h[t].SetXTitle("incoming muon momentum [GeV/c]") + h[t].SetYTitle("prob #DeltaE>X%") + h[t].SetTitle("") + h[t].Draw() + h["NA62"].Draw("sameP") + h["lg"] = ROOT.TLegend(0.53, 0.79, 0.98, 0.94) + h["lg"].AddEntry(h["NA62"], "NA62 measurement >95%", "PL") + h["lg"].AddEntry(h[95], "FairShip >95%", "PL") + h["lg"].AddEntry(h[93], "FairShip >93%", "PL") + h["lg"].Draw() + tc = h["summary"].cd(2) + h["meanEloss"] = h["elossRaw"].ProjectionX() + for n in range(1, h["elossRaw"].GetNbinsX() + 1): + tmp = h["elossRaw"].ProjectionY("tmp", n, n) + eloss = tmp.GetMean() + h["meanEloss"].SetBinContent(n, eloss / density / length * 1000) + h["meanEloss"].SetBinError(n, 0) + h["meanEloss"].SetTitle("mean energy loss MeV cm^{2}/g") + h["meanEloss"].SetStats(0) + h["meanEloss"].SetMaximum(7.0) + h["meanEloss"].SetXTitle("incoming muon momentum [GeV/c]") + h["meanEloss"].SetYTitle("mean energy loss [MeV cm^[2]]/g") + h["meanEloss"].SetTitle("") + h["meanEloss"].Draw() + Gpdg.Draw("sameP") + h["lg2"] = ROOT.TLegend(0.53, 0.79, 0.98, 0.94) + h["lg2"].AddEntry(h["Gpdg"], "muon dE/dx, PDG ", "PL") + h["lg2"].AddEntry(h["meanEloss"], "energy deposited in krypton, FairShip", "PL") + h["lg2"].Draw() + h["summary"].Print("catastrophicEnergyLoss.png") diff --git a/muonShieldOptimization/study_muMSC.py b/muonShieldOptimization/study_muMSC.py index 6ae887d9e7..c61a755ffa 100644 --- a/muonShieldOptimization/study_muMSC.py +++ b/muonShieldOptimization/study_muMSC.py @@ -1,40 +1,79 @@ #!/usr/bin/env python -import ROOT,os,sys,time,shipRoot_conf +import os +import sys +import time + +import ROOT +import shipRoot_conf + ROOT.gROOT.ProcessLine('#include "FairModule.h"') time.sleep(20) import shipunit as u from ShipGeoConfig import ConfigRegistry -mcEngine = "TGeant4" -runnr = 1 -nev = 10000000 +mcEngine = "TGeant4" +runnr = 1 +nev = 10000000 setup = {} -setup['Fig3'] = {'thickness': 0.1*u.cm, 'material':'lead','momentum': 2*u.GeV,'maxTheta':0.2} -setup['Fig4'] = {'thickness': 0.1*u.cm, 'material':'lead','momentum': 8*u.GeV,'maxTheta':0.04} -setup['Fig5'] = {'thickness': 0.1*u.cm, 'material':'lead','momentum': 14*u.GeV,'maxTheta':0.02} - -setup['Fig6'] = {'thickness': 1.44*u.cm, 'material':'copper','momentum': 11.7*u.GeV,'maxTheta':0.045} -setup['Fig7'] = {'thickness': 1.44*u.cm, 'material':'copper','momentum': 7.3*u.GeV,'maxTheta':0.045} +setup["Fig3"] = { + "thickness": 0.1 * u.cm, + "material": "lead", + "momentum": 2 * u.GeV, + "maxTheta": 0.2, +} +setup["Fig4"] = { + "thickness": 0.1 * u.cm, + "material": "lead", + "momentum": 8 * u.GeV, + "maxTheta": 0.04, +} +setup["Fig5"] = { + "thickness": 0.1 * u.cm, + "material": "lead", + "momentum": 14 * u.GeV, + "maxTheta": 0.02, +} + +setup["Fig6"] = { + "thickness": 1.44 * u.cm, + "material": "copper", + "momentum": 11.7 * u.GeV, + "maxTheta": 0.045, +} +setup["Fig7"] = { + "thickness": 1.44 * u.cm, + "material": "copper", + "momentum": 7.3 * u.GeV, + "maxTheta": 0.045, +} s = sys.argv[1] -thickness = setup[s]['thickness'] -material = setup[s]['material'] -momentum = setup[s]['momentum'] -maxTheta = setup[s]['maxTheta'] +thickness = setup[s]["thickness"] +material = setup[s]["material"] +momentum = setup[s]["momentum"] +maxTheta = setup[s]["maxTheta"] checkOverlap = True storeOnlyMuons = True -outFile = "msc"+s+".root" -theSeed = int(10000 * time.time() % 10000000) -ecut = 0.0 +outFile = "msc" + s + ".root" +theSeed = int(10000 * time.time() % 10000000) +ecut = 0.0 # ------------------------------------------------------------------- -ROOT.gRandom.SetSeed(theSeed) # this should be propagated via ROOT to Pythia8 and Geant4VMC -shipRoot_conf.configure() # load basic libraries, prepare atexit for python -ship_geo = ConfigRegistry.loadpy("$FAIRSHIP/geometry/geometry_config.py", Yheight = 10, tankDesign = 5, muShieldDesign = 7, nuTauTargetDesign=1) +ROOT.gRandom.SetSeed( + theSeed +) # this should be propagated via ROOT to Pythia8 and Geant4VMC +shipRoot_conf.configure() # load basic libraries, prepare atexit for python +ship_geo = ConfigRegistry.loadpy( + "$FAIRSHIP/geometry/geometry_config.py", + Yheight=10, + tankDesign=5, + muShieldDesign=7, + nuTauTargetDesign=1, +) # -----Timer-------------------------------------------------------- timer = ROOT.TStopwatch() @@ -44,50 +83,59 @@ run = ROOT.FairRunSim() run.SetName(mcEngine) # Transport engine run.SetOutputFile(outFile) # Output file -run.SetUserConfig("g4Config.C") # user configuration file default g4Config.C +run.SetUserConfig("g4Config.C") # user configuration file default g4Config.C rtdb = run.GetRuntimeDb() # -----Materials---------------------------------------------- run.SetMaterials("media.geo") # -----Create geometry---------------------------------------------- -cave= ROOT.ShipCave("CAVE") +cave = ROOT.ShipCave("CAVE") cave.SetGeometryFileName("cave.geo") run.AddModule(cave) + class Block(ROOT.pyFairModule): - "block of material" - def __init__(self): ROOT.pyFairModule.__init__(self,self) - def ConstructGeometry(self): - print("Construct Block") - top=ROOT.gGeoManager.GetTopVolume() - geoLoad=ROOT.FairGeoLoader.Instance() - geoFace=geoLoad.getGeoInterface() - media=geoFace.getMedia() - geoBuild=geoLoad.getGeoBuilder() - ShipMedium=media.getMedium(material) - W = ROOT.gGeoManager.GetMedium(material) - if not W: - rc = geoBuild.createMedium(ShipMedium) + "block of material" + + def __init__(self): + ROOT.pyFairModule.__init__(self, self) + + def ConstructGeometry(self): + print("Construct Block") + top = ROOT.gGeoManager.GetTopVolume() + geoLoad = ROOT.FairGeoLoader.Instance() + geoFace = geoLoad.getGeoInterface() + media = geoFace.getMedia() + geoBuild = geoLoad.getGeoBuilder() + ShipMedium = media.getMedium(material) W = ROOT.gGeoManager.GetMedium(material) - aBox = ROOT.gGeoManager.MakeBox("target", W, 100.*u.cm, 100.*u.cm, thickness) - top.AddNode(aBox, 1, ROOT.TGeoTranslation(0, 0, 0 )) - def InitParContainers(): - print("not implemented!") + if not W: + rc = geoBuild.createMedium(ShipMedium) + W = ROOT.gGeoManager.GetMedium(material) + aBox = ROOT.gGeoManager.MakeBox( + "target", W, 100.0 * u.cm, 100.0 * u.cm, thickness + ) + top.AddNode(aBox, 1, ROOT.TGeoTranslation(0, 0, 0)) + + def InitParContainers(): + print("not implemented!") + sensPlane = ROOT.exitHadronAbsorber() -sensPlane.SetEnergyCut(ecut*u.GeV) -if storeOnlyMuons: sensPlane.SetOnlyMuons() -sensPlane.SetZposition(thickness+10*u.cm) +sensPlane.SetEnergyCut(ecut * u.GeV) +if storeOnlyMuons: + sensPlane.SetOnlyMuons() +sensPlane.SetZposition(thickness + 10 * u.cm) run.AddModule(sensPlane) target = Block() run.AddModule(target) primGen = ROOT.FairPrimaryGenerator() -myPgun = ROOT.FairBoxGenerator(13,1) # pdg id and multiplicity -myPgun.SetPRange(momentum-0.01,momentum+0.01) -myPgun.SetPhiRange(0,0) # // Azimuth angle range [degree] -myPgun.SetThetaRange(0,0) # // Polar angle in lab system range [degree] -myPgun.SetXYZ(0.*u.cm, 0.*u.cm, -10.*u.cm - (thickness) ) +myPgun = ROOT.FairBoxGenerator(13, 1) # pdg id and multiplicity +myPgun.SetPRange(momentum - 0.01, momentum + 0.01) +myPgun.SetPhiRange(0, 0) # // Azimuth angle range [degree] +myPgun.SetThetaRange(0, 0) # // Polar angle in lab system range [degree] +myPgun.SetXYZ(0.0 * u.cm, 0.0 * u.cm, -10.0 * u.cm - (thickness)) primGen.AddGenerator(myPgun) run.SetGenerator(primGen) # @@ -98,7 +146,7 @@ def InitParContainers(): fStack = gMC.GetStack() fStack.SetMinPoints(1) -fStack.SetEnergyCut(-1.) +fStack.SetEnergyCut(-1.0) # -----Start run---------------------------------------------------- run.Run(nev) @@ -110,35 +158,43 @@ def InitParContainers(): import rootUtils as ut -f=ROOT.gROOT.GetListOfFiles()[0] -h={} -ut.bookHist(h,'theta','scattering angle '+str(momentum)+'GeV/c;{Theta}(rad)',500,0,maxTheta) +f = ROOT.gROOT.GetListOfFiles()[0] +h = {} +ut.bookHist( + h, + "theta", + "scattering angle " + str(momentum) + "GeV/c;{Theta}(rad)", + 500, + 0, + maxTheta, +) sTree = f.cbmsim for n in range(sTree.GetEntries()): - rc = sTree.GetEvent(n) - for aHit in sTree.vetoPoint: - if not aHit.GetTrackID()==0: continue - pt = ROOT.TMath.Sqrt(aHit.GetPx()**2+aHit.GetPy()**2) - scat = ROOT.TMath.ATan2(pt,aHit.GetPz()) - rc = h['theta'].Fill(scat) -ut.bookCanvas(h,key=s,title=s,nx=900,ny=600,cx=1,cy=1) + rc = sTree.GetEvent(n) + for aHit in sTree.vetoPoint: + if not aHit.GetTrackID() == 0: + continue + pt = ROOT.TMath.Sqrt(aHit.GetPx() ** 2 + aHit.GetPy() ** 2) + scat = ROOT.TMath.ATan2(pt, aHit.GetPz()) + rc = h["theta"].Fill(scat) +ut.bookCanvas(h, key=s, title=s, nx=900, ny=600, cx=1, cy=1) tc = h[s].cd(1) tc.SetLogy(1) -h['theta_100']=h['theta'].Clone('theta_100') -h['theta_100']=h['theta'].Rebin(5) -h['theta_100'].Scale(1./h['theta_100'].GetMaximum()) -h['theta_100'].Draw() -h[s].Print(s+'.png') -h[s].Print(s+'.root') +h["theta_100"] = h["theta"].Clone("theta_100") +h["theta_100"] = h["theta"].Rebin(5) +h["theta_100"].Scale(1.0 / h["theta_100"].GetMaximum()) +h["theta_100"].Draw() +h[s].Print(s + ".png") +h[s].Print(s + ".root") -f.Write(h['theta'].GetName()) -f.Write(h['theta_100'].GetName()) +f.Write(h["theta"].GetName()) +f.Write(h["theta_100"].GetName()) # -----Finish------------------------------------------------------- timer.Stop() rtime = timer.RealTime() ctime = timer.CpuTime() -print(' ') +print(" ") print("Macro finished succesfully.") -print("Output file is ", outFile) -print("Real time ",rtime, " s, CPU time ",ctime,"s") +print("Output file is ", outFile) +print("Real time ", rtime, " s, CPU time ", ctime, "s") diff --git a/muonShieldOptimization/study_thinTarget.py b/muonShieldOptimization/study_thinTarget.py index 66d9229fe3..a3c7f88b28 100644 --- a/muonShieldOptimization/study_thinTarget.py +++ b/muonShieldOptimization/study_thinTarget.py @@ -1,88 +1,116 @@ #!/usr/bin/env python -import ROOT,os,sys,time,shipRoot_conf +import os +import sys +import time + +import ROOT +import shipRoot_conf + ROOT.gROOT.ProcessLine('#include "FairModule.h"') time.sleep(20) import shipunit as u from ShipGeoConfig import ConfigRegistry -mcEngine = "TGeant4" -runnr = 1 -nev = 1000000 +mcEngine = "TGeant4" +runnr = 1 +nev = 1000000 setup = {} -setup['TLV'] = {'thickness': 0.1*u.cm, 'material':'tungsten','min momentum': 400*u.GeV,'max momentum': 400*u.GeV} - -s = 'TLV' -thickness = setup[s]['thickness'] -material = setup[s]['material'] -minmomentum = setup[s]['min momentum'] -maxmomentum = setup[s]['max momentum'] +setup["TLV"] = { + "thickness": 0.1 * u.cm, + "material": "tungsten", + "min momentum": 400 * u.GeV, + "max momentum": 400 * u.GeV, +} + +s = "TLV" +thickness = setup[s]["thickness"] +material = setup[s]["material"] +minmomentum = setup[s]["min momentum"] +maxmomentum = setup[s]["max momentum"] checkOverlap = True outFile = "TLV.root" -theSeed = 0 -ecut = 0.0 +theSeed = 0 +ecut = 0.0 # ------------------------------------------------------------------- -ROOT.gRandom.SetSeed(theSeed) # this should be propagated via ROOT to Pythia8 and Geant4VMC -shipRoot_conf.configure() # load basic libraries, prepare atexit for python -ship_geo = ConfigRegistry.loadpy("$FAIRSHIP/geometry/geometry_config.py", Yheight = 10, tankDesign = 5, muShieldDesign = 7, nuTauTargetDesign=1) +ROOT.gRandom.SetSeed( + theSeed +) # this should be propagated via ROOT to Pythia8 and Geant4VMC +shipRoot_conf.configure() # load basic libraries, prepare atexit for python +ship_geo = ConfigRegistry.loadpy( + "$FAIRSHIP/geometry/geometry_config.py", + Yheight=10, + tankDesign=5, + muShieldDesign=7, + nuTauTargetDesign=1, +) # -----Timer-------------------------------------------------------- timer = ROOT.TStopwatch() timer.Start() # -----Create simulation run---------------------------------------- -gFairBaseContFact = ROOT.FairBaseContFact() # required by change to FairBaseContFact to avoid TList::Clear errors +gFairBaseContFact = ( + ROOT.FairBaseContFact() +) # required by change to FairBaseContFact to avoid TList::Clear errors run = ROOT.FairRunSim() run.SetName(mcEngine) # Transport engine run.SetOutputFile(outFile) # Output file -run.SetUserConfig("g4Config.C") # user configuration file default g4Config.C +run.SetUserConfig("g4Config.C") # user configuration file default g4Config.C rtdb = run.GetRuntimeDb() # -----Materials---------------------------------------------- run.SetMaterials("media.geo") # -----Create geometry---------------------------------------------- -cave= ROOT.ShipCave("CAVE") +cave = ROOT.ShipCave("CAVE") cave.SetGeometryFileName("cave.geo") run.AddModule(cave) class Block(ROOT.pyFairModule): - "block of material" - def __init__(self): ROOT.pyFairModule.__init__(self,self) - def ConstructGeometry(self): - print("Construct Block") - top=ROOT.gGeoManager.GetTopVolume() - geoLoad=ROOT.FairGeoLoader.Instance() - geoFace=geoLoad.getGeoInterface() - media=geoFace.getMedia() - geoBuild=geoLoad.getGeoBuilder() - ShipMedium=media.getMedium(material) - W = ROOT.gGeoManager.GetMedium(material) - if not W: - rc = geoBuild.createMedium(ShipMedium) + "block of material" + + def __init__(self): + ROOT.pyFairModule.__init__(self, self) + + def ConstructGeometry(self): + print("Construct Block") + top = ROOT.gGeoManager.GetTopVolume() + geoLoad = ROOT.FairGeoLoader.Instance() + geoFace = geoLoad.getGeoInterface() + media = geoFace.getMedia() + geoBuild = geoLoad.getGeoBuilder() + ShipMedium = media.getMedium(material) W = ROOT.gGeoManager.GetMedium(material) - aBox = ROOT.gGeoManager.MakeBox("target", W, 100.*u.cm, 100.*u.cm, thickness) - top.AddNode(aBox, 1, ROOT.TGeoTranslation(0, 0, 0 )) - def InitParContainers(): - print("not implemented!") + if not W: + rc = geoBuild.createMedium(ShipMedium) + W = ROOT.gGeoManager.GetMedium(material) + aBox = ROOT.gGeoManager.MakeBox( + "target", W, 100.0 * u.cm, 100.0 * u.cm, thickness + ) + top.AddNode(aBox, 1, ROOT.TGeoTranslation(0, 0, 0)) + + def InitParContainers(): + print("not implemented!") + sensPlane = ROOT.exitHadronAbsorber() -sensPlane.SetEnergyCut(ecut*u.GeV) -sensPlane.SetZposition(thickness+10*u.cm) +sensPlane.SetEnergyCut(ecut * u.GeV) +sensPlane.SetZposition(thickness + 10 * u.cm) run.AddModule(sensPlane) target = Block() run.AddModule(target) primGen = ROOT.FairPrimaryGenerator() -myPgun = ROOT.FairBoxGenerator(2212,1) # pdg id and multiplicity -myPgun.SetPRange(minmomentum,maxmomentum) -myPgun.SetPhiRange(0,0) # // Azimuth angle range [degree] -myPgun.SetThetaRange(0,0) # // Polar angle in lab system range [degree] -myPgun.SetXYZ(0.*u.cm, 0.*u.cm, -10.*u.cm - (thickness) ) +myPgun = ROOT.FairBoxGenerator(2212, 1) # pdg id and multiplicity +myPgun.SetPRange(minmomentum, maxmomentum) +myPgun.SetPhiRange(0, 0) # // Azimuth angle range [degree] +myPgun.SetThetaRange(0, 0) # // Polar angle in lab system range [degree] +myPgun.SetXYZ(0.0 * u.cm, 0.0 * u.cm, -10.0 * u.cm - (thickness)) primGen.AddGenerator(myPgun) run.SetGenerator(primGen) # @@ -93,7 +121,7 @@ def InitParContainers(): fStack = gMC.GetStack() fStack.SetMinPoints(1) -fStack.SetEnergyCut(-1.) +fStack.SetEnergyCut(-1.0) # -----Start run---------------------------------------------------- run.Run(nev) @@ -102,24 +130,29 @@ def InitParContainers(): import rootUtils as ut -f=ROOT.TFile('TLV.root') +f = ROOT.TFile("TLV.root") pdg = ROOT.TDatabasePDG.Instance() -h={} +h = {} sTree = f.cbmsim -ut.bookHist(h,'Ekin','Ekin of particles in sens plane',400000,0.,400) -ut.bookHist(h,'EkinLow','Ekin of particles in sens plane',1000,0.,0.001) +ut.bookHist(h, "Ekin", "Ekin of particles in sens plane", 400000, 0.0, 400) +ut.bookHist(h, "EkinLow", "Ekin of particles in sens plane", 1000, 0.0, 0.001) for n in range(sTree.GetEntries()): - rc = sTree.GetEvent(n) - for aHit in sTree.vetoPoint: - oTrack = sTree.MCTrack[aHit.GetTrackID()] - M = pdg.GetParticle(oTrack.GetPdgCode()).Mass() - Ekin = ROOT.TMath.Sqrt( aHit.GetPx()**2+aHit.GetPy()**2+aHit.GetPz()**2 + M**2) - M - rc = h['Ekin'].Fill(Ekin) - rc = h['EkinLow'].Fill(Ekin) -ut.bookCanvas(h,key=s,title=s,nx=900,ny=600,cx=1,cy=1) + rc = sTree.GetEvent(n) + for aHit in sTree.vetoPoint: + oTrack = sTree.MCTrack[aHit.GetTrackID()] + M = pdg.GetParticle(oTrack.GetPdgCode()).Mass() + Ekin = ( + ROOT.TMath.Sqrt( + aHit.GetPx() ** 2 + aHit.GetPy() ** 2 + aHit.GetPz() ** 2 + M**2 + ) + - M + ) + rc = h["Ekin"].Fill(Ekin) + rc = h["EkinLow"].Fill(Ekin) +ut.bookCanvas(h, key=s, title=s, nx=900, ny=600, cx=1, cy=1) tc = h[s].cd(1) tc.SetLogy(1) -h['Ekin'].Draw() +h["Ekin"].Draw() # tungsten dedex mev cm**2/g 1.145 * rho g/cm-3 19.3 * 0.1 # interactionLength 191.9 / 19.3 = 9.94cm, 0.1/9.94 = 1% @@ -128,7 +161,7 @@ def InitParContainers(): timer.Stop() rtime = timer.RealTime() ctime = timer.CpuTime() -print(' ') +print(" ") print("Macro finished succesfully.") -print("Output file is ", outFile) -print("Real time ",rtime, " s, CPU time ",ctime,"s") +print("Output file is ", outFile) +print("Real time ", rtime, " s, CPU time ", ctime, "s") diff --git a/muonShieldOptimization/submitPyG4prod.py b/muonShieldOptimization/submitPyG4prod.py index 5014bea39b..a850efb552 100644 --- a/muonShieldOptimization/submitPyG4prod.py +++ b/muonShieldOptimization/submitPyG4prod.py @@ -1,15 +1,29 @@ -import os,time -path = '../' -if not os.uname()[1].find('Ubuntu')<0: path = os.environ['HNL'] -os.system('cp '+path+'/g4Ex.py g4Ex_thisProduction.py ') -nevents = {1:100000,10:1000000,100:10000000} -ecut = 100. -for run in range(30,40): - logfile = 'log'+str(run)+'_'+str(ecut) - if logfile in os.listdir('.'): os.system('rm '+logfile) - cmd = 'python g4Ex_thisProduction.py '+str(run)+' '+str(int(nevents[ecut]))+' '+str(ecut)+' > '+logfile+' &' - os.system(cmd) - time.sleep(10) +import os +import time + +path = "../" +if not os.uname()[1].find("Ubuntu") < 0: + path = os.environ["HNL"] +os.system("cp " + path + "/g4Ex.py g4Ex_thisProduction.py ") +nevents = {1: 100000, 10: 1000000, 100: 10000000} +ecut = 100.0 +for run in range(30, 40): + logfile = "log" + str(run) + "_" + str(ecut) + if logfile in os.listdir("."): + os.system("rm " + logfile) + cmd = ( + "python g4Ex_thisProduction.py " + + str(run) + + " " + + str(int(nevents[ecut])) + + " " + + str(ecut) + + " > " + + logfile + + " &" + ) + os.system(cmd) + time.sleep(10) # ecut 1, 1E4 events = 63000 seconds = 17.5h : for 1E9 -> 200yrs # ecut 10, 1E4 events = 940 seconds for 1E9 -> 3yrs diff --git a/nutaudet/CMakeLists.txt b/nutaudet/CMakeLists.txt index 9389bf0ad7..5d9b1fed32 100644 --- a/nutaudet/CMakeLists.txt +++ b/nutaudet/CMakeLists.txt @@ -1,43 +1,42 @@ # Create a library called "libnutaudet” which includes the source files given in -# the array . -# The extension is already found. Any number of sources could be listed here. +# the array . The extension is already found. Any number of sources could be +# listed here. set(INCLUDE_DIRECTORIES -${BASE_INCLUDE_DIRECTORIES} -${CMAKE_SOURCE_DIR}/shipdata -${CMAKE_SOURCE_DIR}/nutaudet -${ROOT_INCLUDE_DIR} -${VMC_INCLUDE_DIRS} -${genfit2_INCDIR} -) + ${BASE_INCLUDE_DIRECTORIES} ${CMAKE_SOURCE_DIR}/shipdata + ${CMAKE_SOURCE_DIR}/nutaudet ${ROOT_INCLUDE_DIR} ${VMC_INCLUDE_DIRS} + ${genfit2_INCDIR}) include_directories(${INCLUDE_DIRECTORIES} ${FAIRROOT_INCLUDE_DIR}) include_directories(SYSTEM ${SYSTEM_INCLUDE_DIRECTORIES}) -set(LINK_DIRECTORIES -${ROOT_LIBRARY_DIR} -${FAIRROOT_LIBRARY_DIR} -${genfit2_LIBDIR} -) +set(LINK_DIRECTORIES ${ROOT_LIBRARY_DIR} ${FAIRROOT_LIBRARY_DIR} + ${genfit2_LIBDIR}) -link_directories( ${LINK_DIRECTORIES}) +link_directories(${LINK_DIRECTORIES}) set(SRCS -NuTauMudet.cxx -ShipRpcPoint.cxx -HPT.cxx -HptPoint.cxx -NutaudetContFact.cxx -Target.cxx -EmulsionMagnet.cxx -TargetPoint.cxx -TargetTracker.cxx -TTPoint.cxx -) + NuTauMudet.cxx + ShipRpcPoint.cxx + HPT.cxx + HptPoint.cxx + NutaudetContFact.cxx + Target.cxx + EmulsionMagnet.cxx + TargetPoint.cxx + TargetTracker.cxx + TTPoint.cxx) -Set(HEADERS ) -Set(LINKDEF nutaudetLinkDef.h) -Set(LIBRARY_NAME nutaudet) -set(DEPENDENCIES Base ShipData GeoBase ParBase Geom Core FairLogger::FairLogger) +set(HEADERS) +set(LINKDEF nutaudetLinkDef.h) +set(LIBRARY_NAME nutaudet) +set(DEPENDENCIES + Base + ShipData + GeoBase + ParBase + Geom + Core + FairLogger::FairLogger) -GENERATE_LIBRARY() +generate_library() diff --git a/nutaudet/EmulsionMagnet.cxx b/nutaudet/EmulsionMagnet.cxx index becd91088d..39f834d756 100644 --- a/nutaudet/EmulsionMagnet.cxx +++ b/nutaudet/EmulsionMagnet.cxx @@ -1,47 +1,41 @@ #include "EmulsionMagnet.h" -#include "TGeoManager.h" -#include "FairRun.h" // for FairRun -#include "FairRuntimeDb.h" // for FairRuntimeDb -#include // for ostream -#include "TList.h" // for TListIter, TList (ptr only) -#include "TObjArray.h" // for TObjArray -#include "TString.h" // for TString - -#include "TGeoBBox.h" -#include "TGeoTrd1.h" -#include "TGeoSphere.h" -#include "TGeoCompositeShape.h" -#include "TGeoTube.h" -#include "TGeoMaterial.h" -#include "TGeoMedium.h" -#include "TGeoTrd1.h" -#include "TGeoArb8.h" - -#include "FairVolume.h" -#include "FairGeoVolume.h" -#include "FairGeoNode.h" -#include "FairRootManager.h" -#include "FairGeoLoader.h" +#include "FairGeoBuilder.h" #include "FairGeoInterface.h" -#include "FairGeoTransform.h" +#include "FairGeoLoader.h" #include "FairGeoMedia.h" #include "FairGeoMedium.h" -#include "FairGeoBuilder.h" +#include "FairGeoNode.h" +#include "FairGeoTransform.h" +#include "FairGeoVolume.h" +#include "FairRootManager.h" +#include "FairRun.h" // for FairRun #include "FairRun.h" +#include "FairRuntimeDb.h" // for FairRuntimeDb #include "FairRuntimeDb.h" - +#include "FairVolume.h" #include "ShipDetectorList.h" -#include "ShipUnit.h" #include "ShipStack.h" - -#include "TGeoTrd2.h" +#include "ShipUnit.h" +#include "TGeoArb8.h" +#include "TGeoBBox.h" #include "TGeoCompositeShape.h" - +#include "TGeoManager.h" +#include "TGeoMaterial.h" +#include "TGeoMedium.h" +#include "TGeoSphere.h" +#include "TGeoTrd1.h" +#include "TGeoTrd2.h" +#include "TGeoTube.h" #include "TGeoUniformMagField.h" +#include "TList.h" // for TListIter, TList (ptr only) +#include "TObjArray.h" // for TObjArray +#include "TString.h" // for TString #include "TVector3.h" -#include // for NULL -#include // for operator<<, basic_ostream,etc + +#include // for ostream +#include // for operator<<, basic_ostream,etc +#include // for NULL #include using std::cout; @@ -49,559 +43,646 @@ using std::endl; using namespace ShipUnit; -EmulsionMagnet::~EmulsionMagnet() -{} +EmulsionMagnet::~EmulsionMagnet() {} -EmulsionMagnet::EmulsionMagnet():FairModule("EmulsionMagnet","") +EmulsionMagnet::EmulsionMagnet() + : FairModule("EmulsionMagnet", "") {} -EmulsionMagnet::EmulsionMagnet(const char* name, const Double_t zC,const char* Title):FairModule(name, Title) +EmulsionMagnet::EmulsionMagnet(const char* name, const Double_t zC, const char* Title) + : FairModule(name, Title) { - fCenterZ = zC; + fCenterZ = zC; } void EmulsionMagnet::SetDesign(Int_t Design) { - fDesign = Design; - Info("Chosen TP Design (0 no, 1 yes) "," %i", fDesign); + fDesign = Design; + Info("Chosen TP Design (0 no, 1 yes) ", " %i", fDesign); } void EmulsionMagnet::SetGaps(Double_t Up, Double_t Down) { - fGapUpstream = Up; - fGapDownstream = Down; + fGapUpstream = Up; + fGapDownstream = Down; } void EmulsionMagnet::SetMagnetSizes(Double_t X, Double_t Y, Double_t Z) { - fMagnetX=X; - fMagnetY=Y; - fMagnetZ=Z; + fMagnetX = X; + fMagnetY = Y; + fMagnetZ = Z; } void EmulsionMagnet::SetMagnetColumn(Double_t ColX, Double_t ColY, Double_t ColZ) { - fColumnX=ColX; - fColumnY=ColY; - fColumnZ=ColZ; + fColumnX = ColX; + fColumnY = ColY; + fColumnZ = ColZ; } void EmulsionMagnet::SetBaseDim(Double_t BaseX, Double_t BaseY, Double_t BaseZ) { - fBaseX = BaseX; - fBaseY = BaseY; - fBaseZ = BaseZ; + fBaseX = BaseX; + fBaseY = BaseY; + fBaseZ = BaseZ; } - void EmulsionMagnet::SetCoilParameters(Double_t Radius, Double_t height1, Double_t height2, Double_t Distance) { - fCoilR = Radius; - fCoilH1 = height1; //upper(left) - fCoilH2 = height2; //lowe(right) - fCoilDist = Distance; + fCoilR = Radius; + fCoilH1 = height1; // upper(left) + fCoilH2 = height2; // lowe(right) + fCoilDist = Distance; } void EmulsionMagnet::SetCoilParameters(Double_t X, Double_t Y, Double_t height1, Double_t height2, Double_t Thickness) { - fCoilX = X; - fCoilY = Y; - // cout << "fCoilX = "<< fCoilX<< " fCoilY = "<GetMedium(name); - if (medium!=NULL) - return ShipMedium->getMediumIndex(); - return geoBuild->createMedium(ShipMedium); + TGeoMedium* medium = gGeoManager->GetMedium(name); + if (medium != NULL) + return ShipMedium->getMediumIndex(); + return geoBuild->createMedium(ShipMedium); } void EmulsionMagnet::ConstructGeometry() { - InitMedium("air"); - TGeoMedium *air =gGeoManager->GetMedium("air"); + InitMedium("air"); + TGeoMedium* air = gGeoManager->GetMedium("air"); - InitMedium("iron"); - TGeoMedium *Fe =gGeoManager->GetMedium("iron"); + InitMedium("iron"); + TGeoMedium* Fe = gGeoManager->GetMedium("iron"); - InitMedium("CoilAluminium"); - TGeoMedium *Al = gGeoManager->GetMedium("CoilAluminium"); + InitMedium("CoilAluminium"); + TGeoMedium* Al = gGeoManager->GetMedium("CoilAluminium"); - InitMedium("CoilCopper"); - TGeoMedium *Cu = gGeoManager->GetMedium("CoilCopper"); + InitMedium("CoilCopper"); + TGeoMedium* Cu = gGeoManager->GetMedium("CoilCopper"); - InitMedium("steel"); - TGeoMedium *Steel = gGeoManager->GetMedium("steel"); + InitMedium("steel"); + TGeoMedium* Steel = gGeoManager->GetMedium("steel"); - gGeoManager->SetVisLevel(10); + gGeoManager->SetVisLevel(10); - TGeoVolume *tTauNuDet = gGeoManager->GetVolume("tTauNuDet"); - cout<< "Tau Nu Detector fDesign: "<< fDesign<GetVolume("tTauNuDet"); + cout << "Tau Nu Detector fDesign: " << fDesign << endl; - if(fDesign==0)//OLD, TP + if (fDesign == 0) // OLD, TP { - TGeoUniformMagField *magField1 = new TGeoUniformMagField(0.,-fField,0.); //magnetic field in Magnet pillars - - TGeoVolumeAssembly *MagnetVol = new TGeoVolumeAssembly("Goliath"); - tTauNuDet->AddNode(MagnetVol,1,new TGeoTranslation(0,0,fCenterZ)); - - //Iron basis on which the coils are placed - TGeoBBox *Base = new TGeoBBox(fBaseX/2,fBaseY/2,fBaseZ/2); - TGeoVolume *volBase = new TGeoVolume("volBase",Base,Fe); - volBase->SetLineColor(kRed); - MagnetVol->AddNode(volBase,1,new TGeoTranslation(0, fMagnetY/2 - fBaseY/2, 0)); //upper part - MagnetVol->AddNode(volBase,2,new TGeoTranslation(0, -fMagnetY/2 + fBaseY/2, 0)); //lower part - - //Coils Description: 2 volumes must be defined being the upper coil in Cu and the lower one in Al and also heghts are different - TGeoTube *CoilBoxU = new TGeoTube("C",0,fCoilR,fCoilH1/2); - TGeoVolume *CoilVolUp = new TGeoVolume("CoilVolUp",CoilBoxU, Cu); - CoilVolUp->SetLineColor(kGreen); - TGeoTube *CoilBoxD = new TGeoTube("C",0,fCoilR,fCoilH2/2); - TGeoVolume *CoilVolDown = new TGeoVolume("CoilVolDown",CoilBoxD, Al); - CoilVolDown->SetLineColor(kGreen); - - TGeoRotation *r1 = new TGeoRotation(); - r1->SetAngles(0,90,0); - TGeoCombiTrans tUp(0, fMagnetY/2 - fBaseY - fCoilH1/2, 0,r1); - TGeoHMatrix *mUp = new TGeoHMatrix(tUp); - TGeoCombiTrans tDown(0, -fMagnetY/2 + fBaseY + fCoilH2/2, 0,r1); - TGeoHMatrix *mDown = new TGeoHMatrix(tDown); - - MagnetVol->AddNode(CoilVolUp,1,mUp); - MagnetVol->AddNode(CoilVolDown,1,mDown); - - //********************* Columns **************************** - - //Each column is made of a longer pillar (rectangle + trapezoid) and on top a shorter pillar (rectangle + trapezoid again) - - Double_t base1 = 135, base2 = 78; //basis of the trapezoid - Double_t side1 = 33, side2 = 125, side3 = 57, side4 = 90; //Sides of the columns - - //***** SIDE Left Front **** - - //Shorter Pillar: rectangle - TGeoBBox *LateralS1 = new TGeoBBox("LateralS1",side1/2,fCoilH1/2,base1/2); - TGeoTranslation *tr1 = new TGeoTranslation(-fMagnetX/2 + side1/2, fMagnetY/2 - fBaseY - fCoilH1/2, -fMagnetZ/2 + base1/2); - TGeoVolume *volLateralS1 = new TGeoVolume("volLateralS1",LateralS1,Fe); - volLateralS1->SetLineColor(kRed); - volLateralS1->SetField(magField1); - MagnetVol->AddNode(volLateralS1, 1, tr1); - - //Shorter Pillar: trapezoid - - TGeoArb8 *LateralS2 = new TGeoArb8("LateralS2",fCoilH1/2); - LateralS2->SetVertex(0, side4, 0); - LateralS2->SetVertex(1, side1, 0); - LateralS2->SetVertex(2, side1, base1); - LateralS2->SetVertex(3, side4, base2); - LateralS2->SetVertex(4, side4, 0); - LateralS2->SetVertex(5, side1, 0); - LateralS2->SetVertex(6, side1, base1); - LateralS2->SetVertex(7, side4, base2); - - TGeoVolume *volLateralS2 = new TGeoVolume("volLateralS2",LateralS2,Fe); - volLateralS2->SetLineColor(kRed); - volLateralS2->SetField(magField1); - - TGeoRotation *r2 = new TGeoRotation(); - r2->SetAngles(0,90,0); - TGeoCombiTrans tr3(-fMagnetX/2, fMagnetY/2 - fBaseY - fCoilH1/2, -fMagnetZ/2,r2); - TGeoHMatrix *m3_a = new TGeoHMatrix(tr3); - MagnetVol->AddNode(volLateralS2, 1, m3_a); - - //LOWER LATERAL SURFACE - - //LONGER RECTANGLE - TGeoBBox *LateralSurface1low = new TGeoBBox("LateralSurface1low",side1/2,(fCoilDist + fCoilH2)/2,side2/2); - TGeoVolume *volLateralSurface1low = new TGeoVolume("volLateralSurface1low",LateralSurface1low,Fe); - volLateralSurface1low->SetLineColor(kRed); - volLateralSurface1low->SetField(magField1); - TGeoTranslation *tr1low = new TGeoTranslation(-fMagnetX/2 +side1/2, fMagnetY/2 - fBaseY - fCoilH1 - (fCoilDist + fCoilH2)/2, -fMagnetZ/2 + side2/2); - MagnetVol->AddNode(volLateralSurface1low, 1, tr1low);; - - - //SHORTER RECTANGLE - TGeoBBox *LateralSurface2low = new TGeoBBox("LateralSurface2low",side3/2,(fCoilDist + fCoilH2)/2,base2/2); - TGeoVolume *volLateralSurface2low = new TGeoVolume("volLateralSurface2low",LateralSurface2low,Fe); - volLateralSurface2low->SetLineColor(kRed); - TGeoTranslation *tr2low = new TGeoTranslation(-fMagnetX/2 +side1 + side3/2, fMagnetY/2 - fBaseY -fCoilH1 - (fCoilDist + fCoilH2)/2, -fMagnetZ/2 + base2/2); - MagnetVol->AddNode(volLateralSurface2low, 1, tr2low); - volLateralSurface2low->SetField(magField1); - - //***** SIDE Right Front **** - - //LONGER RECTANGLE - TGeoTranslation *tr1_b = new TGeoTranslation(-fMagnetX/2 + side1/2, fMagnetY/2 - fBaseY - fCoilH1/2, fMagnetZ/2 - base1/2); - TGeoVolume *volLateralS1_b = new TGeoVolume("volLateralS1_b",LateralS1,Fe); - volLateralS1_b->SetLineColor(kRed); - volLateralS1_b->SetField(magField1); - MagnetVol->AddNode(volLateralS1_b, 1, tr1_b); - - //TRAPEZOID - TGeoArb8 *LateralS2_b = new TGeoArb8("LateralS2_b",fCoilH1/2); - LateralS2_b ->SetVertex(0, side4, 0); - LateralS2_b ->SetVertex(1, side1, 0); - LateralS2_b ->SetVertex(2, side1, base1); - LateralS2_b ->SetVertex(3, side4, base2); - LateralS2_b ->SetVertex(4, side4, 0); - LateralS2_b ->SetVertex(5, side1, 0); - LateralS2_b ->SetVertex(6, side1, base1); - LateralS2_b ->SetVertex(7, side4, base2); - - TGeoVolume *volLateralS2_b = new TGeoVolume("volLateralS2_b",LateralS2_b,Fe); - volLateralS2_b->SetLineColor(kRed); - volLateralS2_b->SetField(magField1); - - TGeoRotation *r2_b = new TGeoRotation(); - r2_b->SetAngles(0,270,0); - TGeoCombiTrans tr2_b(-fMagnetX/2 , fMagnetY/2 - fBaseY - fCoilH1/2, fMagnetZ/2,r2_b); - TGeoHMatrix *m3_b = new TGeoHMatrix(tr2_b); - MagnetVol->AddNode(volLateralS2_b, 1, m3_b); - - - //LOWER LATERAL SURFACE - - //LONGER RECTANGLE - TGeoVolume *volLateralSurface1blow = new TGeoVolume("volLateralSurface1blow",LateralSurface1low,Fe); - volLateralSurface1blow->SetLineColor(kRed); - volLateralSurface1blow->SetField(magField1); - TGeoTranslation *tr1blow = new TGeoTranslation(-fMagnetX/2 +side1/2, fMagnetY/2 - fBaseY - fCoilH1 - (fCoilDist + fCoilH2)/2, fMagnetZ/2 - side2/2); - MagnetVol->AddNode(volLateralSurface1blow, 1, tr1blow);; - - - //SHORTER RECTANGLE - TGeoVolume *volLateralSurface2blow = new TGeoVolume("volLateralSurface2blow",LateralSurface2low,Fe); - volLateralSurface2blow->SetLineColor(kRed); - volLateralSurface2blow->SetField(magField1); - TGeoTranslation *tr2blow = new TGeoTranslation(-fMagnetX/2 +side1 + side3/2, fMagnetY/2 - fBaseY - fCoilH1 - (fCoilDist + fCoilH2)/2, fMagnetZ/2 - base2/2); - MagnetVol->AddNode(volLateralSurface2blow, 1, tr2blow); - - - //***** SIDE left Back **** - - - //LONGER RECTANGLE - TGeoBBox *LateralS1_d = new TGeoBBox("LateralS1_d",side1/2,(fCoilH1 + fCoilH2 + fCoilDist)/2,base1/2); - TGeoTranslation *tr1_d = new TGeoTranslation(fMagnetX/2 - side1/2, fMagnetY/2 - fBaseY - (fCoilH1 + fCoilH2 + fCoilDist)/2, -fMagnetZ/2 + base1/2); - TGeoVolume *volLateralS1_d = new TGeoVolume("volLateralS1_d",LateralS1_d,Fe); - volLateralS1_d->SetLineColor(kRed); - volLateralS1_d->SetField(magField1); - MagnetVol->AddNode(volLateralS1_d, 1, tr1_d); - - //TRAPEZOID - - TGeoArb8 *LateralS2_d = new TGeoArb8("LateralS2_d",(fCoilH1 + fCoilH2 + fCoilDist)/2); - LateralS2_d->SetVertex(0, side4, 0); - LateralS2_d->SetVertex(1, side1, 0); - LateralS2_d->SetVertex(2, side1, base1); - LateralS2_d->SetVertex(3, side4, base2); - LateralS2_d->SetVertex(4, side4, 0); - LateralS2_d->SetVertex(5, side1, 0); - LateralS2_d->SetVertex(6, side1, base1); - LateralS2_d->SetVertex(7, side4, base2); - - - TGeoVolume *volLateralS2_d = new TGeoVolume("volLateralS2_d",LateralS2_d,Fe); - volLateralS2_d->SetLineColor(kRed); - volLateralS2_d->SetField(magField1); - - TGeoRotation *r2_d = new TGeoRotation(); - r2_d->SetAngles(0,270,180); - TGeoCombiTrans tr2_d(fMagnetX/2 , fMagnetY/2 - fBaseY - (fCoilH1 + fCoilH2 + fCoilDist)/2, -fMagnetZ/2,r2_d); - TGeoHMatrix *m3_d = new TGeoHMatrix(tr2_d); - MagnetVol->AddNode(volLateralS2_d, 1, m3_d); - -//***** SIDE right Back **** - - - //LONGER RECTANGLE - TGeoBBox *LateralS1_c = new TGeoBBox("LateralS1_c",side1/2,(fCoilH1 + fCoilH2 + fCoilDist)/2,base1/2); - TGeoTranslation *tr1_c = new TGeoTranslation(fMagnetX/2 - side1/2, fMagnetY/2 - fBaseY - (fCoilH1 + fCoilH2 + fCoilDist)/2, fMagnetZ/2 - base1/2); - TGeoVolume *volLateralS1_c = new TGeoVolume("volLateralS1_c",LateralS1_c,Fe); - volLateralS1_c->SetLineColor(kRed); - volLateralS1_c->SetField(magField1); - MagnetVol->AddNode(volLateralS1_c, 1, tr1_c); - - //TRAPEZOID - - TGeoArb8 *LateralS2_c = new TGeoArb8("LateralS2_c",(fCoilH1 + fCoilH2 + fCoilDist)/2); - LateralS2_c ->SetVertex(0, side4, 0); - LateralS2_c ->SetVertex(1, side1, 0); - LateralS2_c ->SetVertex(2, side1, base1); - LateralS2_c ->SetVertex(3, side4, base2); - LateralS2_c ->SetVertex(4, side4, 0); - LateralS2_c ->SetVertex(5, side1, 0); - LateralS2_c ->SetVertex(6, side1, base1); - LateralS2_c ->SetVertex(7, side4, base2); - - TGeoVolume *volLateralS2_c = new TGeoVolume("volLateralS2_c",LateralS2_c,Fe); - volLateralS2_c->SetLineColor(kRed); - volLateralS2_c->SetField(magField1); - - TGeoRotation *r2_c = new TGeoRotation(); - r2_c->SetAngles(0,90,180); - TGeoCombiTrans tr2_c(fMagnetX/2 , fMagnetY/2 - fBaseY - (fCoilH1 + fCoilH2 + fCoilDist)/2, fMagnetZ/2,r2_c); - TGeoHMatrix *m3_c = new TGeoHMatrix(tr2_c); - MagnetVol->AddNode(volLateralS2_c, 1, m3_c); - - + TGeoUniformMagField* magField1 = new TGeoUniformMagField(0., -fField, 0.); // magnetic field in Magnet pillars + + TGeoVolumeAssembly* MagnetVol = new TGeoVolumeAssembly("Goliath"); + tTauNuDet->AddNode(MagnetVol, 1, new TGeoTranslation(0, 0, fCenterZ)); + + // Iron basis on which the coils are placed + TGeoBBox* Base = new TGeoBBox(fBaseX / 2, fBaseY / 2, fBaseZ / 2); + TGeoVolume* volBase = new TGeoVolume("volBase", Base, Fe); + volBase->SetLineColor(kRed); + MagnetVol->AddNode(volBase, 1, new TGeoTranslation(0, fMagnetY / 2 - fBaseY / 2, 0)); // upper part + MagnetVol->AddNode(volBase, 2, new TGeoTranslation(0, -fMagnetY / 2 + fBaseY / 2, 0)); // lower part + + // Coils Description: 2 volumes must be defined being the upper coil in Cu and the lower one in Al and also + // heghts are different + TGeoTube* CoilBoxU = new TGeoTube("C", 0, fCoilR, fCoilH1 / 2); + TGeoVolume* CoilVolUp = new TGeoVolume("CoilVolUp", CoilBoxU, Cu); + CoilVolUp->SetLineColor(kGreen); + TGeoTube* CoilBoxD = new TGeoTube("C", 0, fCoilR, fCoilH2 / 2); + TGeoVolume* CoilVolDown = new TGeoVolume("CoilVolDown", CoilBoxD, Al); + CoilVolDown->SetLineColor(kGreen); + + TGeoRotation* r1 = new TGeoRotation(); + r1->SetAngles(0, 90, 0); + TGeoCombiTrans tUp(0, fMagnetY / 2 - fBaseY - fCoilH1 / 2, 0, r1); + TGeoHMatrix* mUp = new TGeoHMatrix(tUp); + TGeoCombiTrans tDown(0, -fMagnetY / 2 + fBaseY + fCoilH2 / 2, 0, r1); + TGeoHMatrix* mDown = new TGeoHMatrix(tDown); + + MagnetVol->AddNode(CoilVolUp, 1, mUp); + MagnetVol->AddNode(CoilVolDown, 1, mDown); + + //********************* Columns **************************** + + // Each column is made of a longer pillar (rectangle + trapezoid) and on top a shorter pillar (rectangle + + // trapezoid again) + + Double_t base1 = 135, base2 = 78; // basis of the trapezoid + Double_t side1 = 33, side2 = 125, side3 = 57, side4 = 90; // Sides of the columns + + //***** SIDE Left Front **** + + // Shorter Pillar: rectangle + TGeoBBox* LateralS1 = new TGeoBBox("LateralS1", side1 / 2, fCoilH1 / 2, base1 / 2); + TGeoTranslation* tr1 = new TGeoTranslation( + -fMagnetX / 2 + side1 / 2, fMagnetY / 2 - fBaseY - fCoilH1 / 2, -fMagnetZ / 2 + base1 / 2); + TGeoVolume* volLateralS1 = new TGeoVolume("volLateralS1", LateralS1, Fe); + volLateralS1->SetLineColor(kRed); + volLateralS1->SetField(magField1); + MagnetVol->AddNode(volLateralS1, 1, tr1); + + // Shorter Pillar: trapezoid + + TGeoArb8* LateralS2 = new TGeoArb8("LateralS2", fCoilH1 / 2); + LateralS2->SetVertex(0, side4, 0); + LateralS2->SetVertex(1, side1, 0); + LateralS2->SetVertex(2, side1, base1); + LateralS2->SetVertex(3, side4, base2); + LateralS2->SetVertex(4, side4, 0); + LateralS2->SetVertex(5, side1, 0); + LateralS2->SetVertex(6, side1, base1); + LateralS2->SetVertex(7, side4, base2); + + TGeoVolume* volLateralS2 = new TGeoVolume("volLateralS2", LateralS2, Fe); + volLateralS2->SetLineColor(kRed); + volLateralS2->SetField(magField1); + + TGeoRotation* r2 = new TGeoRotation(); + r2->SetAngles(0, 90, 0); + TGeoCombiTrans tr3(-fMagnetX / 2, fMagnetY / 2 - fBaseY - fCoilH1 / 2, -fMagnetZ / 2, r2); + TGeoHMatrix* m3_a = new TGeoHMatrix(tr3); + MagnetVol->AddNode(volLateralS2, 1, m3_a); + + // LOWER LATERAL SURFACE + + // LONGER RECTANGLE + TGeoBBox* LateralSurface1low = + new TGeoBBox("LateralSurface1low", side1 / 2, (fCoilDist + fCoilH2) / 2, side2 / 2); + TGeoVolume* volLateralSurface1low = new TGeoVolume("volLateralSurface1low", LateralSurface1low, Fe); + volLateralSurface1low->SetLineColor(kRed); + volLateralSurface1low->SetField(magField1); + TGeoTranslation* tr1low = new TGeoTranslation(-fMagnetX / 2 + side1 / 2, + fMagnetY / 2 - fBaseY - fCoilH1 - (fCoilDist + fCoilH2) / 2, + -fMagnetZ / 2 + side2 / 2); + MagnetVol->AddNode(volLateralSurface1low, 1, tr1low); + ; + + // SHORTER RECTANGLE + TGeoBBox* LateralSurface2low = + new TGeoBBox("LateralSurface2low", side3 / 2, (fCoilDist + fCoilH2) / 2, base2 / 2); + TGeoVolume* volLateralSurface2low = new TGeoVolume("volLateralSurface2low", LateralSurface2low, Fe); + volLateralSurface2low->SetLineColor(kRed); + TGeoTranslation* tr2low = new TGeoTranslation(-fMagnetX / 2 + side1 + side3 / 2, + fMagnetY / 2 - fBaseY - fCoilH1 - (fCoilDist + fCoilH2) / 2, + -fMagnetZ / 2 + base2 / 2); + MagnetVol->AddNode(volLateralSurface2low, 1, tr2low); + volLateralSurface2low->SetField(magField1); + + //***** SIDE Right Front **** + + // LONGER RECTANGLE + TGeoTranslation* tr1_b = new TGeoTranslation( + -fMagnetX / 2 + side1 / 2, fMagnetY / 2 - fBaseY - fCoilH1 / 2, fMagnetZ / 2 - base1 / 2); + TGeoVolume* volLateralS1_b = new TGeoVolume("volLateralS1_b", LateralS1, Fe); + volLateralS1_b->SetLineColor(kRed); + volLateralS1_b->SetField(magField1); + MagnetVol->AddNode(volLateralS1_b, 1, tr1_b); + + // TRAPEZOID + TGeoArb8* LateralS2_b = new TGeoArb8("LateralS2_b", fCoilH1 / 2); + LateralS2_b->SetVertex(0, side4, 0); + LateralS2_b->SetVertex(1, side1, 0); + LateralS2_b->SetVertex(2, side1, base1); + LateralS2_b->SetVertex(3, side4, base2); + LateralS2_b->SetVertex(4, side4, 0); + LateralS2_b->SetVertex(5, side1, 0); + LateralS2_b->SetVertex(6, side1, base1); + LateralS2_b->SetVertex(7, side4, base2); + + TGeoVolume* volLateralS2_b = new TGeoVolume("volLateralS2_b", LateralS2_b, Fe); + volLateralS2_b->SetLineColor(kRed); + volLateralS2_b->SetField(magField1); + + TGeoRotation* r2_b = new TGeoRotation(); + r2_b->SetAngles(0, 270, 0); + TGeoCombiTrans tr2_b(-fMagnetX / 2, fMagnetY / 2 - fBaseY - fCoilH1 / 2, fMagnetZ / 2, r2_b); + TGeoHMatrix* m3_b = new TGeoHMatrix(tr2_b); + MagnetVol->AddNode(volLateralS2_b, 1, m3_b); + + // LOWER LATERAL SURFACE + + // LONGER RECTANGLE + TGeoVolume* volLateralSurface1blow = new TGeoVolume("volLateralSurface1blow", LateralSurface1low, Fe); + volLateralSurface1blow->SetLineColor(kRed); + volLateralSurface1blow->SetField(magField1); + TGeoTranslation* tr1blow = new TGeoTranslation(-fMagnetX / 2 + side1 / 2, + fMagnetY / 2 - fBaseY - fCoilH1 - (fCoilDist + fCoilH2) / 2, + fMagnetZ / 2 - side2 / 2); + MagnetVol->AddNode(volLateralSurface1blow, 1, tr1blow); + ; + + // SHORTER RECTANGLE + TGeoVolume* volLateralSurface2blow = new TGeoVolume("volLateralSurface2blow", LateralSurface2low, Fe); + volLateralSurface2blow->SetLineColor(kRed); + volLateralSurface2blow->SetField(magField1); + TGeoTranslation* tr2blow = new TGeoTranslation(-fMagnetX / 2 + side1 + side3 / 2, + fMagnetY / 2 - fBaseY - fCoilH1 - (fCoilDist + fCoilH2) / 2, + fMagnetZ / 2 - base2 / 2); + MagnetVol->AddNode(volLateralSurface2blow, 1, tr2blow); + + //***** SIDE left Back **** + + // LONGER RECTANGLE + TGeoBBox* LateralS1_d = new TGeoBBox("LateralS1_d", side1 / 2, (fCoilH1 + fCoilH2 + fCoilDist) / 2, base1 / 2); + TGeoTranslation* tr1_d = new TGeoTranslation(fMagnetX / 2 - side1 / 2, + fMagnetY / 2 - fBaseY - (fCoilH1 + fCoilH2 + fCoilDist) / 2, + -fMagnetZ / 2 + base1 / 2); + TGeoVolume* volLateralS1_d = new TGeoVolume("volLateralS1_d", LateralS1_d, Fe); + volLateralS1_d->SetLineColor(kRed); + volLateralS1_d->SetField(magField1); + MagnetVol->AddNode(volLateralS1_d, 1, tr1_d); + + // TRAPEZOID + + TGeoArb8* LateralS2_d = new TGeoArb8("LateralS2_d", (fCoilH1 + fCoilH2 + fCoilDist) / 2); + LateralS2_d->SetVertex(0, side4, 0); + LateralS2_d->SetVertex(1, side1, 0); + LateralS2_d->SetVertex(2, side1, base1); + LateralS2_d->SetVertex(3, side4, base2); + LateralS2_d->SetVertex(4, side4, 0); + LateralS2_d->SetVertex(5, side1, 0); + LateralS2_d->SetVertex(6, side1, base1); + LateralS2_d->SetVertex(7, side4, base2); + + TGeoVolume* volLateralS2_d = new TGeoVolume("volLateralS2_d", LateralS2_d, Fe); + volLateralS2_d->SetLineColor(kRed); + volLateralS2_d->SetField(magField1); + + TGeoRotation* r2_d = new TGeoRotation(); + r2_d->SetAngles(0, 270, 180); + TGeoCombiTrans tr2_d( + fMagnetX / 2, fMagnetY / 2 - fBaseY - (fCoilH1 + fCoilH2 + fCoilDist) / 2, -fMagnetZ / 2, r2_d); + TGeoHMatrix* m3_d = new TGeoHMatrix(tr2_d); + MagnetVol->AddNode(volLateralS2_d, 1, m3_d); + + //***** SIDE right Back **** + + // LONGER RECTANGLE + TGeoBBox* LateralS1_c = new TGeoBBox("LateralS1_c", side1 / 2, (fCoilH1 + fCoilH2 + fCoilDist) / 2, base1 / 2); + TGeoTranslation* tr1_c = new TGeoTranslation(fMagnetX / 2 - side1 / 2, + fMagnetY / 2 - fBaseY - (fCoilH1 + fCoilH2 + fCoilDist) / 2, + fMagnetZ / 2 - base1 / 2); + TGeoVolume* volLateralS1_c = new TGeoVolume("volLateralS1_c", LateralS1_c, Fe); + volLateralS1_c->SetLineColor(kRed); + volLateralS1_c->SetField(magField1); + MagnetVol->AddNode(volLateralS1_c, 1, tr1_c); + + // TRAPEZOID + + TGeoArb8* LateralS2_c = new TGeoArb8("LateralS2_c", (fCoilH1 + fCoilH2 + fCoilDist) / 2); + LateralS2_c->SetVertex(0, side4, 0); + LateralS2_c->SetVertex(1, side1, 0); + LateralS2_c->SetVertex(2, side1, base1); + LateralS2_c->SetVertex(3, side4, base2); + LateralS2_c->SetVertex(4, side4, 0); + LateralS2_c->SetVertex(5, side1, 0); + LateralS2_c->SetVertex(6, side1, base1); + LateralS2_c->SetVertex(7, side4, base2); + + TGeoVolume* volLateralS2_c = new TGeoVolume("volLateralS2_c", LateralS2_c, Fe); + volLateralS2_c->SetLineColor(kRed); + volLateralS2_c->SetField(magField1); + + TGeoRotation* r2_c = new TGeoRotation(); + r2_c->SetAngles(0, 90, 180); + TGeoCombiTrans tr2_c( + fMagnetX / 2, fMagnetY / 2 - fBaseY - (fCoilH1 + fCoilH2 + fCoilDist) / 2, fMagnetZ / 2, r2_c); + TGeoHMatrix* m3_c = new TGeoHMatrix(tr2_c); + MagnetVol->AddNode(volLateralS2_c, 1, m3_c); } - if(fDesign==1) //NEW with magnet + if (fDesign == 1) // NEW with magnet { - TGeoUniformMagField *magField1 = new TGeoUniformMagField(-fField,0.,0.); //magnetic field in Magnet pillars - - TGeoVolumeAssembly *MagnetVol = new TGeoVolumeAssembly("Davide"); - tTauNuDet->AddNode(MagnetVol,1,new TGeoTranslation(0,0,fCenterZ)); - - //The -0.01*mm is only for drawing reasons - [[maybe_unused]] auto *LateralBox = new TGeoBBox("LB",fBaseZ/2,fBaseY/2,(fBaseX-0.01*mm)/2); - TGeoTube *CoilBox = new TGeoTube("C",0,fCoilR,fCoilH1/2); - - TGeoCompositeShape *LateralSurf = new TGeoCompositeShape("LS","LB-C"); - - TGeoVolume *CoilVol = new TGeoVolume("CoilVol",CoilBox, Cu); - CoilVol->SetLineColor(kGreen); - TGeoVolume *LateralSurfVol = new TGeoVolume("LateralSurfVol",LateralSurf, Fe); - LateralSurfVol->SetLineColor(kRed); - - TGeoRotation *r1 = new TGeoRotation(); - r1->RotateY(90); - //r1->RotateY(90); - //r1->RotateY(90); - r1->RegisterYourself(); - - TGeoCombiTrans *trans1r = new TGeoCombiTrans(-fMagnetX/2+fBaseX/2,0,0,r1); - TGeoCombiTrans *trans1l = new TGeoCombiTrans(fMagnetX/2-fBaseX/2,0,0,r1); - TGeoHMatrix *m1_r = new TGeoHMatrix("m1_r"); - *m1_r = trans1r; - TGeoHMatrix *m1_l = new TGeoHMatrix("m1_l"); - *m1_l = trans1l; - - MagnetVol->AddNode(CoilVol,1, m1_r); - MagnetVol->AddNode(LateralSurfVol,1,m1_r); - MagnetVol->AddNode(CoilVol,2, m1_l); - MagnetVol->AddNode(LateralSurfVol,2,m1_l); - - TGeoBBox *ColumnBox = new TGeoBBox(fColumnX/2, fColumnY/2, fColumnZ/2); - TGeoVolume *ColumnVol = new TGeoVolume("ColumnVol",ColumnBox,Fe); - ColumnVol->SetField(magField1); - ColumnVol->SetLineColor(kRed); - MagnetVol->AddNode(ColumnVol,1,new TGeoTranslation(0,fMagnetY/2-fColumnY/2, -fMagnetZ/2+fColumnZ/2)); - MagnetVol->AddNode(ColumnVol,2,new TGeoTranslation(0,fMagnetY/2-fColumnY/2, fMagnetZ/2-fColumnZ/2)); - MagnetVol->AddNode(ColumnVol,3,new TGeoTranslation(0,-fMagnetY/2+fColumnY/2, -fMagnetZ/2+fColumnZ/2)); - MagnetVol->AddNode(ColumnVol,4,new TGeoTranslation(0,-fMagnetY/2+fColumnY/2, fMagnetZ/2-fColumnZ/2)); - - TGeoBBox *BaseBox = new TGeoBBox(fCoilDist/2,fColumnY/2, fBaseZ/2); - TGeoVolume *BaseVol = new TGeoVolume("BaseVol",BaseBox,Fe); - BaseVol->SetLineColor(kRed); - MagnetVol->AddNode(BaseVol,1, new TGeoTranslation(0,-fMagnetY/2+fColumnY/2,0)); - - TGeoBBox *PillarBox = new TGeoBBox(fPillarX/2,fPillarY/2, fPillarZ/2); - TGeoVolume *PillarVol = new TGeoVolume("PillarVol",PillarBox,Steel); - PillarVol->SetLineColor(kGreen+3); - tTauNuDet->AddNode(PillarVol,1, new TGeoTranslation(-fMagnetX/2+fPillarX/2,-fMagnetY/2-fPillarY/2, fCenterZ-fMagnetZ/2+fPillarZ/2)); - tTauNuDet->AddNode(PillarVol,2, new TGeoTranslation(fMagnetX/2-fPillarX/2,-fMagnetY/2-fPillarY/2, fCenterZ-fMagnetZ/2+fPillarZ/2)); - tTauNuDet->AddNode(PillarVol,3, new TGeoTranslation(-fMagnetX/2+fPillarX/2,-fMagnetY/2-fPillarY/2, fCenterZ+fMagnetZ/2-fPillarZ/2)); - tTauNuDet->AddNode(PillarVol,4, new TGeoTranslation(fMagnetX/2-fPillarX/2,-fMagnetY/2-fPillarY/2, fCenterZ+fMagnetZ/2-fPillarZ/2)); + TGeoUniformMagField* magField1 = new TGeoUniformMagField(-fField, 0., 0.); // magnetic field in Magnet pillars + + TGeoVolumeAssembly* MagnetVol = new TGeoVolumeAssembly("Davide"); + tTauNuDet->AddNode(MagnetVol, 1, new TGeoTranslation(0, 0, fCenterZ)); + + // The -0.01*mm is only for drawing reasons + [[maybe_unused]] auto* LateralBox = new TGeoBBox("LB", fBaseZ / 2, fBaseY / 2, (fBaseX - 0.01 * mm) / 2); + TGeoTube* CoilBox = new TGeoTube("C", 0, fCoilR, fCoilH1 / 2); + + TGeoCompositeShape* LateralSurf = new TGeoCompositeShape("LS", "LB-C"); + + TGeoVolume* CoilVol = new TGeoVolume("CoilVol", CoilBox, Cu); + CoilVol->SetLineColor(kGreen); + TGeoVolume* LateralSurfVol = new TGeoVolume("LateralSurfVol", LateralSurf, Fe); + LateralSurfVol->SetLineColor(kRed); + + TGeoRotation* r1 = new TGeoRotation(); + r1->RotateY(90); + // r1->RotateY(90); + // r1->RotateY(90); + r1->RegisterYourself(); + + TGeoCombiTrans* trans1r = new TGeoCombiTrans(-fMagnetX / 2 + fBaseX / 2, 0, 0, r1); + TGeoCombiTrans* trans1l = new TGeoCombiTrans(fMagnetX / 2 - fBaseX / 2, 0, 0, r1); + TGeoHMatrix* m1_r = new TGeoHMatrix("m1_r"); + *m1_r = trans1r; + TGeoHMatrix* m1_l = new TGeoHMatrix("m1_l"); + *m1_l = trans1l; + + MagnetVol->AddNode(CoilVol, 1, m1_r); + MagnetVol->AddNode(LateralSurfVol, 1, m1_r); + MagnetVol->AddNode(CoilVol, 2, m1_l); + MagnetVol->AddNode(LateralSurfVol, 2, m1_l); + + TGeoBBox* ColumnBox = new TGeoBBox(fColumnX / 2, fColumnY / 2, fColumnZ / 2); + TGeoVolume* ColumnVol = new TGeoVolume("ColumnVol", ColumnBox, Fe); + ColumnVol->SetField(magField1); + ColumnVol->SetLineColor(kRed); + MagnetVol->AddNode( + ColumnVol, 1, new TGeoTranslation(0, fMagnetY / 2 - fColumnY / 2, -fMagnetZ / 2 + fColumnZ / 2)); + MagnetVol->AddNode( + ColumnVol, 2, new TGeoTranslation(0, fMagnetY / 2 - fColumnY / 2, fMagnetZ / 2 - fColumnZ / 2)); + MagnetVol->AddNode( + ColumnVol, 3, new TGeoTranslation(0, -fMagnetY / 2 + fColumnY / 2, -fMagnetZ / 2 + fColumnZ / 2)); + MagnetVol->AddNode( + ColumnVol, 4, new TGeoTranslation(0, -fMagnetY / 2 + fColumnY / 2, fMagnetZ / 2 - fColumnZ / 2)); + + TGeoBBox* BaseBox = new TGeoBBox(fCoilDist / 2, fColumnY / 2, fBaseZ / 2); + TGeoVolume* BaseVol = new TGeoVolume("BaseVol", BaseBox, Fe); + BaseVol->SetLineColor(kRed); + MagnetVol->AddNode(BaseVol, 1, new TGeoTranslation(0, -fMagnetY / 2 + fColumnY / 2, 0)); + + TGeoBBox* PillarBox = new TGeoBBox(fPillarX / 2, fPillarY / 2, fPillarZ / 2); + TGeoVolume* PillarVol = new TGeoVolume("PillarVol", PillarBox, Steel); + PillarVol->SetLineColor(kGreen + 3); + tTauNuDet->AddNode(PillarVol, + 1, + new TGeoTranslation(-fMagnetX / 2 + fPillarX / 2, + -fMagnetY / 2 - fPillarY / 2, + fCenterZ - fMagnetZ / 2 + fPillarZ / 2)); + tTauNuDet->AddNode(PillarVol, + 2, + new TGeoTranslation(fMagnetX / 2 - fPillarX / 2, + -fMagnetY / 2 - fPillarY / 2, + fCenterZ - fMagnetZ / 2 + fPillarZ / 2)); + tTauNuDet->AddNode(PillarVol, + 3, + new TGeoTranslation(-fMagnetX / 2 + fPillarX / 2, + -fMagnetY / 2 - fPillarY / 2, + fCenterZ + fMagnetZ / 2 - fPillarZ / 2)); + tTauNuDet->AddNode(PillarVol, + 4, + new TGeoTranslation(fMagnetX / 2 - fPillarX / 2, + -fMagnetY / 2 - fPillarY / 2, + fCenterZ + fMagnetZ / 2 - fPillarZ / 2)); } - if(fDesign==3) //NEW with magnet + if (fDesign == 3) // NEW with magnet { - //Box for Magnet - TGeoVolumeAssembly *MagnetVol = new TGeoVolumeAssembly("NudetMagnet"); - tTauNuDet->AddNode(MagnetVol,1,new TGeoTranslation(0,0,fCenterZ)); - - TGeoBBox *BaseBox = new TGeoBBox(fBaseX/2,fBaseY/2,fBaseZ/2); - TGeoVolume *BaseVol = new TGeoVolume("BaseVol",BaseBox,Fe); - BaseVol->SetLineColor(kRed); - TGeoBBox *LateralBox = new TGeoBBox(fColumnX/2,fColumnY/2,fColumnZ/2); - - //prepare for triangolar cuts - LateralBox->SetName("L"); - Double_t delta = 0.1; //to avoid border effects in the cuts (cut is not visualized in viewer, I do not know if it can affect simulation) - TGeoTrd2 * Model= new TGeoTrd2("Model",fCutHeight/2,0, (fColumnZ+delta)/2,(fColumnZ+delta)/2,(fCutLength+delta)/2); //length and height are not x and y here, because it will be rotated! - Model->SetName("T"); - - const Double_t SemiLateralBoxHeight =(fColumnY - fCutHeight)/2; - - //we need different volumes to place different magnetic fields - TGeoBBox *SemiLateralBox = new TGeoBBox("SemiLateralBox",(fColumnX)/2, SemiLateralBoxHeight /2, fColumnZ/2); - TGeoVolume *volUpLateral = new TGeoVolume("volUpLateral",SemiLateralBox,Fe); //up and down refer to the magnetic field verse - - TGeoVolume *volDownLateral = new TGeoVolume("volDownLateral",SemiLateralBox,Fe); - SemiLateralBox->SetName("S"); - volUpLateral->SetLineColor(kRed); - volDownLateral->SetLineColor(kRed); - - const Double_t MidBoxHeight = fCutHeight/2; - - TGeoBBox *MidLateralBox = new TGeoBBox("MidLateralBox",fColumnX/2, MidBoxHeight/2, fColumnZ/2); - MidLateralBox->SetName("M"); - - //some boolean operations for triangular cuts - - TGeoRotation rot("rot",90,90,0); - TGeoRotation rot1("rot1",-90,90,0); - const TGeoTranslation trans("trans",-fColumnX/2.+ fCutLength/2,0,0); - TGeoCombiTrans* comb = new TGeoCombiTrans(trans,rot); - comb->SetName("comb"); - comb->RegisterYourself(); - [[maybe_unused]] auto *cut = new TGeoCompositeShape("CUT", "L-T:comb"); - - - TGeoTranslation* transcuttop = new TGeoTranslation("transcuttop",0, fCutHeight/2 + SemiLateralBoxHeight/2 ,0); //top and bottom refer to their geometrical positions - TGeoTranslation* transcuttop1 = new TGeoTranslation("transcuttop1",0, MidBoxHeight/2 ,0); - TGeoTranslation* transcutbottom = new TGeoTranslation("transcutbottom",0, - fCutHeight/2 - SemiLateralBoxHeight/2 ,0); - TGeoTranslation* transcutbottom1 = new TGeoTranslation("transcutbottom1",0, -MidBoxHeight/2 ,0); - - transcuttop->RegisterYourself(); - transcuttop1->RegisterYourself(); - transcutbottom->RegisterYourself(); - transcutbottom1->RegisterYourself(); - - TGeoCompositeShape *cuttop = new TGeoCompositeShape("CUTTOP", "CUT - (S:transcuttop) - (S:transcutbottom)"); //triangular cut in the right lateral wall - TGeoVolume *volcuttop = new TGeoVolume("volcuttop", cuttop, Fe); - volcuttop->SetLineColor(kRed); - - const TGeoTranslation transleft("transleft",+fColumnX/2.- fCutLength/2,0,0); - TGeoCombiTrans* combleft = new TGeoCombiTrans(transleft,rot1); - combleft->SetName("combleft"); - combleft->RegisterYourself(); - [[maybe_unused]] auto *cutleft = new TGeoCompositeShape("CUTLEFT", "L-T:combleft"); - TGeoCompositeShape *cuttopleft = new TGeoCompositeShape("CUTTOPLEFT", "CUTLEFT - (S:transcuttop) - (S:transcutbottom)"); //triangular cut in the left lateral wall - TGeoVolume *volcuttopleft = new TGeoVolume("volcuttopleft", cuttopleft, Fe); - volcuttopleft->SetLineColor(kRed); - - //composite coil - TGeoBBox *IncoilBox = new TGeoBBox("IC", fCoilX/2,fCoilH2/2,(fMagnetZ-fCoilH1)/2); - - //circular arcs (first two options are radii, not half radii!) - Double_t OuterRadius = fCoilY + fCoilThickness; - - [[maybe_unused]] auto *Coillateraltuberightdown = new TGeoTubeSeg("Coillateraltuberightdown",fCoilThickness,OuterRadius, fCoilX/2,90,180); - [[maybe_unused]] auto *Coillateraltuberighttup = new TGeoTubeSeg("Coillateraltuberightup",fCoilThickness,OuterRadius, fCoilX/2,0,90); - [[maybe_unused]] auto *Coillateraltubeleftup = new TGeoTubeSeg("Coillateraltubeleftup",fCoilThickness,OuterRadius, fCoilX/2,270,360); - [[maybe_unused]] auto *Coillateraltubeleftdown = new TGeoTubeSeg("Coillateraltubeleftdown",fCoilThickness,OuterRadius, fCoilX/2,180,270); - [[maybe_unused]] auto *Coillateralcenter = new TGeoBBox("Coillateralcenter",fCoilX/2., (fCoilH2-2*fCoilThickness)/2, fCoilY/2.); - - TGeoRotation rottube("rottube",90,90,0); - //transformations to combine them - const TGeoTranslation transtube("transtube",0.,-(fCoilH2-2*fCoilThickness)/2, -fCoilThickness-fCoilY/2); - const TGeoTranslation transtube1("transtube1",0.,(fCoilH2-2*fCoilThickness)/2, -fCoilThickness-fCoilY/2); - const TGeoTranslation transtube2("transtube2",0.,-(fCoilH2-2*fCoilThickness)/2,+fCoilThickness+fCoilY/2); - const TGeoTranslation transtube3("transtube3",0.,(fCoilH2-2*fCoilThickness)/2,+fCoilThickness+fCoilY/2); - TGeoCombiTrans* combination = new TGeoCombiTrans(transtube,rottube); - TGeoCombiTrans* combination1 = new TGeoCombiTrans(transtube1,rottube); - TGeoCombiTrans* combination2 = new TGeoCombiTrans(transtube2,rottube); - TGeoCombiTrans* combination3 = new TGeoCombiTrans(transtube3,rottube); - - combination->SetName("combination"); - combination->RegisterYourself(); - combination1->SetName("combination1"); - combination1->RegisterYourself(); - combination2->SetName("combination2"); - combination2->RegisterYourself(); - combination3->SetName("combination3"); - combination3->RegisterYourself(); - //adding the shapes and making the volumes - TGeoCompositeShape * CoilRight = new TGeoCompositeShape("CoilRight","Coillateraltuberightdown:combination+Coillateraltuberightup:combination1+Coillateralcenter"); - TGeoVolume *CoilVolright = new TGeoVolume("CoilVolright",CoilRight,Cu); - - TGeoCompositeShape * CoilLeft = new TGeoCompositeShape("CoilLeft","Coillateraltubeleftdown:combination2+Coillateraltubeleftup:combination3+Coillateralcenter"); - TGeoVolume *CoilVolleft = new TGeoVolume("CoilVolleft",CoilLeft,Cu); - - - - TGeoBBox *Coil = new TGeoBBox("Coil", fCoilX/2,fCoilY/2, (fMagnetZ-2*OuterRadius)/2); //two times the external radius - TGeoVolume *CoilVol = new TGeoVolume("CoilVol",Coil, Cu); - - //adding obtained volumes - - MagnetVol->AddNode(BaseVol,1, new TGeoTranslation(0,-fMagnetY/2+fBaseY/2,0)); - MagnetVol->AddNode(BaseVol,2, new TGeoTranslation(0,fMagnetY/2-fBaseY/2,0)); - - MagnetVol->AddNode(volUpLateral, 1, new TGeoTranslation(-fMagnetX/2+fColumnX/2, (fCutHeight + (fColumnY - fCutHeight)/2)/2 ,0)); - MagnetVol->AddNode(volDownLateral, 1, new TGeoTranslation(-fMagnetX/2+fColumnX/2, (-fCutHeight - (fColumnY - fCutHeight)/2)/2,0)); - MagnetVol->AddNode(volcuttop, 1, new TGeoTranslation(-fMagnetX/2+fColumnX/2, 0, 0)); - - MagnetVol->AddNode(volUpLateral, 2, new TGeoTranslation(fMagnetX/2-fColumnX/2, (-fCutHeight - (fColumnY - fCutHeight)/2)/2 ,0)); - MagnetVol->AddNode(volDownLateral, 2, new TGeoTranslation(fMagnetX/2-fColumnX/2, (+fCutHeight + (fColumnY - fCutHeight)/2)/2,0)); - MagnetVol->AddNode(volcuttopleft,2, new TGeoTranslation(fMagnetX/2-fColumnX/2,0,0)); - - CoilVolleft->SetLineColor(kGreen); - MagnetVol->AddNode(CoilVolleft,1,new TGeoTranslation(0,0,-fMagnetZ/2.+fCoilY/2.)); - CoilVolright->SetLineColor(kGreen); - MagnetVol->AddNode(CoilVolright,1,new TGeoTranslation(0,0,+fMagnetZ/2.-fCoilY/2.)); - CoilVol->SetLineColor(kGreen); - MagnetVol->AddNode(CoilVol,1,new TGeoTranslation(0,(fCoilH1+fCoilH2)/4,0)); - MagnetVol->AddNode(CoilVol,2,new TGeoTranslation(0,-(fCoilH1+fCoilH2)/4,0)); - - //magnetized region - - TGeoVolume *volMagRegion = new TGeoVolume("volMagRegion",IncoilBox, air); - MagnetVol->AddNode(volMagRegion, 1, new TGeoTranslation(0,0,0)); - - //pillars for the magnet - TGeoBBox *PillarBox = new TGeoBBox(fPillarX/2,fPillarY/2, fPillarZ/2); - TGeoVolume *PillarVol = new TGeoVolume("PillarVol",PillarBox,Steel); - PillarVol->SetLineColor(kGreen+3); - tTauNuDet->AddNode(PillarVol,1, new TGeoTranslation(-fMagnetX/2+fPillarX/2,-fMagnetY/2-fPillarY/2, fCenterZ-fMagnetZ/2+fPillarZ/2)); - tTauNuDet->AddNode(PillarVol,2, new TGeoTranslation(fMagnetX/2-fPillarX/2,-fMagnetY/2-fPillarY/2, fCenterZ-fMagnetZ/2+fPillarZ/2)); - tTauNuDet->AddNode(PillarVol,3, new TGeoTranslation(-fMagnetX/2+fPillarX/2,-fMagnetY/2-fPillarY/2, fCenterZ+fMagnetZ/2-fPillarZ/2)); - tTauNuDet->AddNode(PillarVol,4, new TGeoTranslation(fMagnetX/2-fPillarX/2,-fMagnetY/2-fPillarY/2, fCenterZ+fMagnetZ/2-fPillarZ/2)); - - - if (fConstField){ //adding magnetic field if not implemented from nudet field map - TGeoUniformMagField *magField1 = new TGeoUniformMagField(-fField,0.,0.); //magnetic field in Magnet pillars - TGeoUniformMagField *magField2 = new TGeoUniformMagField(fField,0.,0.); //magnetic field in target - TGeoUniformMagField *magField1y = new TGeoUniformMagField(0.,-fField,0.); //down return magnetic field along y - TGeoUniformMagField *magField2y = new TGeoUniformMagField(0.,fField,0.); //up return magnetic field along y - - BaseVol->SetField(magField1); - volUpLateral->SetField(magField2y); - volDownLateral->SetField(magField1y); - volMagRegion->SetField(magField2); - } + // Box for Magnet + TGeoVolumeAssembly* MagnetVol = new TGeoVolumeAssembly("NudetMagnet"); + tTauNuDet->AddNode(MagnetVol, 1, new TGeoTranslation(0, 0, fCenterZ)); + + TGeoBBox* BaseBox = new TGeoBBox(fBaseX / 2, fBaseY / 2, fBaseZ / 2); + TGeoVolume* BaseVol = new TGeoVolume("BaseVol", BaseBox, Fe); + BaseVol->SetLineColor(kRed); + TGeoBBox* LateralBox = new TGeoBBox(fColumnX / 2, fColumnY / 2, fColumnZ / 2); + + // prepare for triangolar cuts + LateralBox->SetName("L"); + Double_t delta = 0.1; // to avoid border effects in the cuts (cut is not visualized in viewer, I do not know + // if it can affect simulation) + TGeoTrd2* Model = new TGeoTrd2( + "Model", + fCutHeight / 2, + 0, + (fColumnZ + delta) / 2, + (fColumnZ + delta) / 2, + (fCutLength + delta) / 2); // length and height are not x and y here, because it will be rotated! + Model->SetName("T"); + + const Double_t SemiLateralBoxHeight = (fColumnY - fCutHeight) / 2; + + // we need different volumes to place different magnetic fields + TGeoBBox* SemiLateralBox = + new TGeoBBox("SemiLateralBox", (fColumnX) / 2, SemiLateralBoxHeight / 2, fColumnZ / 2); + TGeoVolume* volUpLateral = + new TGeoVolume("volUpLateral", SemiLateralBox, Fe); // up and down refer to the magnetic field verse + + TGeoVolume* volDownLateral = new TGeoVolume("volDownLateral", SemiLateralBox, Fe); + SemiLateralBox->SetName("S"); + volUpLateral->SetLineColor(kRed); + volDownLateral->SetLineColor(kRed); + + const Double_t MidBoxHeight = fCutHeight / 2; + + TGeoBBox* MidLateralBox = new TGeoBBox("MidLateralBox", fColumnX / 2, MidBoxHeight / 2, fColumnZ / 2); + MidLateralBox->SetName("M"); + + // some boolean operations for triangular cuts + + TGeoRotation rot("rot", 90, 90, 0); + TGeoRotation rot1("rot1", -90, 90, 0); + const TGeoTranslation trans("trans", -fColumnX / 2. + fCutLength / 2, 0, 0); + TGeoCombiTrans* comb = new TGeoCombiTrans(trans, rot); + comb->SetName("comb"); + comb->RegisterYourself(); + [[maybe_unused]] auto* cut = new TGeoCompositeShape("CUT", "L-T:comb"); + + TGeoTranslation* transcuttop = new TGeoTranslation("transcuttop", + 0, + fCutHeight / 2 + SemiLateralBoxHeight / 2, + 0); // top and bottom refer to their geometrical positions + TGeoTranslation* transcuttop1 = new TGeoTranslation("transcuttop1", 0, MidBoxHeight / 2, 0); + TGeoTranslation* transcutbottom = + new TGeoTranslation("transcutbottom", 0, -fCutHeight / 2 - SemiLateralBoxHeight / 2, 0); + TGeoTranslation* transcutbottom1 = new TGeoTranslation("transcutbottom1", 0, -MidBoxHeight / 2, 0); + + transcuttop->RegisterYourself(); + transcuttop1->RegisterYourself(); + transcutbottom->RegisterYourself(); + transcutbottom1->RegisterYourself(); + + TGeoCompositeShape* cuttop = new TGeoCompositeShape( + "CUTTOP", "CUT - (S:transcuttop) - (S:transcutbottom)"); // triangular cut in the right lateral wall + TGeoVolume* volcuttop = new TGeoVolume("volcuttop", cuttop, Fe); + volcuttop->SetLineColor(kRed); + + const TGeoTranslation transleft("transleft", +fColumnX / 2. - fCutLength / 2, 0, 0); + TGeoCombiTrans* combleft = new TGeoCombiTrans(transleft, rot1); + combleft->SetName("combleft"); + combleft->RegisterYourself(); + [[maybe_unused]] auto* cutleft = new TGeoCompositeShape("CUTLEFT", "L-T:combleft"); + TGeoCompositeShape* cuttopleft = new TGeoCompositeShape( + "CUTTOPLEFT", + "CUTLEFT - (S:transcuttop) - (S:transcutbottom)"); // triangular cut in the left lateral wall + TGeoVolume* volcuttopleft = new TGeoVolume("volcuttopleft", cuttopleft, Fe); + volcuttopleft->SetLineColor(kRed); + + // composite coil + TGeoBBox* IncoilBox = new TGeoBBox("IC", fCoilX / 2, fCoilH2 / 2, (fMagnetZ - fCoilH1) / 2); + + // circular arcs (first two options are radii, not half radii!) + Double_t OuterRadius = fCoilY + fCoilThickness; + + [[maybe_unused]] auto* Coillateraltuberightdown = + new TGeoTubeSeg("Coillateraltuberightdown", fCoilThickness, OuterRadius, fCoilX / 2, 90, 180); + [[maybe_unused]] auto* Coillateraltuberighttup = + new TGeoTubeSeg("Coillateraltuberightup", fCoilThickness, OuterRadius, fCoilX / 2, 0, 90); + [[maybe_unused]] auto* Coillateraltubeleftup = + new TGeoTubeSeg("Coillateraltubeleftup", fCoilThickness, OuterRadius, fCoilX / 2, 270, 360); + [[maybe_unused]] auto* Coillateraltubeleftdown = + new TGeoTubeSeg("Coillateraltubeleftdown", fCoilThickness, OuterRadius, fCoilX / 2, 180, 270); + [[maybe_unused]] auto* Coillateralcenter = + new TGeoBBox("Coillateralcenter", fCoilX / 2., (fCoilH2 - 2 * fCoilThickness) / 2, fCoilY / 2.); + + TGeoRotation rottube("rottube", 90, 90, 0); + // transformations to combine them + const TGeoTranslation transtube( + "transtube", 0., -(fCoilH2 - 2 * fCoilThickness) / 2, -fCoilThickness - fCoilY / 2); + const TGeoTranslation transtube1( + "transtube1", 0., (fCoilH2 - 2 * fCoilThickness) / 2, -fCoilThickness - fCoilY / 2); + const TGeoTranslation transtube2( + "transtube2", 0., -(fCoilH2 - 2 * fCoilThickness) / 2, +fCoilThickness + fCoilY / 2); + const TGeoTranslation transtube3( + "transtube3", 0., (fCoilH2 - 2 * fCoilThickness) / 2, +fCoilThickness + fCoilY / 2); + TGeoCombiTrans* combination = new TGeoCombiTrans(transtube, rottube); + TGeoCombiTrans* combination1 = new TGeoCombiTrans(transtube1, rottube); + TGeoCombiTrans* combination2 = new TGeoCombiTrans(transtube2, rottube); + TGeoCombiTrans* combination3 = new TGeoCombiTrans(transtube3, rottube); + + combination->SetName("combination"); + combination->RegisterYourself(); + combination1->SetName("combination1"); + combination1->RegisterYourself(); + combination2->SetName("combination2"); + combination2->RegisterYourself(); + combination3->SetName("combination3"); + combination3->RegisterYourself(); + // adding the shapes and making the volumes + TGeoCompositeShape* CoilRight = new TGeoCompositeShape( + "CoilRight", "Coillateraltuberightdown:combination+Coillateraltuberightup:combination1+Coillateralcenter"); + TGeoVolume* CoilVolright = new TGeoVolume("CoilVolright", CoilRight, Cu); + + TGeoCompositeShape* CoilLeft = new TGeoCompositeShape( + "CoilLeft", "Coillateraltubeleftdown:combination2+Coillateraltubeleftup:combination3+Coillateralcenter"); + TGeoVolume* CoilVolleft = new TGeoVolume("CoilVolleft", CoilLeft, Cu); + + TGeoBBox* Coil = new TGeoBBox( + "Coil", fCoilX / 2, fCoilY / 2, (fMagnetZ - 2 * OuterRadius) / 2); // two times the external radius + TGeoVolume* CoilVol = new TGeoVolume("CoilVol", Coil, Cu); + + // adding obtained volumes + + MagnetVol->AddNode(BaseVol, 1, new TGeoTranslation(0, -fMagnetY / 2 + fBaseY / 2, 0)); + MagnetVol->AddNode(BaseVol, 2, new TGeoTranslation(0, fMagnetY / 2 - fBaseY / 2, 0)); + + MagnetVol->AddNode( + volUpLateral, + 1, + new TGeoTranslation(-fMagnetX / 2 + fColumnX / 2, (fCutHeight + (fColumnY - fCutHeight) / 2) / 2, 0)); + MagnetVol->AddNode( + volDownLateral, + 1, + new TGeoTranslation(-fMagnetX / 2 + fColumnX / 2, (-fCutHeight - (fColumnY - fCutHeight) / 2) / 2, 0)); + MagnetVol->AddNode(volcuttop, 1, new TGeoTranslation(-fMagnetX / 2 + fColumnX / 2, 0, 0)); + + MagnetVol->AddNode( + volUpLateral, + 2, + new TGeoTranslation(fMagnetX / 2 - fColumnX / 2, (-fCutHeight - (fColumnY - fCutHeight) / 2) / 2, 0)); + MagnetVol->AddNode( + volDownLateral, + 2, + new TGeoTranslation(fMagnetX / 2 - fColumnX / 2, (+fCutHeight + (fColumnY - fCutHeight) / 2) / 2, 0)); + MagnetVol->AddNode(volcuttopleft, 2, new TGeoTranslation(fMagnetX / 2 - fColumnX / 2, 0, 0)); + + CoilVolleft->SetLineColor(kGreen); + MagnetVol->AddNode(CoilVolleft, 1, new TGeoTranslation(0, 0, -fMagnetZ / 2. + fCoilY / 2.)); + CoilVolright->SetLineColor(kGreen); + MagnetVol->AddNode(CoilVolright, 1, new TGeoTranslation(0, 0, +fMagnetZ / 2. - fCoilY / 2.)); + CoilVol->SetLineColor(kGreen); + MagnetVol->AddNode(CoilVol, 1, new TGeoTranslation(0, (fCoilH1 + fCoilH2) / 4, 0)); + MagnetVol->AddNode(CoilVol, 2, new TGeoTranslation(0, -(fCoilH1 + fCoilH2) / 4, 0)); + + // magnetized region + + TGeoVolume* volMagRegion = new TGeoVolume("volMagRegion", IncoilBox, air); + MagnetVol->AddNode(volMagRegion, 1, new TGeoTranslation(0, 0, 0)); + + // pillars for the magnet + TGeoBBox* PillarBox = new TGeoBBox(fPillarX / 2, fPillarY / 2, fPillarZ / 2); + TGeoVolume* PillarVol = new TGeoVolume("PillarVol", PillarBox, Steel); + PillarVol->SetLineColor(kGreen + 3); + tTauNuDet->AddNode(PillarVol, + 1, + new TGeoTranslation(-fMagnetX / 2 + fPillarX / 2, + -fMagnetY / 2 - fPillarY / 2, + fCenterZ - fMagnetZ / 2 + fPillarZ / 2)); + tTauNuDet->AddNode(PillarVol, + 2, + new TGeoTranslation(fMagnetX / 2 - fPillarX / 2, + -fMagnetY / 2 - fPillarY / 2, + fCenterZ - fMagnetZ / 2 + fPillarZ / 2)); + tTauNuDet->AddNode(PillarVol, + 3, + new TGeoTranslation(-fMagnetX / 2 + fPillarX / 2, + -fMagnetY / 2 - fPillarY / 2, + fCenterZ + fMagnetZ / 2 - fPillarZ / 2)); + tTauNuDet->AddNode(PillarVol, + 4, + new TGeoTranslation(fMagnetX / 2 - fPillarX / 2, + -fMagnetY / 2 - fPillarY / 2, + fCenterZ + fMagnetZ / 2 - fPillarZ / 2)); + + if (fConstField) { // adding magnetic field if not implemented from nudet field map + TGeoUniformMagField* magField1 = + new TGeoUniformMagField(-fField, 0., 0.); // magnetic field in Magnet pillars + TGeoUniformMagField* magField2 = new TGeoUniformMagField(fField, 0., 0.); // magnetic field in target + TGeoUniformMagField* magField1y = + new TGeoUniformMagField(0., -fField, 0.); // down return magnetic field along y + TGeoUniformMagField* magField2y = + new TGeoUniformMagField(0., fField, 0.); // up return magnetic field along y + + BaseVol->SetField(magField1); + volUpLateral->SetField(magField2y); + volDownLateral->SetField(magField1y); + volMagRegion->SetField(magField2); + } } } diff --git a/nutaudet/EmulsionMagnet.h b/nutaudet/EmulsionMagnet.h index 72942cf690..4e0b331356 100644 --- a/nutaudet/EmulsionMagnet.h +++ b/nutaudet/EmulsionMagnet.h @@ -6,9 +6,10 @@ #ifndef EmulsionMagnet_H #define EmulsionMagnet_H -#include "FairModule.h" // for FairModule -#include "Rtypes.h" // for ShipMuonShield::Class, Bool_t, etc +#include "FairModule.h" // for FairModule +#include "Rtypes.h" // for ShipMuonShield::Class, Bool_t, etc #include "TVector3.h" + #include using std::cout; @@ -16,59 +17,58 @@ using std::endl; class EmulsionMagnet : public FairModule { - public: - EmulsionMagnet(const char* name, const Double_t zC, const char* Title="EmulsionMagnet"); - EmulsionMagnet(); - ~EmulsionMagnet(); - - void SetGaps(Double_t Up, Double_t Down); - void SetMagnetSizes(Double_t X, Double_t Y, Double_t Z); - void SetMagnetColumn(Double_t ColX, Double_t ColY, Double_t ColZ); - void SetBaseDim(Double_t BaseX, Double_t BaseY, Double_t BaseZ); - void SetCoilParameters(Double_t radius, Double_t height1, Double_t height2, Double_t Distance); - void SetCoilParameters(Double_t X, Double_t Y, Double_t height1, Double_t height2, Double_t Thickness); - void SetDesign(Int_t Design); - void SetMagneticField(Double_t B); + public: + EmulsionMagnet(const char* name, const Double_t zC, const char* Title = "EmulsionMagnet"); + EmulsionMagnet(); + ~EmulsionMagnet(); - void SetPillarDimensions(Double_t X, Double_t Y, Double_t Z); - void SetCutDimensions(Double_t CutLength, Double_t CutHeight); + void SetGaps(Double_t Up, Double_t Down); + void SetMagnetSizes(Double_t X, Double_t Y, Double_t Z); + void SetMagnetColumn(Double_t ColX, Double_t ColY, Double_t ColZ); + void SetBaseDim(Double_t BaseX, Double_t BaseY, Double_t BaseZ); + void SetCoilParameters(Double_t radius, Double_t height1, Double_t height2, Double_t Distance); + void SetCoilParameters(Double_t X, Double_t Y, Double_t height1, Double_t height2, Double_t Thickness); + void SetDesign(Int_t Design); + void SetMagneticField(Double_t B); - void SetConstantField(Bool_t EmuMagnetConstField); + void SetPillarDimensions(Double_t X, Double_t Y, Double_t Z); + void SetCutDimensions(Double_t CutLength, Double_t CutHeight); - void ConstructGeometry(); - Int_t InitMedium(const char* name); + void SetConstantField(Bool_t EmuMagnetConstField); - ClassDef(EmulsionMagnet,5); + void ConstructGeometry(); + Int_t InitMedium(const char* name); - protected: + ClassDef(EmulsionMagnet, 5); - Double_t fMagnetX; - Double_t fMagnetY; - Double_t fMagnetZ; - Double_t fColumnX; - Double_t fColumnY; - Double_t fColumnZ; - Double_t fCutLength; //dimensions of triangular cuts for lateral volumes (only in NuTauTargetDesign 3) - Double_t fCutHeight; - Double_t fBaseX; - Double_t fBaseY; - Double_t fBaseZ; - Double_t fCenterZ; - Double_t fCoilR; - Double_t fCoilX; - Double_t fCoilY; - Double_t fCoilH1; //thickness of the upper (left) coil - Double_t fCoilH2; //thickness of the loweer (right) coil - Double_t fCoilDist; - Double_t fCoilThickness;//Thickness in Z config. fDesign==3 - Double_t fGapUpstream; - Double_t fGapDownstream; - Double_t fField; - Int_t fDesign; //0= TP_config, 1=new_config, 2=no magnet - Double_t fPillarX; - Double_t fPillarY; - Double_t fPillarZ; - Bool_t fConstField; + protected: + Double_t fMagnetX; + Double_t fMagnetY; + Double_t fMagnetZ; + Double_t fColumnX; + Double_t fColumnY; + Double_t fColumnZ; + Double_t fCutLength; // dimensions of triangular cuts for lateral volumes (only in NuTauTargetDesign 3) + Double_t fCutHeight; + Double_t fBaseX; + Double_t fBaseY; + Double_t fBaseZ; + Double_t fCenterZ; + Double_t fCoilR; + Double_t fCoilX; + Double_t fCoilY; + Double_t fCoilH1; // thickness of the upper (left) coil + Double_t fCoilH2; // thickness of the loweer (right) coil + Double_t fCoilDist; + Double_t fCoilThickness; // Thickness in Z config. fDesign==3 + Double_t fGapUpstream; + Double_t fGapDownstream; + Double_t fField; + Int_t fDesign; // 0= TP_config, 1=new_config, 2=no magnet + Double_t fPillarX; + Double_t fPillarY; + Double_t fPillarZ; + Bool_t fConstField; }; #endif diff --git a/nutaudet/HPT.cxx b/nutaudet/HPT.cxx index 09e9295c7a..bcf816f220 100644 --- a/nutaudet/HPT.cxx +++ b/nutaudet/HPT.cxx @@ -7,79 +7,76 @@ // #include "HPT.h" -#include "NuTauMudet.h" + +#include "FairGeoBuilder.h" +#include "FairGeoInterface.h" +#include "FairGeoLoader.h" +#include "FairGeoMedia.h" +#include "FairGeoNode.h" +#include "FairGeoVolume.h" +#include "FairRootManager.h" +#include "FairRun.h" // for FairRun +#include "FairRun.h" +#include "FairRuntimeDb.h" // for FairRuntimeDb +#include "FairRuntimeDb.h" +#include "FairVolume.h" #include "HptPoint.h" -#include "TGeoManager.h" -#include "FairRun.h" // for FairRun -#include "FairRuntimeDb.h" // for FairRuntimeDb -#include // for ostream -#include "TList.h" // for TListIter, TList (ptr only) -#include "TObjArray.h" // for TObjArray -#include "TString.h" // for TString +#include "NuTauMudet.h" +#include "ShipDetectorList.h" +#include "ShipStack.h" +#include "ShipUnit.h" #include "TClonesArray.h" -#include "TVirtualMC.h" - #include "TGeoBBox.h" -#include "TGeoTrd1.h" #include "TGeoCompositeShape.h" -#include "TGeoTube.h" +#include "TGeoManager.h" #include "TGeoMaterial.h" #include "TGeoMedium.h" +#include "TGeoTrd1.h" +#include "TGeoTube.h" +#include "TGeoUniformMagField.h" +#include "TList.h" // for TListIter, TList (ptr only) +#include "TObjArray.h" // for TObjArray #include "TParticle.h" +#include "TString.h" // for TString #include "TVector3.h" +#include "TVirtualMC.h" -#include "FairVolume.h" -#include "FairGeoVolume.h" -#include "FairGeoNode.h" -#include "FairRootManager.h" -#include "FairGeoLoader.h" -#include "FairGeoInterface.h" -#include "FairGeoMedia.h" -#include "FairGeoBuilder.h" -#include "FairRun.h" -#include "FairRuntimeDb.h" - -#include "ShipDetectorList.h" -#include "ShipUnit.h" -#include "ShipStack.h" - -#include "TGeoUniformMagField.h" -#include // for NULL -#include // for operator<<, basic_ostream, etc +#include // for ostream +#include // for operator<<, basic_ostream, etc +#include // for NULL using std::cout; using std::endl; using namespace ShipUnit; Hpt::Hpt() - : FairDetector("HighPrecisionTrackers",kTRUE, ktauHpt), - fTrackID(-1), - fPdgCode(), - fVolumeID(-1), - fPos(), - fMom(), - fTime(-1.), - fLength(-1.), - fELoss(-1), - fHptPointCollection(new TClonesArray("HptPoint")) -{ -} - -Hpt::Hpt(const char* name, const Double_t DX, const Double_t DY, const Double_t DZ, Bool_t Active,const char* Title) - : FairDetector(name, Active, ktauHpt), - fTrackID(-1), - fPdgCode(), - fVolumeID(-1), - fPos(), - fMom(), - fTime(-1.), - fLength(-1.), - fELoss(-1), - fHptPointCollection(new TClonesArray("HptPoint")) + : FairDetector("HighPrecisionTrackers", kTRUE, ktauHpt) + , fTrackID(-1) + , fPdgCode() + , fVolumeID(-1) + , fPos() + , fMom() + , fTime(-1.) + , fLength(-1.) + , fELoss(-1) + , fHptPointCollection(new TClonesArray("HptPoint")) +{} + +Hpt::Hpt(const char* name, const Double_t DX, const Double_t DY, const Double_t DZ, Bool_t Active, const char* Title) + : FairDetector(name, Active, ktauHpt) + , fTrackID(-1) + , fPdgCode() + , fVolumeID(-1) + , fPos() + , fMom() + , fTime(-1.) + , fLength(-1.) + , fELoss(-1) + , fHptPointCollection(new TClonesArray("HptPoint")) { - DimX = DX; - DimY = DY; - DimZ = DZ; + DimX = DX; + DimY = DY; + DimZ = DZ; } Hpt::~Hpt() @@ -95,74 +92,77 @@ void Hpt::Initialize() FairDetector::Initialize(); } -//Sets the dimension of the Magnetic Spectrometer volume in which the HPT are placed +// Sets the dimension of the Magnetic Spectrometer volume in which the HPT are placed void Hpt::SetZsize(const Double_t Mudetsize) { - zSizeMudet = Mudetsize; + zSizeMudet = Mudetsize; } -//Sets the dimension of the concrete base on which the external couples of HPTs are placed +// Sets the dimension of the concrete base on which the external couples of HPTs are placed void Hpt::SetConcreteBaseDim(Double_t X, Double_t Y, Double_t Z) { - fConcreteX = X; - fConcreteY = Y; - fConcreteZ = Z; + fConcreteX = X; + fConcreteY = Y; + fConcreteZ = Z; } -void Hpt::SetDistanceHPTs(Double_t dd) //only for geometry 3 +void Hpt::SetDistanceHPTs(Double_t dd) // only for geometry 3 { - fDistance = dd; + fDistance = dd; } void Hpt::SetHPTNumber(Int_t nHPT) { - fnHPT = nHPT; + fnHPT = nHPT; } void Hpt::SetDesign(Int_t Design) { - fDesign = Design; + fDesign = Design; } void Hpt::SetSurroundingDetHeight(Double_t height) { - fSRHeight = height; + fSRHeight = height; } void Hpt::GetMagnetGeometry(Double_t EmuzC, Double_t EmuY) { - fmagnetcenter = EmuzC; - fmagnety = EmuY; + fmagnetcenter = EmuzC; + fmagnety = EmuY; } -void Hpt::GetNumberofTargets(Int_t ntarget) //in nutautargetdesign 3 more than one neutrino target are considered +void Hpt::GetNumberofTargets(Int_t ntarget) // in nutautargetdesign 3 more than one neutrino target are considered { - fntarget = ntarget; + fntarget = ntarget; } // ----- Private method InitMedium Int_t Hpt::InitMedium(const char* name) { - static FairGeoLoader *geoLoad=FairGeoLoader::Instance(); - static FairGeoInterface *geoFace=geoLoad->getGeoInterface(); - static FairGeoMedia *media=geoFace->getMedia(); - static FairGeoBuilder *geoBuild=geoLoad->getGeoBuilder(); - - FairGeoMedium *ShipMedium=media->getMedium(name); - - if (!ShipMedium) - { - Fatal("InitMedium","Material %s not defined in media file.", name); - return -1111; - } - TGeoMedium* medium=gGeoManager->GetMedium(name); - if (medium!=NULL) - return ShipMedium->getMediumIndex(); - return geoBuild->createMedium(ShipMedium); + static FairGeoLoader* geoLoad = FairGeoLoader::Instance(); + static FairGeoInterface* geoFace = geoLoad->getGeoInterface(); + static FairGeoMedia* media = geoFace->getMedia(); + static FairGeoBuilder* geoBuild = geoLoad->getGeoBuilder(); + + FairGeoMedium* ShipMedium = media->getMedium(name); + + if (!ShipMedium) { + Fatal("InitMedium", "Material %s not defined in media file.", name); + return -1111; + } + TGeoMedium* medium = gGeoManager->GetMedium(name); + if (medium != NULL) + return ShipMedium->getMediumIndex(); + return geoBuild->createMedium(ShipMedium); } -void Hpt::SetSciFiParam(Double_t scifimat_width_, Double_t scifimat_hor_, Double_t scifimat_vert_, - Double_t scifimat_z_, Double_t support_z_, Double_t honeycomb_z_) +void Hpt::SetSciFiParam(Double_t scifimat_width_, + Double_t scifimat_hor_, + Double_t scifimat_vert_, + Double_t scifimat_z_, + Double_t support_z_, + Double_t honeycomb_z_) { scifimat_width = scifimat_width_; scifimat_hor = scifimat_hor_; @@ -174,8 +174,8 @@ void Hpt::SetSciFiParam(Double_t scifimat_width_, Double_t scifimat_hor_, Doubl void Hpt::SetNumberSciFi(Int_t n_hor_planes_, Int_t n_vert_planes_) { - n_hor_planes = n_hor_planes_; - n_vert_planes = n_vert_planes_; + n_hor_planes = n_hor_planes_; + n_vert_planes = n_vert_planes_; } void Hpt::SetHPTrackerParam(Double_t HPTX, Double_t HPTY, Double_t HPTZ) @@ -188,98 +188,108 @@ void Hpt::SetHPTrackerParam(Double_t HPTX, Double_t HPTY, Double_t HPTZ) void Hpt::ConstructGeometry() { InitMedium("HPTgas"); - TGeoMedium *HPTmat =gGeoManager->GetMedium("HPTgas"); + TGeoMedium* HPTmat = gGeoManager->GetMedium("HPTgas"); InitMedium("Concrete"); - TGeoMedium *Conc =gGeoManager->GetMedium("Concrete"); + TGeoMedium* Conc = gGeoManager->GetMedium("Concrete"); // cout << "zSizeMudet = " << zSizeMudet << endl; - if (fDesign < 3){ - TGeoVolume *volMudetBox = gGeoManager->GetVolume("volNuTauMudet"); - TGeoBBox *HPT = new TGeoBBox("HPT", DimX/2, DimY/2, DimZ/2); - TGeoVolume *volHPT = new TGeoVolume("volHPT",HPT,HPTmat); - volHPT->SetLineColor(kBlue-5); - AddSensitiveVolume(volHPT); - - TGeoBBox *Cbase = new TGeoBBox("Cbase", fConcreteX/2, fConcreteY/2, fConcreteZ/2); - TGeoVolume *volCbase = new TGeoVolume("volCbase",Cbase,Conc); - volCbase->SetLineColor(kOrange-7); - - //1 closer to Goliath - volMudetBox->AddNode(volHPT,1,new TGeoTranslation(0,0,-zSizeMudet/2 + DimZ/2)); - volMudetBox->AddNode(volCbase,1,new TGeoTranslation(0,-DimY/2-fConcreteY/2,-zSizeMudet/2 + DimZ/2)); - - //2 closer to Arm1 - //NB: 55 cm is the distance between the borders of the last 2 drift tubes - volMudetBox->AddNode(volHPT,2,new TGeoTranslation(0,0,-zSizeMudet/2 + 3*DimZ/2 +55*cm)); - volMudetBox->AddNode(volCbase,2,new TGeoTranslation(0,-DimY/2-fConcreteY/2,-zSizeMudet/2 + 3*DimZ/2 +55*cm)); - - //Central Drift tubes // 3 closer to Arm1, 4 closer to Arm2 - volMudetBox->AddNode(volHPT,3,new TGeoTranslation(0,0,-72*cm/2 - DimZ/2)); - - //NB: 72cm is the distance between the borders of the central drift tubes - volMudetBox->AddNode(volHPT,4,new TGeoTranslation(0,0,72*cm/2 + DimZ/2)); - - - //After spectro Drift Tubes 5 closer to Arm, 6 closer to decay vessel - volMudetBox->AddNode(volHPT,5,new TGeoTranslation(0,0,zSizeMudet/2 - 3*DimZ/2 - 55*cm)); - volMudetBox->AddNode(volCbase,5,new TGeoTranslation(0,-DimY/2-fConcreteY/2,zSizeMudet/2 - 3*DimZ/2 - 55*cm)); - - volMudetBox->AddNode(volHPT,6,new TGeoTranslation(0,0,zSizeMudet/2 - DimZ/2)); - volMudetBox->AddNode(volCbase,6,new TGeoTranslation(0,-DimY/2-fConcreteY/2,zSizeMudet/2 - DimZ/2)); - + if (fDesign < 3) { + TGeoVolume* volMudetBox = gGeoManager->GetVolume("volNuTauMudet"); + TGeoBBox* HPT = new TGeoBBox("HPT", DimX / 2, DimY / 2, DimZ / 2); + TGeoVolume* volHPT = new TGeoVolume("volHPT", HPT, HPTmat); + volHPT->SetLineColor(kBlue - 5); + AddSensitiveVolume(volHPT); + + TGeoBBox* Cbase = new TGeoBBox("Cbase", fConcreteX / 2, fConcreteY / 2, fConcreteZ / 2); + TGeoVolume* volCbase = new TGeoVolume("volCbase", Cbase, Conc); + volCbase->SetLineColor(kOrange - 7); + + // 1 closer to Goliath + volMudetBox->AddNode(volHPT, 1, new TGeoTranslation(0, 0, -zSizeMudet / 2 + DimZ / 2)); + volMudetBox->AddNode( + volCbase, 1, new TGeoTranslation(0, -DimY / 2 - fConcreteY / 2, -zSizeMudet / 2 + DimZ / 2)); + + // 2 closer to Arm1 + // NB: 55 cm is the distance between the borders of the last 2 drift tubes + volMudetBox->AddNode(volHPT, 2, new TGeoTranslation(0, 0, -zSizeMudet / 2 + 3 * DimZ / 2 + 55 * cm)); + volMudetBox->AddNode( + volCbase, 2, new TGeoTranslation(0, -DimY / 2 - fConcreteY / 2, -zSizeMudet / 2 + 3 * DimZ / 2 + 55 * cm)); + + // Central Drift tubes // 3 closer to Arm1, 4 closer to Arm2 + volMudetBox->AddNode(volHPT, 3, new TGeoTranslation(0, 0, -72 * cm / 2 - DimZ / 2)); + + // NB: 72cm is the distance between the borders of the central drift tubes + volMudetBox->AddNode(volHPT, 4, new TGeoTranslation(0, 0, 72 * cm / 2 + DimZ / 2)); + + // After spectro Drift Tubes 5 closer to Arm, 6 closer to decay vessel + volMudetBox->AddNode(volHPT, 5, new TGeoTranslation(0, 0, zSizeMudet / 2 - 3 * DimZ / 2 - 55 * cm)); + volMudetBox->AddNode( + volCbase, 5, new TGeoTranslation(0, -DimY / 2 - fConcreteY / 2, zSizeMudet / 2 - 3 * DimZ / 2 - 55 * cm)); + + volMudetBox->AddNode(volHPT, 6, new TGeoTranslation(0, 0, zSizeMudet / 2 - DimZ / 2)); + volMudetBox->AddNode( + volCbase, 6, new TGeoTranslation(0, -DimY / 2 - fConcreteY / 2, zSizeMudet / 2 - DimZ / 2)); } - if (fDesign == 3){ - //Trackers that in design 3 follow the target -------------------------------------------------------------------------------------- - TGeoVolume *volMagRegion=gGeoManager->GetVolume("volMagRegion"); - TGeoVolume *volTarget =gGeoManager->GetVolume("volTarget"); + if (fDesign == 3) { + // Trackers that in design 3 follow the target + // -------------------------------------------------------------------------------------- + TGeoVolume* volMagRegion = gGeoManager->GetVolume("volMagRegion"); + TGeoVolume* volTarget = gGeoManager->GetVolume("volTarget"); - Double_t DZMagnetizedRegion = static_cast (volMagRegion->GetShape())->GetDZ() *2; + Double_t DZMagnetizedRegion = static_cast(volMagRegion->GetShape())->GetDZ() * 2; - Double_t DZTarget = static_cast (volTarget->GetShape())->GetDZ() *2; + Double_t DZTarget = static_cast(volTarget->GetShape())->GetDZ() * 2; - //HPT is DownStreamTracker - TGeoBBox *DT = new TGeoBBox("DT", DimX/2, DimY/2, DimZ/2); - TGeoVolume *volDT = new TGeoVolume("volDT",DT,HPTmat); - volDT->SetLineColor(kBlue-5); + // HPT is DownStreamTracker + TGeoBBox* DT = new TGeoBBox("DT", DimX / 2, DimY / 2, DimZ / 2); + TGeoVolume* volDT = new TGeoVolume("volDT", DT, HPTmat); + volDT->SetLineColor(kBlue - 5); // Creating of SciFi modules in HPT InitMedium("CarbonComposite"); - TGeoMedium *CarbonComposite = gGeoManager->GetMedium("CarbonComposite"); + TGeoMedium* CarbonComposite = gGeoManager->GetMedium("CarbonComposite"); InitMedium("SciFiMat"); - TGeoMedium *SciFiMat = gGeoManager->GetMedium("SciFiMat"); + TGeoMedium* SciFiMat = gGeoManager->GetMedium("SciFiMat"); InitMedium("Airex"); - TGeoMedium *Airex = gGeoManager->GetMedium("Airex"); + TGeoMedium* Airex = gGeoManager->GetMedium("Airex"); - //Support Carbon Composite + // Support Carbon Composite TGeoBBox* HPT_support_box = new TGeoBBox("HPT_support_box", HPTrackerX / 2, HPTrackerY / 2, support_z / 2); TGeoVolume* HPT_support_volume = new TGeoVolume("HPT_support", HPT_support_box, CarbonComposite); HPT_support_volume->SetLineColor(kGray - 2); HPT_support_volume->SetVisibility(1); - //Honeycomb Airex (or Nomex) - TGeoBBox* HPT_honeycomb_box = new TGeoBBox("HPT_honeycomb_box", HPTrackerX / 2, HPTrackerY / 2, honeycomb_z / 2); + // Honeycomb Airex (or Nomex) + TGeoBBox* HPT_honeycomb_box = + new TGeoBBox("HPT_honeycomb_box", HPTrackerX / 2, HPTrackerY / 2, honeycomb_z / 2); TGeoVolume* HPT_honeycomb_volume = new TGeoVolume("HPT_honeycomb", HPT_honeycomb_box, Airex); HPT_honeycomb_volume->SetLineColor(kYellow); HPT_honeycomb_volume->SetVisibility(1); - //SciFi planes - TGeoBBox* HPT_scifi_plane_hor_box = new TGeoBBox("HPT_scifi_plane_hor_box", HPTrackerX / 2, HPTrackerY / 2, scifimat_z / 2); - TGeoVolume* HPT_scifi_plane_hor_volume = new TGeoVolume("HPT_scifi_plane_hor", HPT_scifi_plane_hor_box, SciFiMat); + // SciFi planes + TGeoBBox* HPT_scifi_plane_hor_box = + new TGeoBBox("HPT_scifi_plane_hor_box", HPTrackerX / 2, HPTrackerY / 2, scifimat_z / 2); + TGeoVolume* HPT_scifi_plane_hor_volume = + new TGeoVolume("HPT_scifi_plane_hor", HPT_scifi_plane_hor_box, SciFiMat); HPT_scifi_plane_hor_volume->SetVisibility(1); - TGeoBBox* HPT_scifi_plane_vert_box = new TGeoBBox("HPT_scifi_plane_vert_box", HPTrackerX / 2, HPTrackerY / 2, scifimat_z / 2); - TGeoVolume* HPT_scifi_plane_vert_volume = new TGeoVolume("HPT_scifi_plane_vert", HPT_scifi_plane_vert_box, SciFiMat); + TGeoBBox* HPT_scifi_plane_vert_box = + new TGeoBBox("HPT_scifi_plane_vert_box", HPTrackerX / 2, HPTrackerY / 2, scifimat_z / 2); + TGeoVolume* HPT_scifi_plane_vert_volume = + new TGeoVolume("HPT_scifi_plane_vert", HPT_scifi_plane_vert_box, SciFiMat); HPT_scifi_plane_vert_volume->SetVisibility(1); - //SciFi mats - TGeoBBox* HPT_scifimat_hor_box = new TGeoBBox("HPT_scifimat_hor_box", scifimat_hor / 2, scifimat_width / 2, scifimat_z / 2); + // SciFi mats + TGeoBBox* HPT_scifimat_hor_box = + new TGeoBBox("HPT_scifimat_hor_box", scifimat_hor / 2, scifimat_width / 2, scifimat_z / 2); TGeoVolume* HPT_scifimat_hor_volume = new TGeoVolume("HPT_scifimat_hor", HPT_scifimat_hor_box, SciFiMat); HPT_scifimat_hor_volume->SetLineColor(kCyan); - TGeoBBox* HPT_scifimat_vert_box = new TGeoBBox("HPT_scifimat_vert_box", scifimat_width / 2, scifimat_vert / 2, scifimat_z / 2); + TGeoBBox* HPT_scifimat_vert_box = + new TGeoBBox("HPT_scifimat_vert_box", scifimat_width / 2, scifimat_vert / 2, scifimat_z / 2); TGeoVolume* HPT_scifimat_vert_volume = new TGeoVolume("HPT_scifimat_vert", HPT_scifimat_vert_box, SciFiMat); HPT_scifimat_vert_volume->SetLineColor(kGreen); @@ -287,36 +297,55 @@ void Hpt::ConstructGeometry() AddSensitiveVolume(HPT_scifimat_vert_volume); // Creating physical volumes and multiply - for (int i = 0; i < n_hor_planes; i++){ - HPT_scifi_plane_hor_volume->AddNode(HPT_scifimat_hor_volume, i+1, new TGeoTranslation(0, (-(n_hor_planes-1)/2.0 + i)*scifimat_width, 0)); + for (int i = 0; i < n_hor_planes; i++) { + HPT_scifi_plane_hor_volume->AddNode( + HPT_scifimat_hor_volume, + i + 1, + new TGeoTranslation(0, (-(n_hor_planes - 1) / 2.0 + i) * scifimat_width, 0)); } - for (int i = 0; i < n_vert_planes; i++){ - HPT_scifi_plane_vert_volume->AddNode(HPT_scifimat_vert_volume, 100+i+1 , new TGeoTranslation((-(n_vert_planes-1)/2.0 + i)*scifimat_width, 0, 0)); + for (int i = 0; i < n_vert_planes; i++) { + HPT_scifi_plane_vert_volume->AddNode( + HPT_scifimat_vert_volume, + 100 + i + 1, + new TGeoTranslation((-(n_vert_planes - 1) / 2.0 + i) * scifimat_width, 0, 0)); } - volDT->AddNode(HPT_support_volume, 0, new TGeoTranslation(0, 0, - DimZ / 2 + support_z / 2)); - volDT->AddNode(HPT_scifi_plane_hor_volume, 0, new TGeoTranslation(0, 0, - DimZ / 2 + support_z + scifimat_z / 2)); - volDT->AddNode(HPT_scifi_plane_vert_volume, 0, new TGeoTranslation(0, 0, - DimZ / 2 + support_z + scifimat_z + scifimat_z / 2)); - volDT->AddNode(HPT_honeycomb_volume, 0, new TGeoTranslation(0, 0, - DimZ / 2 + support_z + 2 * scifimat_z + honeycomb_z / 2)); - volDT->AddNode(HPT_support_volume, 1, new TGeoTranslation(0, 0, - DimZ / 2 + support_z + 2 * scifimat_z + honeycomb_z + support_z / 2)); + volDT->AddNode(HPT_support_volume, 0, new TGeoTranslation(0, 0, -DimZ / 2 + support_z / 2)); + volDT->AddNode( + HPT_scifi_plane_hor_volume, 0, new TGeoTranslation(0, 0, -DimZ / 2 + support_z + scifimat_z / 2)); + volDT->AddNode(HPT_scifi_plane_vert_volume, + 0, + new TGeoTranslation(0, 0, -DimZ / 2 + support_z + scifimat_z + scifimat_z / 2)); + volDT->AddNode(HPT_honeycomb_volume, + 0, + new TGeoTranslation(0, 0, -DimZ / 2 + support_z + 2 * scifimat_z + honeycomb_z / 2)); + volDT->AddNode(HPT_support_volume, + 1, + new TGeoTranslation(0, 0, -DimZ / 2 + support_z + 2 * scifimat_z + honeycomb_z + support_z / 2)); ////////////////////////////////////////////////////////////// - Double_t first_DT_position = -DZMagnetizedRegion/2 + DZTarget + DimZ/2; - for(int i=0;iAddNode(volDT,(i+1)*1000+j*fnHPT,new TGeoTranslation(0,0, first_DT_position + i*(fDistance+DimZ) + j*(DZTarget+ fnHPT * DimZ + (fnHPT-1)*fDistance))); + Double_t first_DT_position = -DZMagnetizedRegion / 2 + DZTarget + DimZ / 2; + for (int i = 0; i < fnHPT; i++) { + for (int j = 0; j < fntarget; j++) { + volMagRegion->AddNode( + volDT, + (i + 1) * 1000 + j * fnHPT, + new TGeoTranslation(0, + 0, + first_DT_position + i * (fDistance + DimZ) + + j * (DZTarget + fnHPT * DimZ + (fnHPT - 1) * fDistance))); } } } } -Bool_t Hpt::ProcessHits(FairVolume* vol) +Bool_t Hpt::ProcessHits(FairVolume* vol) { /** This method is called from the MC stepping */ - //Set parameters at entrance of volume. Reset ELoss. - if ( gMC->IsTrackEntering() ) { - fELoss = 0.; - fTime = gMC->TrackTime() * 1.0e09; + // Set parameters at entrance of volume. Reset ELoss. + if (gMC->IsTrackEntering()) { + fELoss = 0.; + fTime = gMC->TrackTime() * 1.0e09; fLength = gMC->TrackLength(); gMC->TrackPosition(fPos); gMC->TrackMomentum(fMom); @@ -325,13 +354,13 @@ Bool_t Hpt::ProcessHits(FairVolume* vol) fELoss += gMC->Edep(); // Create muonPoint at exit of active volume - if ( gMC->IsTrackExiting() || - gMC->IsTrackStop() || - gMC->IsTrackDisappeared() ){ - if (fELoss == 0. ) { return kFALSE; } - TParticle* p=gMC->GetStack()->GetCurrentTrack(); + if (gMC->IsTrackExiting() || gMC->IsTrackStop() || gMC->IsTrackDisappeared()) { + if (fELoss == 0.) { + return kFALSE; + } + TParticle* p = gMC->GetStack()->GetCurrentTrack(); Int_t pdgCode = p->GetPdgCode(); - fTrackID = gMC->GetStack()->GetCurrentTrackNumber(); + fTrackID = gMC->GetStack()->GetCurrentTrackNumber(); gMC->CurrentVolID(fVolumeID); Int_t detID = fVolumeID; @@ -341,16 +370,21 @@ Bool_t Hpt::ProcessHits(FairVolume* vol) TLorentzVector Pos; gMC->TrackPosition(Pos); - Double_t xmean = (fPos.X()+Pos.X())/2. ; - Double_t ymean = (fPos.Y()+Pos.Y())/2. ; - Double_t zmean = (fPos.Z()+Pos.Z())/2. ; + Double_t xmean = (fPos.X() + Pos.X()) / 2.; + Double_t ymean = (fPos.Y() + Pos.Y()) / 2.; + Double_t zmean = (fPos.Z() + Pos.Z()) / 2.; - AddHit(fTrackID, fVolumeID, TVector3(xmean, ymean, zmean), + AddHit(fTrackID, + fVolumeID, + TVector3(xmean, ymean, zmean), TVector3(fMom.Px(), fMom.Py(), fMom.Pz()), - fTime, fLength,fELoss, pdgCode); + fTime, + fLength, + fELoss, + pdgCode); // Increment number of muon det points in TParticle - ShipStack* stack = (ShipStack*) gMC->GetStack(); + ShipStack* stack = (ShipStack*)gMC->GetStack(); stack->AddPoint(ktauRpc); } @@ -362,7 +396,6 @@ void Hpt::EndOfEvent() fHptPointCollection->Clear(); } - void Hpt::Register() { @@ -372,29 +405,31 @@ void Hpt::Register() only during the simulation. */ - FairRootManager::Instance()->Register("HptPoint", "Hpt", - fHptPointCollection, kTRUE); + FairRootManager::Instance()->Register("HptPoint", "Hpt", fHptPointCollection, kTRUE); } // ----- Public method to Decode volume info ------------------------------------------- // ----- returns hpt, arm, rpc numbers ----------------------------------- -void Hpt::DecodeVolumeID(Int_t detID,int &nHPT, int &nplane, Bool_t &ishor) +void Hpt::DecodeVolumeID(Int_t detID, int& nHPT, int& nplane, Bool_t& ishor) { - nHPT = detID/1000; - int idir = (detID - nHPT*1000)/100; - - if (idir == 1) ishor = kFALSE; - else if (idir == 0) ishor = kTRUE; - - nplane = (detID - nHPT*1000 - idir*100); + nHPT = detID / 1000; + int idir = (detID - nHPT * 1000) / 100; + if (idir == 1) + ishor = kFALSE; + else if (idir == 0) + ishor = kTRUE; + nplane = (detID - nHPT * 1000 - idir * 100); } TClonesArray* Hpt::GetCollection(Int_t iColl) const { - if (iColl == 0) { return fHptPointCollection; } - else { return NULL; } + if (iColl == 0) { + return fHptPointCollection; + } else { + return NULL; + } } void Hpt::Reset() @@ -402,15 +437,18 @@ void Hpt::Reset() fHptPointCollection->Clear(); } - -HptPoint* Hpt::AddHit(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t time, Double_t length, - Double_t eLoss, Int_t pdgCode) +HptPoint* Hpt::AddHit(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t time, + Double_t length, + Double_t eLoss, + Int_t pdgCode) { TClonesArray& clref = *fHptPointCollection; Int_t size = clref.GetEntriesFast(); - return new(clref[size]) HptPoint(trackID, detID, pos, mom,time, length, eLoss, pdgCode); + return new (clref[size]) HptPoint(trackID, detID, pos, mom, time, length, eLoss, pdgCode); } diff --git a/nutaudet/HPT.h b/nutaudet/HPT.h index 8d0f82678d..540fe6f433 100644 --- a/nutaudet/HPT.h +++ b/nutaudet/HPT.h @@ -1,38 +1,45 @@ #ifndef HPT_H #define HPT_H -#include "FairModule.h" // for FairModule -#include "FairDetector.h" // for FairDetector - -#include "Rtypes.h" // for ShipMuonShield::Class, Bool_t, etc - -#include // for string - -#include "TVector3.h" +#include "FairDetector.h" // for FairDetector +#include "FairModule.h" // for FairModule +#include "Rtypes.h" // for ShipMuonShield::Class, Bool_t, etc #include "TLorentzVector.h" +#include "TVector3.h" + +#include // for string class HptPoint; class FairVolume; class TClonesArray; -class Hpt:public FairDetector +class Hpt : public FairDetector { public: - Hpt(const char* name, const Double_t DX, const Double_t DY, const Double_t DZ,Bool_t Active, const char* Title="HighPrecisionTrackers"); + Hpt(const char* name, + const Double_t DX, + const Double_t DY, + const Double_t DZ, + Bool_t Active, + const char* Title = "HighPrecisionTrackers"); Hpt(); virtual ~Hpt(); void ConstructGeometry(); - void SetSciFiParam(Double_t scifimat_width, Double_t scifimat_hor, Double_t scifimat_vert, - Double_t scifimat_z, Double_t support_z, Double_t honeycomb_z); + void SetSciFiParam(Double_t scifimat_width, + Double_t scifimat_hor, + Double_t scifimat_vert, + Double_t scifimat_z, + Double_t support_z, + Double_t honeycomb_z); void SetHPTrackerParam(Double_t HPTX, Double_t HPTY, Double_t HPTZ); void SetNumberSciFi(Int_t n_hor_planes_, Int_t n_vert_planes_); void SetZsize(const Double_t Mudetsize); void SetConcreteBaseDim(Double_t X, Double_t Y, Double_t Z); void SetDesign(Int_t Design); - //methods for design 3 + // methods for design 3 void SetDistanceHPTs(Double_t dd); void SetHPTNumber(Int_t nHPT); void SetSurroundingDetHeight(Double_t height); @@ -45,70 +52,69 @@ class Hpt:public FairDetector /** this method is called for each step during simulation * (see FairMCApplication::Stepping()) */ - virtual Bool_t ProcessHits( FairVolume* v=0); + virtual Bool_t ProcessHits(FairVolume* v = 0); /** Registers the produced collections in FAIRRootManager. */ - virtual void Register(); + virtual void Register(); /** Gets the produced collections */ - virtual TClonesArray* GetCollection(Int_t iColl) const ; + virtual TClonesArray* GetCollection(Int_t iColl) const; /** has to be called after each event to reset the containers */ - virtual void Reset(); + virtual void Reset(); /** This method is an example of how to add your own point * of type muonPoint to the clones array */ - HptPoint* AddHit(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t time, Double_t length, - Double_t eLoss, Int_t pdgCode); + HptPoint* AddHit(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t time, + Double_t length, + Double_t eLoss, + Int_t pdgCode); /** The following methods can be implemented if you need to make * any optional action in your detector during the transport. */ - virtual void CopyClones( TClonesArray* cl1, TClonesArray* cl2 , - Int_t offset) {;} - virtual void SetSpecialPhysicsCuts() {;} - virtual void EndOfEvent(); - virtual void FinishPrimary() {;} - virtual void FinishRun() {;} - virtual void BeginPrimary() {;} - virtual void PostTrack() {;} - virtual void PreTrack() {;} - virtual void BeginEvent() {;} + virtual void CopyClones(TClonesArray* cl1, TClonesArray* cl2, Int_t offset) { ; } + virtual void SetSpecialPhysicsCuts() { ; } + virtual void EndOfEvent(); + virtual void FinishPrimary() { ; } + virtual void FinishRun() { ; } + virtual void BeginPrimary() { ; } + virtual void PostTrack() { ; } + virtual void PreTrack() { ; } + virtual void BeginEvent() { ; } - void DecodeVolumeID(Int_t detID,int &nHPT, int &nplane, Bool_t &ishor); - -private: + void DecodeVolumeID(Int_t detID, int& nHPT, int& nplane, Bool_t& ishor); + private: /** Track information to be stored until the track leaves the active volume. */ - Int_t fTrackID; //! track index - Int_t fPdgCode; //! pdg code - Int_t fVolumeID; //! volume id - TLorentzVector fPos; //! position at entrance - TLorentzVector fMom; //! momentum at entrance - Double32_t fTime; //! time - Double32_t fLength; //! length - Double32_t fELoss; //! energy loss + Int_t fTrackID; //! track index + Int_t fPdgCode; //! pdg code + Int_t fVolumeID; //! volume id + TLorentzVector fPos; //! position at entrance + TLorentzVector fMom; //! momentum at entrance + Double32_t fTime; //! time + Double32_t fLength; //! length + Double32_t fELoss; //! energy loss /** container for data points */ - TClonesArray* fHptPointCollection; + TClonesArray* fHptPointCollection; Int_t InitMedium(const char* name); - - -protected: - + protected: Double_t DimX; Double_t DimY; Double_t DimZ; - Double_t zSizeMudet; //dimension of the Muon Detector volume - Double_t fConcreteX; //dimesion of Concrete Base on which the external HPTs lie + Double_t zSizeMudet; // dimension of the Muon Detector volume + Double_t fConcreteX; // dimesion of Concrete Base on which the external HPTs lie Double_t fConcreteY; Double_t fConcreteZ; @@ -117,7 +123,7 @@ class Hpt:public FairDetector Double_t fDistance; Int_t fnHPT; - Double_t HPTrackerX; // parameters for Downstream SciFi Tracker + Double_t HPTrackerX; // parameters for Downstream SciFi Tracker Double_t HPTrackerY; Double_t HPTrackerZ; @@ -130,14 +136,13 @@ class Hpt:public FairDetector Int_t n_hor_planes; Int_t n_vert_planes; - Double_t fmagnety; //parameters from EmuMagnet + Double_t fmagnety; // parameters from EmuMagnet Double_t fmagnetcenter; Int_t fntarget; Hpt(const Hpt&); Hpt& operator=(const Hpt&); - ClassDef(Hpt,5) - + ClassDef(Hpt, 5) }; #endif diff --git a/nutaudet/HptPoint.cxx b/nutaudet/HptPoint.cxx index 58077bdfde..7074b10ffb 100644 --- a/nutaudet/HptPoint.cxx +++ b/nutaudet/HptPoint.cxx @@ -4,38 +4,37 @@ using std::cout; using std::endl; - // ----- Default constructor ------------------------------------------- HptPoint::HptPoint() - : FairMCPoint() -{ -} + : FairMCPoint() +{} // ------------------------------------------------------------------------- -HptPoint::HptPoint(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t tof, Double_t length, - Double_t eLoss, Int_t pdgcode) - : FairMCPoint(trackID, detID, pos, mom, tof, length, eLoss), fPdgCode(pdgcode) -{ -} +HptPoint::HptPoint(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t tof, + Double_t length, + Double_t eLoss, + Int_t pdgcode) + : FairMCPoint(trackID, detID, pos, mom, tof, length, eLoss) + , fPdgCode(pdgcode) +{} // ------------------------------------------------------------------------- // ----- Destructor ---------------------------------------------------- -HptPoint::~HptPoint() { } +HptPoint::~HptPoint() {} // ------------------------------------------------------------------------- // ----- Public method Print ------------------------------------------- void HptPoint::Print(const Option_t* opt) const { - cout << "-I- HptPoint: Hpt point for track " << fTrackID - << " in detector " << fDetectorID << endl; - cout << " Position (" << fX << ", " << fY << ", " << fZ - << ") cm" << endl; - cout << " Momentum (" << fPx << ", " << fPy << ", " << fPz - << ") GeV" << endl; - cout << " Time " << fTime << " ns, Length " << fLength - << " cm, Energy loss " << fELoss*1.0e06 << " keV" << endl; + cout << "-I- HptPoint: Hpt point for track " << fTrackID << " in detector " << fDetectorID << endl; + cout << " Position (" << fX << ", " << fY << ", " << fZ << ") cm" << endl; + cout << " Momentum (" << fPx << ", " << fPy << ", " << fPz << ") GeV" << endl; + cout << " Time " << fTime << " ns, Length " << fLength << " cm, Energy loss " << fELoss * 1.0e06 << " keV" + << endl; } // ------------------------------------------------------------------------- diff --git a/nutaudet/HptPoint.h b/nutaudet/HptPoint.h index 3f1af604dc..f68d6d534d 100644 --- a/nutaudet/HptPoint.h +++ b/nutaudet/HptPoint.h @@ -1,9 +1,7 @@ #ifndef HPTPOINT_H #define HPTPOINT_H 1 - #include "FairMCPoint.h" - #include "TObject.h" #include "TVector3.h" @@ -11,11 +9,9 @@ class HptPoint : public FairMCPoint { public: - /** Default constructor **/ HptPoint(); - /** Constructor with arguments *@param trackID Index of MCTrack *@param detID Detector ID @@ -26,18 +22,21 @@ class HptPoint : public FairMCPoint *@param eLoss Energy deposit [GeV] **/ - - HptPoint(Int_t trackID, Int_t detID, TVector3 pos, TVector3 mom, - Double_t tof, Double_t length, Double_t eLoss, Int_t pdgcode); - + HptPoint(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t tof, + Double_t length, + Double_t eLoss, + Int_t pdgcode); /** Destructor **/ virtual ~HptPoint(); /** Output to screen **/ virtual void Print(const Option_t* opt) const; - Int_t PdgCode() const {return fPdgCode;} - + Int_t PdgCode() const { return fPdgCode; } private: /** Copy constructor **/ @@ -46,8 +45,7 @@ class HptPoint : public FairMCPoint HptPoint(const HptPoint& point); HptPoint operator=(const HptPoint& point); - ClassDef(HptPoint,1) - + ClassDef(HptPoint, 1) }; #endif diff --git a/nutaudet/MagneticSpectrometer.cxx b/nutaudet/MagneticSpectrometer.cxx index 25b993f492..297ce505e7 100644 --- a/nutaudet/MagneticSpectrometer.cxx +++ b/nutaudet/MagneticSpectrometer.cxx @@ -1,608 +1,645 @@ #include "MagneticSpectrometer.h" + +#include "FairGeoBuilder.h" +#include "FairGeoInterface.h" +#include "FairGeoLoader.h" +#include "FairGeoMedia.h" +#include "FairGeoNode.h" +#include "FairGeoVolume.h" +#include "FairRootManager.h" +#include "FairRun.h" // for FairRun +#include "FairRun.h" +#include "FairRuntimeDb.h" // for FairRuntimeDb +#include "FairRuntimeDb.h" +#include "FairVolume.h" +#include "ShipDetectorList.h" #include "ShipRpcPoint.h" -#include "TGeoManager.h" -#include "FairRun.h" // for FairRun -#include "FairRuntimeDb.h" // for FairRuntimeDb -#include // for ostream -#include "TList.h" // for TListIter, TList (ptr only) -#include "TObjArray.h" // for TObjArray -#include "TString.h" // for TString +#include "ShipStack.h" +#include "ShipUnit.h" #include "TClonesArray.h" -#include "TVirtualMC.h" - #include "TGeoBBox.h" -#include "TGeoTrd1.h" #include "TGeoCompositeShape.h" -#include "TGeoTube.h" +#include "TGeoManager.h" #include "TGeoMaterial.h" #include "TGeoMedium.h" +#include "TGeoTrd1.h" +#include "TGeoTube.h" +#include "TGeoUniformMagField.h" +#include "TList.h" // for TListIter, TList (ptr only) +#include "TObjArray.h" // for TObjArray #include "TParticle.h" +#include "TString.h" // for TString #include "TVector3.h" +#include "TVirtualMC.h" -#include "FairVolume.h" -#include "FairGeoVolume.h" -#include "FairGeoNode.h" -#include "FairRootManager.h" -#include "FairGeoLoader.h" -#include "FairGeoInterface.h" -#include "FairGeoMedia.h" -#include "FairGeoBuilder.h" -#include "FairRun.h" -#include "FairRuntimeDb.h" - -#include "ShipDetectorList.h" -#include "ShipUnit.h" -#include "ShipStack.h" - -#include "TGeoUniformMagField.h" -#include // for NULL -#include // for operator<<, basic_ostream, etc +#include // for ostream +#include // for operator<<, basic_ostream, etc +#include // for NULL using std::cout; using std::endl; using namespace ShipUnit; MagneticSpectrometer::MagneticSpectrometer() - : FairDetector("MagneticSpectrometer",kTRUE, ktauRpc), - fTrackID(-1), - fPdgCode(), - fVolumeID(-1), - fPos(), - fMom(), - fTime(-1.), - fLength(-1.), - fELoss(-1), - fShipRpcPointCollection(new TClonesArray("ShipRpcPoint")) + : FairDetector("MagneticSpectrometer", kTRUE, ktauRpc) + , fTrackID(-1) + , fPdgCode() + , fVolumeID(-1) + , fPos() + , fMom() + , fTime(-1.) + , fLength(-1.) + , fELoss(-1) + , fShipRpcPointCollection(new TClonesArray("ShipRpcPoint")) +{} + +MagneticSpectrometer::MagneticSpectrometer(const char* name, const Double_t Zcenter, Bool_t Active, const char* Title) + : FairDetector(name, Active, ktauRpc) + , fTrackID(-1) + , fPdgCode() + , fVolumeID(-1) + , fPos() + , fMom() + , fTime(-1.) + , fLength(-1.) + , fELoss(-1) + , fShipRpcPointCollection(new TClonesArray("ShipRpcPoint")) { -} - -MagneticSpectrometer::MagneticSpectrometer(const char* name, const Double_t Zcenter,Bool_t Active,const char* Title) - : FairDetector(name, Active, ktauRpc), - fTrackID(-1), - fPdgCode(), - fVolumeID(-1), - fPos(), - fMom(), - fTime(-1.), - fLength(-1.), - fELoss(-1), - fShipRpcPointCollection(new TClonesArray("ShipRpcPoint")) -{ - fZcenter = Zcenter; + fZcenter = Zcenter; } void MagneticSpectrometer::SetDesign(Int_t Design) { - fDesign = Design; - cout <<" Mag Spectro Design "<< fDesign<Delete(); - delete fShipRpcPointCollection; - } + if (fShipRpcPointCollection) { + fShipRpcPointCollection->Delete(); + delete fShipRpcPointCollection; + } } void MagneticSpectrometer::Initialize() { - FairDetector::Initialize(); + FairDetector::Initialize(); } // ----- Private method InitMedium Int_t MagneticSpectrometer::InitMedium(const char* name) { - static FairGeoLoader *geoLoad=FairGeoLoader::Instance(); - static FairGeoInterface *geoFace=geoLoad->getGeoInterface(); - static FairGeoMedia *media=geoFace->getMedia(); - static FairGeoBuilder *geoBuild=geoLoad->getGeoBuilder(); + static FairGeoLoader* geoLoad = FairGeoLoader::Instance(); + static FairGeoInterface* geoFace = geoLoad->getGeoInterface(); + static FairGeoMedia* media = geoFace->getMedia(); + static FairGeoBuilder* geoBuild = geoLoad->getGeoBuilder(); - FairGeoMedium *ShipMedium=media->getMedium(name); + FairGeoMedium* ShipMedium = media->getMedium(name); - if (!ShipMedium) - { - Fatal("InitMedium","Material %s not defined in media file.", name); - return -1111; + if (!ShipMedium) { + Fatal("InitMedium", "Material %s not defined in media file.", name); + return -1111; } - TGeoMedium* medium=gGeoManager->GetMedium(name); - if (medium!=NULL) - return ShipMedium->getMediumIndex(); - return geoBuild->createMedium(ShipMedium); + TGeoMedium* medium = gGeoManager->GetMedium(name); + if (medium != NULL) + return ShipMedium->getMediumIndex(); + return geoBuild->createMedium(ShipMedium); } void MagneticSpectrometer::ConstructGeometry() { - TGeoVolume *top = gGeoManager->GetTopVolume(); - TGeoVolumeAssembly *tTauNuDet = new TGeoVolumeAssembly("tTauNuDet"); - top->AddNode(tTauNuDet, 1, new TGeoTranslation(0, 0, 0)); - - InitMedium("RPCgas"); - TGeoMedium *RPCmat =gGeoManager->GetMedium("RPCgas"); - - InitMedium("vacuum"); - TGeoMedium *vacuum =gGeoManager->GetMedium("vacuum"); - - InitMedium("Bakelite"); - TGeoMedium *bakelite =gGeoManager->GetMedium("Bakelite"); - - InitMedium("iron"); - TGeoMedium *Iron =gGeoManager->GetMedium("iron"); - - InitMedium("steel"); - TGeoMedium *Steel =gGeoManager->GetMedium("steel"); - - InitMedium("copper"); - TGeoMedium *Cu =gGeoManager->GetMedium("copper"); - - InitMedium("Concrete"); - TGeoMedium *Conc =gGeoManager->GetMedium("Concrete"); - - TGeoUniformMagField *retFieldU = new TGeoUniformMagField(0.,0.,-fField); //magnetic field up return yoke - TGeoUniformMagField *retFieldL = new TGeoUniformMagField(0.,0.,fField); //magnetic field low return yoke - - Double_t d = 0; - - if(fDesign!=3) - { - TGeoBBox *MSBox = new TGeoBBox("MagneticSpectrometerBox", fXRyoke/2, fYtot/2, fZtot/2); - TGeoVolume *volMSBox = new TGeoVolume("volMagneticSpectrometer", MSBox, vacuum); - tTauNuDet->AddNode(volMSBox, 1, new TGeoTranslation(0,10*cm,fZcenter)); - - - TGeoBBox *UpYokeBox = new TGeoBBox("UpYokeBox", fXRyoke/2, fYRyoke/2, fZRyoke/2); - TGeoVolume *volUpYoke = new TGeoVolume("volUpYoke",UpYokeBox,vacuum); - volMSBox->AddNode(volUpYoke,1,new TGeoTranslation(0,fYtot/2 - fYRyoke/2,0)); - volUpYoke->SetField(retFieldU); - - - TGeoBBox *FeYoke = new TGeoBBox("FeYoke",fXtot/2, fYRyoke/2, fZArm/2); - TGeoVolume *volFeYoke = new TGeoVolume("volFeYoke",FeYoke,Iron); - volFeYoke->SetLineColor(kGray+1); - - TGeoBBox *FeYoke1 = new TGeoBBox("FeYoke1",fXtot/2, fYRyoke_s/2, fZRyoke_s/2); - TGeoVolume *volFeYoke1 = new TGeoVolume("volFeYoke1",FeYoke1,Iron); - volFeYoke1->SetLineColor(kGray+1); - - TGeoBBox *CoilContainer = new TGeoBBox("CoilContainer",fXtot/2, fCoilH/2, 40*cm); - TGeoVolume *volCoilContainer = new TGeoVolume("volCoilContainer",CoilContainer,vacuum); - - TGeoBBox *Coil = new TGeoBBox("Coil",fXtot/2, fCoilH/2, fCoilW/2); - TGeoVolume *volCoil = new TGeoVolume("volCoil",Coil,Cu); - volCoil->SetLineColor(kOrange -5); - for(int i = 0; i < fNCoil; i++) - { - volCoilContainer->AddNode(volCoil, i, new TGeoTranslation(0,0, -40*cm + fCoilW/2 + i*(fCoilGap + fCoilW))); - } - - //vertical coils - TGeoBBox *CoilV = new TGeoBBox("CoilV",fCoilH/2, fYRyoke/2 , fCoilW/2); - TGeoVolume *volCoilV = new TGeoVolume("volCoilV",CoilV,Cu); - volCoilV->SetLineColor(kOrange -5); - for(int i = 0; i < fNCoil; i++) - { - volUpYoke->AddNode(volCoilV, i, new TGeoTranslation(fXRyoke/2 - fCoilH/2,0, -40*cm + fCoilW/2 + i*(fCoilGap + fCoilW))); - } - for(int i = 0; i < fNCoil; i++) - { - volUpYoke->AddNode(volCoilV, i, new TGeoTranslation(-fXRyoke/2 + fCoilH/2,0, -40*cm + fCoilW/2 + i*(fCoilGap + fCoilW))); - } - - //cout <<"fZArm: " << fZArm<< endl; - - volUpYoke->AddNode(volFeYoke,1, new TGeoTranslation(0,0,- (fZArm + fGapMiddle)/2)); - volUpYoke->AddNode(volFeYoke,2, new TGeoTranslation(0,0,(fZArm + fGapMiddle)/2)); - volUpYoke->AddNode(volFeYoke1,1,new TGeoTranslation(0,0,0)); - volUpYoke->AddNode(volCoilContainer,1,new TGeoTranslation(0,fYRyoke/2 - fCoilH/2,0)); //up - volUpYoke->AddNode(volCoilContainer,2,new TGeoTranslation(0,-fYRyoke/2 + fCoilH/2,0)); //low - - TGeoBBox *LowYokeBox = new TGeoBBox("LowYokeBox", fXRyoke/2, fYRyoke/2, fZRyoke/2); - TGeoVolume *volLowYoke = new TGeoVolume("volLowYoke",LowYokeBox,vacuum); - volMSBox->AddNode(volLowYoke,1,new TGeoTranslation(0,-fYtot/2 + fYRyoke/2,0)); - volLowYoke->SetField(retFieldL); - - //vertical coils - for(int i = 0; i < fNCoil; i++) - { - volLowYoke->AddNode(volCoilV, i, new TGeoTranslation(fXRyoke/2 - fCoilH/2,0, -40*cm + fCoilW/2 + i*(fCoilGap + fCoilW))); - } - for(int i = 0; i < fNCoil; i++) - { - volLowYoke->AddNode(volCoilV, i, new TGeoTranslation(-fXRyoke/2 + fCoilH/2,0, -40*cm + fCoilW/2 + i*(fCoilGap + fCoilW))); - } - - volLowYoke->AddNode(volFeYoke,3, new TGeoTranslation(0,0,- (fZArm + fGapMiddle)/2)); - volLowYoke->AddNode(volFeYoke,4, new TGeoTranslation(0,0,(fZArm + fGapMiddle)/2)); - volLowYoke->AddNode(volFeYoke1,1,new TGeoTranslation(0,0,0)); - volLowYoke->AddNode(volCoilContainer,3,new TGeoTranslation(0,fYRyoke/2- fCoilH/2,0)); //up - volLowYoke->AddNode(volCoilContainer,4,new TGeoTranslation(0,-fYRyoke/2 + fCoilH/2,0)); //low - - Int_t ArmNumber = 1; - TGeoBBox *Arm1Box = new TGeoBBox("Arm1MSBox", fXFe/2, fYFe/2, fZArm/2); - TGeoVolume *volArm1 = new TGeoVolume("volArm1MS", Arm1Box,vacuum); - TGeoUniformMagField *magField1 = new TGeoUniformMagField(0.,-fField,0.); //magnetic field arm1 - volArm1->SetField(magField1); - volMSBox ->AddNode(volArm1,ArmNumber,new TGeoTranslation(0,0,-(fGapMiddle+fZArm)/2)); - - Int_t nr = ArmNumber*1E4; - - TGeoBBox *IronLayer = new TGeoBBox("Iron",fXFe/2, fYFe/2, fZFe/2); - TGeoVolume *volIron = new TGeoVolume("volIron",IronLayer,Iron); - //volIron->SetField(magField1); - - for(Int_t i = 0; i < fNFe; i++) - { - volArm1->AddNode(volIron,nr + 100 + i, new TGeoTranslation(0, 0, -fZArm/2+i*(fZFe +fZRpc) +fZFe/2)); - } - - TGeoBBox *RpcContainer = new TGeoBBox("RpcContainer", fXRpc/2, fYRpc/2, fZRpc/2); - TGeoVolume *volRpcContainer = new TGeoVolume("volRpcContainer",RpcContainer,vacuum); - - TGeoBBox *Strip = new TGeoBBox("Strip",fXStrip/2, fYStrip/2, fZStrip/2); - TGeoVolume *volStrip = new TGeoVolume("volStrip",Strip,Cu); - volStrip->SetLineColor(kRed); - volRpcContainer->AddNode(volStrip,1,new TGeoTranslation (0,0,-3.25*mm)); - volRpcContainer->AddNode(volStrip,2,new TGeoTranslation (0,0,3.25*mm)); - TGeoBBox *PETinsulator = new TGeoBBox("PETinsulator", fXPet/2, fYPet/2, fZPet/2); - TGeoVolume *volPETinsulator = new TGeoVolume("volPETinsulator", PETinsulator, bakelite); - volPETinsulator->SetLineColor(kYellow); - volRpcContainer->AddNode(volPETinsulator,1,new TGeoTranslation(0,0,-3.1*mm)); - volRpcContainer->AddNode(volPETinsulator,2,new TGeoTranslation(0,0, 3.1*mm)); - TGeoBBox *Electrode = new TGeoBBox("Electrode",fXEle/2, fYEle/2, fZEle/2); - TGeoVolume *volElectrode = new TGeoVolume("volElectrode",Electrode,bakelite); - volElectrode->SetLineColor(kGreen); - volRpcContainer->AddNode(volElectrode,1,new TGeoTranslation(0,0,-2*mm)); - volRpcContainer->AddNode(volElectrode,2,new TGeoTranslation(0,0, 2*mm)); - TGeoBBox *RpcGas = new TGeoBBox("RpcGas", fXGas/2, fYGas/2, fZGas/2); - TGeoVolume *volRpc = new TGeoVolume("volRpc",RpcGas,RPCmat); - volRpc->SetLineColor(kCyan); - volRpcContainer->AddNode(volRpc,1,new TGeoTranslation(0,0,0)); - - AddSensitiveVolume(volRpc); - - for(Int_t i = 0; i < fNRpc; i++) - { - volArm1->AddNode(volRpcContainer,nr + i,new TGeoTranslation(0, -fYFe/2 + fYRpc/2, -fZArm/2+(i+1)*fZFe + i*fZRpc +fZRpc/2)); - } - - ArmNumber = 2; - nr = ArmNumber*1E4; - - TGeoBBox *Arm2Box = new TGeoBBox("Arm2MSBox",fXFe/2, fYFe/2, fZArm/2); - TGeoVolume *volArm2 = new TGeoVolume("volArm2MS", Arm2Box,vacuum); - TGeoUniformMagField *magField2 = new TGeoUniformMagField(0.,fField,0.); //magnetic field arm2 - volArm2->SetField(magField2); - volMSBox ->AddNode(volArm2,1,new TGeoTranslation(0,0,(fGapMiddle+fZArm)/2)); - TGeoVolume *volIron2 = new TGeoVolume("volIron2",IronLayer,Iron); - - //different volumes for second arm - - TGeoVolume *volRpcContainer2 = new TGeoVolume("volRpcContainer2",RpcContainer,vacuum); - TGeoVolume *volStrip2 = new TGeoVolume("volStrip2",Strip,Cu); - - volStrip2->SetLineColor(kRed); - volRpcContainer2->AddNode(volStrip2,1,new TGeoTranslation (0,0,-3.25*mm)); - volRpcContainer2->AddNode(volStrip2,2,new TGeoTranslation (0,0,3.25*mm)); - - TGeoVolume *volPETinsulator2 = new TGeoVolume("volPETinsulator2", PETinsulator, bakelite); - volPETinsulator2->SetLineColor(kYellow); - volRpcContainer2->AddNode(volPETinsulator2,1,new TGeoTranslation(0,0,-3.1*mm)); - volRpcContainer2->AddNode(volPETinsulator2,2,new TGeoTranslation(0,0, 3.1*mm)); - - TGeoVolume *volElectrode2 = new TGeoVolume("volElectrode2",Electrode,bakelite); - volElectrode2->SetLineColor(kGreen); - volRpcContainer2->AddNode(volElectrode2,1,new TGeoTranslation(0,0,-2*mm)); - volRpcContainer2->AddNode(volElectrode2,2,new TGeoTranslation(0,0, 2*mm)); - - TGeoVolume *volRpc2 = new TGeoVolume("volRpc2",RpcGas,RPCmat); - volRpc2->SetLineColor(kCyan); - volRpcContainer2->AddNode(volRpc2,1,new TGeoTranslation(0,0,0)); - AddSensitiveVolume(volRpc2); - - for(Int_t i = 0; i < fNFe; i++) - { - volArm2->AddNode(volIron2,nr + 100 + i,new TGeoTranslation(0, 0, -fZArm/2+i*(fZFe +fZRpc) +fZFe/2)); - } - - for(Int_t i = 0; i < fNRpc; i++) - { - volArm2->AddNode(volRpcContainer2, nr + i,new TGeoTranslation(0, -fYFe/2 + fYRpc/2, -fZArm/2+(i+1)*fZFe + i*fZRpc +fZRpc/2)); - } - - //10 cm of Concrete on which the whole Magnetic Spectrometer volume (HPT included) will be placed - TGeoBBox *Base = new TGeoBBox("Base", fXtot/2, 10*cm/2, fZtot/2); - TGeoVolume *volBase = new TGeoVolume("volBase",Base,Conc); - volBase->SetLineColor(kYellow-3); - - tTauNuDet->AddNode(volBase,1, new TGeoTranslation(0,-fYtot/2 + 10*cm/2,fZcenter)); - - - TGeoBBox *Pillar1Box = new TGeoBBox(fPillarX/2,fPillarY/2, fPillarZ/2); - TGeoVolume *Pillar1Vol = new TGeoVolume("Pillar1Vol",Pillar1Box,Steel); - Pillar1Vol->SetLineColor(kGreen+3); - - tTauNuDet->AddNode(Pillar1Vol,1, new TGeoTranslation(-fXtot/2+fPillarX/2,-fYtot/2-fPillarY/2,fZcenter-fZArm/2 - fGapMiddle/2 +fPillarZ/2)); - tTauNuDet->AddNode(Pillar1Vol,2, new TGeoTranslation(fXtot/2-fPillarX/2,-fYtot/2-fPillarY/2,fZcenter-fZArm/2 - fGapMiddle/2 +fPillarZ/2)); - tTauNuDet->AddNode(Pillar1Vol,3, new TGeoTranslation(-fXtot/2+fPillarX/2,-fYtot/2-fPillarY/2,fZcenter+fZArm/2+fGapMiddle/2-fPillarZ/2)); - tTauNuDet->AddNode(Pillar1Vol,4, new TGeoTranslation(fXtot/2-fPillarX/2,-fYtot/2-fPillarY/2,fZcenter+fZArm/2+fGapMiddle/2-fPillarZ/2)); + TGeoVolume* top = gGeoManager->GetTopVolume(); + TGeoVolumeAssembly* tTauNuDet = new TGeoVolumeAssembly("tTauNuDet"); + top->AddNode(tTauNuDet, 1, new TGeoTranslation(0, 0, 0)); + + InitMedium("RPCgas"); + TGeoMedium* RPCmat = gGeoManager->GetMedium("RPCgas"); + + InitMedium("vacuum"); + TGeoMedium* vacuum = gGeoManager->GetMedium("vacuum"); + + InitMedium("Bakelite"); + TGeoMedium* bakelite = gGeoManager->GetMedium("Bakelite"); + + InitMedium("iron"); + TGeoMedium* Iron = gGeoManager->GetMedium("iron"); + + InitMedium("steel"); + TGeoMedium* Steel = gGeoManager->GetMedium("steel"); + + InitMedium("copper"); + TGeoMedium* Cu = gGeoManager->GetMedium("copper"); + + InitMedium("Concrete"); + TGeoMedium* Conc = gGeoManager->GetMedium("Concrete"); + + TGeoUniformMagField* retFieldU = new TGeoUniformMagField(0., 0., -fField); // magnetic field up return yoke + TGeoUniformMagField* retFieldL = new TGeoUniformMagField(0., 0., fField); // magnetic field low return yoke + + Double_t d = 0; + + if (fDesign != 3) { + TGeoBBox* MSBox = new TGeoBBox("MagneticSpectrometerBox", fXRyoke / 2, fYtot / 2, fZtot / 2); + TGeoVolume* volMSBox = new TGeoVolume("volMagneticSpectrometer", MSBox, vacuum); + tTauNuDet->AddNode(volMSBox, 1, new TGeoTranslation(0, 10 * cm, fZcenter)); + + TGeoBBox* UpYokeBox = new TGeoBBox("UpYokeBox", fXRyoke / 2, fYRyoke / 2, fZRyoke / 2); + TGeoVolume* volUpYoke = new TGeoVolume("volUpYoke", UpYokeBox, vacuum); + volMSBox->AddNode(volUpYoke, 1, new TGeoTranslation(0, fYtot / 2 - fYRyoke / 2, 0)); + volUpYoke->SetField(retFieldU); + + TGeoBBox* FeYoke = new TGeoBBox("FeYoke", fXtot / 2, fYRyoke / 2, fZArm / 2); + TGeoVolume* volFeYoke = new TGeoVolume("volFeYoke", FeYoke, Iron); + volFeYoke->SetLineColor(kGray + 1); + + TGeoBBox* FeYoke1 = new TGeoBBox("FeYoke1", fXtot / 2, fYRyoke_s / 2, fZRyoke_s / 2); + TGeoVolume* volFeYoke1 = new TGeoVolume("volFeYoke1", FeYoke1, Iron); + volFeYoke1->SetLineColor(kGray + 1); + + TGeoBBox* CoilContainer = new TGeoBBox("CoilContainer", fXtot / 2, fCoilH / 2, 40 * cm); + TGeoVolume* volCoilContainer = new TGeoVolume("volCoilContainer", CoilContainer, vacuum); + + TGeoBBox* Coil = new TGeoBBox("Coil", fXtot / 2, fCoilH / 2, fCoilW / 2); + TGeoVolume* volCoil = new TGeoVolume("volCoil", Coil, Cu); + volCoil->SetLineColor(kOrange - 5); + for (int i = 0; i < fNCoil; i++) { + volCoilContainer->AddNode( + volCoil, i, new TGeoTranslation(0, 0, -40 * cm + fCoilW / 2 + i * (fCoilGap + fCoilW))); + } + + // vertical coils + TGeoBBox* CoilV = new TGeoBBox("CoilV", fCoilH / 2, fYRyoke / 2, fCoilW / 2); + TGeoVolume* volCoilV = new TGeoVolume("volCoilV", CoilV, Cu); + volCoilV->SetLineColor(kOrange - 5); + for (int i = 0; i < fNCoil; i++) { + volUpYoke->AddNode( + volCoilV, + i, + new TGeoTranslation(fXRyoke / 2 - fCoilH / 2, 0, -40 * cm + fCoilW / 2 + i * (fCoilGap + fCoilW))); + } + for (int i = 0; i < fNCoil; i++) { + volUpYoke->AddNode( + volCoilV, + i, + new TGeoTranslation(-fXRyoke / 2 + fCoilH / 2, 0, -40 * cm + fCoilW / 2 + i * (fCoilGap + fCoilW))); + } + + // cout <<"fZArm: " << fZArm<< endl; + + volUpYoke->AddNode(volFeYoke, 1, new TGeoTranslation(0, 0, -(fZArm + fGapMiddle) / 2)); + volUpYoke->AddNode(volFeYoke, 2, new TGeoTranslation(0, 0, (fZArm + fGapMiddle) / 2)); + volUpYoke->AddNode(volFeYoke1, 1, new TGeoTranslation(0, 0, 0)); + volUpYoke->AddNode(volCoilContainer, 1, new TGeoTranslation(0, fYRyoke / 2 - fCoilH / 2, 0)); // up + volUpYoke->AddNode(volCoilContainer, 2, new TGeoTranslation(0, -fYRyoke / 2 + fCoilH / 2, 0)); // low + + TGeoBBox* LowYokeBox = new TGeoBBox("LowYokeBox", fXRyoke / 2, fYRyoke / 2, fZRyoke / 2); + TGeoVolume* volLowYoke = new TGeoVolume("volLowYoke", LowYokeBox, vacuum); + volMSBox->AddNode(volLowYoke, 1, new TGeoTranslation(0, -fYtot / 2 + fYRyoke / 2, 0)); + volLowYoke->SetField(retFieldL); + + // vertical coils + for (int i = 0; i < fNCoil; i++) { + volLowYoke->AddNode( + volCoilV, + i, + new TGeoTranslation(fXRyoke / 2 - fCoilH / 2, 0, -40 * cm + fCoilW / 2 + i * (fCoilGap + fCoilW))); + } + for (int i = 0; i < fNCoil; i++) { + volLowYoke->AddNode( + volCoilV, + i, + new TGeoTranslation(-fXRyoke / 2 + fCoilH / 2, 0, -40 * cm + fCoilW / 2 + i * (fCoilGap + fCoilW))); + } + + volLowYoke->AddNode(volFeYoke, 3, new TGeoTranslation(0, 0, -(fZArm + fGapMiddle) / 2)); + volLowYoke->AddNode(volFeYoke, 4, new TGeoTranslation(0, 0, (fZArm + fGapMiddle) / 2)); + volLowYoke->AddNode(volFeYoke1, 1, new TGeoTranslation(0, 0, 0)); + volLowYoke->AddNode(volCoilContainer, 3, new TGeoTranslation(0, fYRyoke / 2 - fCoilH / 2, 0)); // up + volLowYoke->AddNode(volCoilContainer, 4, new TGeoTranslation(0, -fYRyoke / 2 + fCoilH / 2, 0)); // low + + Int_t ArmNumber = 1; + TGeoBBox* Arm1Box = new TGeoBBox("Arm1MSBox", fXFe / 2, fYFe / 2, fZArm / 2); + TGeoVolume* volArm1 = new TGeoVolume("volArm1MS", Arm1Box, vacuum); + TGeoUniformMagField* magField1 = new TGeoUniformMagField(0., -fField, 0.); // magnetic field arm1 + volArm1->SetField(magField1); + volMSBox->AddNode(volArm1, ArmNumber, new TGeoTranslation(0, 0, -(fGapMiddle + fZArm) / 2)); + + Int_t nr = ArmNumber * 1E4; + + TGeoBBox* IronLayer = new TGeoBBox("Iron", fXFe / 2, fYFe / 2, fZFe / 2); + TGeoVolume* volIron = new TGeoVolume("volIron", IronLayer, Iron); + // volIron->SetField(magField1); + + for (Int_t i = 0; i < fNFe; i++) { + volArm1->AddNode( + volIron, nr + 100 + i, new TGeoTranslation(0, 0, -fZArm / 2 + i * (fZFe + fZRpc) + fZFe / 2)); + } + + TGeoBBox* RpcContainer = new TGeoBBox("RpcContainer", fXRpc / 2, fYRpc / 2, fZRpc / 2); + TGeoVolume* volRpcContainer = new TGeoVolume("volRpcContainer", RpcContainer, vacuum); + + TGeoBBox* Strip = new TGeoBBox("Strip", fXStrip / 2, fYStrip / 2, fZStrip / 2); + TGeoVolume* volStrip = new TGeoVolume("volStrip", Strip, Cu); + volStrip->SetLineColor(kRed); + volRpcContainer->AddNode(volStrip, 1, new TGeoTranslation(0, 0, -3.25 * mm)); + volRpcContainer->AddNode(volStrip, 2, new TGeoTranslation(0, 0, 3.25 * mm)); + TGeoBBox* PETinsulator = new TGeoBBox("PETinsulator", fXPet / 2, fYPet / 2, fZPet / 2); + TGeoVolume* volPETinsulator = new TGeoVolume("volPETinsulator", PETinsulator, bakelite); + volPETinsulator->SetLineColor(kYellow); + volRpcContainer->AddNode(volPETinsulator, 1, new TGeoTranslation(0, 0, -3.1 * mm)); + volRpcContainer->AddNode(volPETinsulator, 2, new TGeoTranslation(0, 0, 3.1 * mm)); + TGeoBBox* Electrode = new TGeoBBox("Electrode", fXEle / 2, fYEle / 2, fZEle / 2); + TGeoVolume* volElectrode = new TGeoVolume("volElectrode", Electrode, bakelite); + volElectrode->SetLineColor(kGreen); + volRpcContainer->AddNode(volElectrode, 1, new TGeoTranslation(0, 0, -2 * mm)); + volRpcContainer->AddNode(volElectrode, 2, new TGeoTranslation(0, 0, 2 * mm)); + TGeoBBox* RpcGas = new TGeoBBox("RpcGas", fXGas / 2, fYGas / 2, fZGas / 2); + TGeoVolume* volRpc = new TGeoVolume("volRpc", RpcGas, RPCmat); + volRpc->SetLineColor(kCyan); + volRpcContainer->AddNode(volRpc, 1, new TGeoTranslation(0, 0, 0)); + + AddSensitiveVolume(volRpc); + + for (Int_t i = 0; i < fNRpc; i++) { + volArm1->AddNode( + volRpcContainer, + nr + i, + new TGeoTranslation(0, -fYFe / 2 + fYRpc / 2, -fZArm / 2 + (i + 1) * fZFe + i * fZRpc + fZRpc / 2)); + } + + ArmNumber = 2; + nr = ArmNumber * 1E4; + + TGeoBBox* Arm2Box = new TGeoBBox("Arm2MSBox", fXFe / 2, fYFe / 2, fZArm / 2); + TGeoVolume* volArm2 = new TGeoVolume("volArm2MS", Arm2Box, vacuum); + TGeoUniformMagField* magField2 = new TGeoUniformMagField(0., fField, 0.); // magnetic field arm2 + volArm2->SetField(magField2); + volMSBox->AddNode(volArm2, 1, new TGeoTranslation(0, 0, (fGapMiddle + fZArm) / 2)); + TGeoVolume* volIron2 = new TGeoVolume("volIron2", IronLayer, Iron); + + // different volumes for second arm + + TGeoVolume* volRpcContainer2 = new TGeoVolume("volRpcContainer2", RpcContainer, vacuum); + TGeoVolume* volStrip2 = new TGeoVolume("volStrip2", Strip, Cu); + + volStrip2->SetLineColor(kRed); + volRpcContainer2->AddNode(volStrip2, 1, new TGeoTranslation(0, 0, -3.25 * mm)); + volRpcContainer2->AddNode(volStrip2, 2, new TGeoTranslation(0, 0, 3.25 * mm)); + + TGeoVolume* volPETinsulator2 = new TGeoVolume("volPETinsulator2", PETinsulator, bakelite); + volPETinsulator2->SetLineColor(kYellow); + volRpcContainer2->AddNode(volPETinsulator2, 1, new TGeoTranslation(0, 0, -3.1 * mm)); + volRpcContainer2->AddNode(volPETinsulator2, 2, new TGeoTranslation(0, 0, 3.1 * mm)); + + TGeoVolume* volElectrode2 = new TGeoVolume("volElectrode2", Electrode, bakelite); + volElectrode2->SetLineColor(kGreen); + volRpcContainer2->AddNode(volElectrode2, 1, new TGeoTranslation(0, 0, -2 * mm)); + volRpcContainer2->AddNode(volElectrode2, 2, new TGeoTranslation(0, 0, 2 * mm)); + + TGeoVolume* volRpc2 = new TGeoVolume("volRpc2", RpcGas, RPCmat); + volRpc2->SetLineColor(kCyan); + volRpcContainer2->AddNode(volRpc2, 1, new TGeoTranslation(0, 0, 0)); + AddSensitiveVolume(volRpc2); + + for (Int_t i = 0; i < fNFe; i++) { + volArm2->AddNode( + volIron2, nr + 100 + i, new TGeoTranslation(0, 0, -fZArm / 2 + i * (fZFe + fZRpc) + fZFe / 2)); + } + + for (Int_t i = 0; i < fNRpc; i++) { + volArm2->AddNode( + volRpcContainer2, + nr + i, + new TGeoTranslation(0, -fYFe / 2 + fYRpc / 2, -fZArm / 2 + (i + 1) * fZFe + i * fZRpc + fZRpc / 2)); + } + + // 10 cm of Concrete on which the whole Magnetic Spectrometer volume (HPT included) will be placed + TGeoBBox* Base = new TGeoBBox("Base", fXtot / 2, 10 * cm / 2, fZtot / 2); + TGeoVolume* volBase = new TGeoVolume("volBase", Base, Conc); + volBase->SetLineColor(kYellow - 3); + + tTauNuDet->AddNode(volBase, 1, new TGeoTranslation(0, -fYtot / 2 + 10 * cm / 2, fZcenter)); + + TGeoBBox* Pillar1Box = new TGeoBBox(fPillarX / 2, fPillarY / 2, fPillarZ / 2); + TGeoVolume* Pillar1Vol = new TGeoVolume("Pillar1Vol", Pillar1Box, Steel); + Pillar1Vol->SetLineColor(kGreen + 3); + + tTauNuDet->AddNode(Pillar1Vol, + 1, + new TGeoTranslation(-fXtot / 2 + fPillarX / 2, + -fYtot / 2 - fPillarY / 2, + fZcenter - fZArm / 2 - fGapMiddle / 2 + fPillarZ / 2)); + tTauNuDet->AddNode(Pillar1Vol, + 2, + new TGeoTranslation(fXtot / 2 - fPillarX / 2, + -fYtot / 2 - fPillarY / 2, + fZcenter - fZArm / 2 - fGapMiddle / 2 + fPillarZ / 2)); + tTauNuDet->AddNode(Pillar1Vol, + 3, + new TGeoTranslation(-fXtot / 2 + fPillarX / 2, + -fYtot / 2 - fPillarY / 2, + fZcenter + fZArm / 2 + fGapMiddle / 2 - fPillarZ / 2)); + tTauNuDet->AddNode(Pillar1Vol, + 4, + new TGeoTranslation(fXtot / 2 - fPillarX / 2, + -fYtot / 2 - fPillarY / 2, + fZcenter + fZArm / 2 + fGapMiddle / 2 - fPillarZ / 2)); } - if(fDesign==3) - { - Int_t nr = 1E4; - - TGeoBBox *MSBox = new TGeoBBox("MagneticSpectrometerBox", fXtot/2, fYtot/2, fZtot/2); - TGeoVolume *volMSBox = new TGeoVolume("volMagneticSpectrometer", MSBox, vacuum); - tTauNuDet->AddNode(volMSBox, 1, new TGeoTranslation(0,0,fZcenter)); - - TGeoBBox *IronLayer = new TGeoBBox("Iron",fXFe/2, fYFe/2, fZFe/2); - TGeoVolume *volIron = new TGeoVolume("volIron",IronLayer,Iron); - //volIron->SetField(magField1); - - for(Int_t i = 0; i < fNFe; i++) - { - volMSBox->AddNode(volIron,nr + 100 + i, new TGeoTranslation(0, 0,-fZtot/2+i*fZFe+fZFe/2+i*fZRpc)); - } - - TGeoBBox *RpcContainer = new TGeoBBox("RpcContainer", fXRpc/2, fYRpc/2, fZRpc/2); - TGeoVolume *volRpcContainer = new TGeoVolume("volRpcContainer",RpcContainer,vacuum); - - TGeoBBox *Strip = new TGeoBBox("Strip",fXStrip/2, fYStrip/2, fZStrip/2); - TGeoVolume *volStrip = new TGeoVolume("volStrip",Strip,Cu); - volStrip->SetLineColor(kRed); - volRpcContainer->AddNode(volStrip,1,new TGeoTranslation (0,0,-3.25*mm)); - volRpcContainer->AddNode(volStrip,2,new TGeoTranslation (0,0,3.25*mm)); - TGeoBBox *PETinsulator = new TGeoBBox("PETinsulator", fXPet/2, fYPet/2, fZPet/2); - TGeoVolume *volPETinsulator = new TGeoVolume("volPETinsulator", PETinsulator, bakelite); - volPETinsulator->SetLineColor(kYellow); - volRpcContainer->AddNode(volPETinsulator,1,new TGeoTranslation(0,0,-3.1*mm)); - volRpcContainer->AddNode(volPETinsulator,2,new TGeoTranslation(0,0, 3.1*mm)); - TGeoBBox *Electrode = new TGeoBBox("Electrode",fXEle/2, fYEle/2, fZEle/2); - TGeoVolume *volElectrode = new TGeoVolume("volElectrode",Electrode,bakelite); - volElectrode->SetLineColor(kGreen); - volRpcContainer->AddNode(volElectrode,1,new TGeoTranslation(0,0,-2*mm)); - volRpcContainer->AddNode(volElectrode,2,new TGeoTranslation(0,0, 2*mm)); - TGeoBBox *RpcGas = new TGeoBBox("RpcGas", fXGas/2, fYGas/2, fZGas/2); - TGeoVolume *volRpc = new TGeoVolume("volRpc",RpcGas,RPCmat); - volRpc->SetLineColor(kCyan); - volRpcContainer->AddNode(volRpc,1,new TGeoTranslation(0,0,0)); - - AddSensitiveVolume(volRpc); - - for(Int_t i = 0; i < fNRpc; i++) - { - volMSBox->AddNode(volRpcContainer,nr + i,new TGeoTranslation(0, 0, -fZtot/2+(i+1)*fZFe + i*fZRpc +fZRpc/2)); - } - - TGeoBBox *Pillar1Box = new TGeoBBox(fPillarX/2,fPillarY/2, fPillarZ/2); - TGeoVolume *Pillar1Vol = new TGeoVolume("Pillar1Vol",Pillar1Box,Steel); - Pillar1Vol->SetLineColor(kGreen+3); - - tTauNuDet->AddNode(Pillar1Vol,1, new TGeoTranslation(-fXtot/2+fPillarX/2,-fYtot/2-fPillarY/2,fZcenter-fZtot/2+fPillarZ/2)); - tTauNuDet->AddNode(Pillar1Vol,2, new TGeoTranslation(fXtot/2-fPillarX/2,-fYtot/2-fPillarY/2,fZcenter-fZtot/2 +fPillarZ/2)); - // tTauNuDet->AddNode(Pillar1Vol,3, new TGeoTranslation(-fXtot/2+fPillarX/2,-fYtot/2-fPillarY/2,fZcenter+fZtot/2-fPillarZ/2)); - //tTauNuDet->AddNode(Pillar1Vol,4, new TGeoTranslation(fXtot/2-fPillarX/2,-fYtot/2-fPillarY/2,fZcenter+fZtot/2-fPillarZ/2)); + if (fDesign == 3) { + Int_t nr = 1E4; + + TGeoBBox* MSBox = new TGeoBBox("MagneticSpectrometerBox", fXtot / 2, fYtot / 2, fZtot / 2); + TGeoVolume* volMSBox = new TGeoVolume("volMagneticSpectrometer", MSBox, vacuum); + tTauNuDet->AddNode(volMSBox, 1, new TGeoTranslation(0, 0, fZcenter)); + + TGeoBBox* IronLayer = new TGeoBBox("Iron", fXFe / 2, fYFe / 2, fZFe / 2); + TGeoVolume* volIron = new TGeoVolume("volIron", IronLayer, Iron); + // volIron->SetField(magField1); + + for (Int_t i = 0; i < fNFe; i++) { + volMSBox->AddNode( + volIron, nr + 100 + i, new TGeoTranslation(0, 0, -fZtot / 2 + i * fZFe + fZFe / 2 + i * fZRpc)); + } + + TGeoBBox* RpcContainer = new TGeoBBox("RpcContainer", fXRpc / 2, fYRpc / 2, fZRpc / 2); + TGeoVolume* volRpcContainer = new TGeoVolume("volRpcContainer", RpcContainer, vacuum); + + TGeoBBox* Strip = new TGeoBBox("Strip", fXStrip / 2, fYStrip / 2, fZStrip / 2); + TGeoVolume* volStrip = new TGeoVolume("volStrip", Strip, Cu); + volStrip->SetLineColor(kRed); + volRpcContainer->AddNode(volStrip, 1, new TGeoTranslation(0, 0, -3.25 * mm)); + volRpcContainer->AddNode(volStrip, 2, new TGeoTranslation(0, 0, 3.25 * mm)); + TGeoBBox* PETinsulator = new TGeoBBox("PETinsulator", fXPet / 2, fYPet / 2, fZPet / 2); + TGeoVolume* volPETinsulator = new TGeoVolume("volPETinsulator", PETinsulator, bakelite); + volPETinsulator->SetLineColor(kYellow); + volRpcContainer->AddNode(volPETinsulator, 1, new TGeoTranslation(0, 0, -3.1 * mm)); + volRpcContainer->AddNode(volPETinsulator, 2, new TGeoTranslation(0, 0, 3.1 * mm)); + TGeoBBox* Electrode = new TGeoBBox("Electrode", fXEle / 2, fYEle / 2, fZEle / 2); + TGeoVolume* volElectrode = new TGeoVolume("volElectrode", Electrode, bakelite); + volElectrode->SetLineColor(kGreen); + volRpcContainer->AddNode(volElectrode, 1, new TGeoTranslation(0, 0, -2 * mm)); + volRpcContainer->AddNode(volElectrode, 2, new TGeoTranslation(0, 0, 2 * mm)); + TGeoBBox* RpcGas = new TGeoBBox("RpcGas", fXGas / 2, fYGas / 2, fZGas / 2); + TGeoVolume* volRpc = new TGeoVolume("volRpc", RpcGas, RPCmat); + volRpc->SetLineColor(kCyan); + volRpcContainer->AddNode(volRpc, 1, new TGeoTranslation(0, 0, 0)); + + AddSensitiveVolume(volRpc); + + for (Int_t i = 0; i < fNRpc; i++) { + volMSBox->AddNode(volRpcContainer, + nr + i, + new TGeoTranslation(0, 0, -fZtot / 2 + (i + 1) * fZFe + i * fZRpc + fZRpc / 2)); + } + + TGeoBBox* Pillar1Box = new TGeoBBox(fPillarX / 2, fPillarY / 2, fPillarZ / 2); + TGeoVolume* Pillar1Vol = new TGeoVolume("Pillar1Vol", Pillar1Box, Steel); + Pillar1Vol->SetLineColor(kGreen + 3); + + tTauNuDet->AddNode(Pillar1Vol, + 1, + new TGeoTranslation(-fXtot / 2 + fPillarX / 2, + -fYtot / 2 - fPillarY / 2, + fZcenter - fZtot / 2 + fPillarZ / 2)); + tTauNuDet->AddNode(Pillar1Vol, + 2, + new TGeoTranslation(fXtot / 2 - fPillarX / 2, + -fYtot / 2 - fPillarY / 2, + fZcenter - fZtot / 2 + fPillarZ / 2)); + // tTauNuDet->AddNode(Pillar1Vol,3, new + // TGeoTranslation(-fXtot/2+fPillarX/2,-fYtot/2-fPillarY/2,fZcenter+fZtot/2-fPillarZ/2)); + // tTauNuDet->AddNode(Pillar1Vol,4, new + // TGeoTranslation(fXtot/2-fPillarX/2,-fYtot/2-fPillarY/2,fZcenter+fZtot/2-fPillarZ/2)); } - } - -Bool_t MagneticSpectrometer::ProcessHits(FairVolume* vol) +Bool_t MagneticSpectrometer::ProcessHits(FairVolume* vol) { - /** This method is called from the MC stepping */ - //Set parameters at entrance of volume. Reset ELoss. - if ( gMC->IsTrackEntering() ) { - fELoss = 0.; - fTime = gMC->TrackTime() * 1.0e09; - fLength = gMC->TrackLength(); - gMC->TrackPosition(fPos); - gMC->TrackMomentum(fMom); - } - // Sum energy loss for all steps in the active volume - fELoss += gMC->Edep(); - - // Create muonPoint at exit of active volume - if ( gMC->IsTrackExiting() || - gMC->IsTrackStop() || - gMC->IsTrackDisappeared() ) { - fTrackID = gMC->GetStack()->GetCurrentTrackNumber(); - fVolumeID = vol->getMCid(); - if (fELoss == 0. ) { return kFALSE; } - TParticle* p=gMC->GetStack()->GetCurrentTrack(); - Int_t pdgCode = p->GetPdgCode(); - Int_t detID=0; - gMC->CurrentVolID(detID); - - // cout<< "detID = " << detID << endl; - Int_t MaxLevel = gGeoManager->GetLevel(); - const Int_t MaxL = MaxLevel; - //cout << "MaxLevel = " << MaxL << endl; - //cout << gMC->CurrentVolPath()<< endl; - Int_t NRpc =0; - const char *name; - name = gMC->CurrentVolName(); - //cout << name << endl; - Int_t motherID = gGeoManager->GetMother(0)->GetNumber(); - const char *mumname = gMC->CurrentVolOffName(0); - //cout<Register("ShipRpcPoint", "MagneticSpectrometer", fShipRpcPointCollection, kTRUE); } // ----- Public method to Decode volume info ------------------------------------------- // ----- returns hpt, arm, rpc numbers ----------------------------------- -void MagneticSpectrometer::DecodeVolumeID(Int_t detID,int &nARM,int &nRPC) +void MagneticSpectrometer::DecodeVolumeID(Int_t detID, int& nARM, int& nRPC) { - nARM = detID/1E4; - nRPC = detID - nARM*1E4; + nARM = detID / 1E4; + nRPC = detID - nARM * 1E4; } TClonesArray* MagneticSpectrometer::GetCollection(Int_t iColl) const { - if (iColl == 0) { return fShipRpcPointCollection; } - else { return NULL; } + if (iColl == 0) { + return fShipRpcPointCollection; + } else { + return NULL; + } } void MagneticSpectrometer::Reset() { - fShipRpcPointCollection->Clear(); + fShipRpcPointCollection->Clear(); } - -ShipRpcPoint* MagneticSpectrometer::AddHit(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t time, Double_t length, - Double_t eLoss, Int_t pdgCode) +ShipRpcPoint* MagneticSpectrometer::AddHit(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t time, + Double_t length, + Double_t eLoss, + Int_t pdgCode) { - TClonesArray& clref = *fShipRpcPointCollection; - Int_t size = clref.GetEntriesFast(); - //cout << "ShipRpctau hit called"<< pos.z()< // for string - -#include "TVector3.h" +#include "FairDetector.h" // for FairDetector +#include "FairModule.h" // for FairModule +#include "Rtypes.h" // for ShipMuonShield::Class, Bool_t, etc #include "TLorentzVector.h" +#include "TVector3.h" + +#include // for string class ShipRpcPoint; class FairVolume; class TClonesArray; -class MagneticSpectrometer:public FairDetector +class MagneticSpectrometer : public FairDetector { public: - MagneticSpectrometer(const char* name, const Double_t Zcenter, Bool_t Active, const char* Title="MagneticSpectrometer"); + MagneticSpectrometer(const char* name, + const Double_t Zcenter, + Bool_t Active, + const char* Title = "MagneticSpectrometer"); MagneticSpectrometer(); virtual ~MagneticSpectrometer(); @@ -49,88 +50,87 @@ class MagneticSpectrometer:public FairDetector /** this method is called for each step during simulation * (see FairMCApplication::Stepping()) */ - virtual Bool_t ProcessHits( FairVolume* v=0); + virtual Bool_t ProcessHits(FairVolume* v = 0); /** Registers the produced collections in FAIRRootManager. */ - virtual void Register(); + virtual void Register(); /** Gets the produced collections */ - virtual TClonesArray* GetCollection(Int_t iColl) const ; + virtual TClonesArray* GetCollection(Int_t iColl) const; /** has to be called after each event to reset the containers */ - virtual void Reset(); + virtual void Reset(); /** This method is an example of how to add your own point * of type muonPoint to the clones array */ - ShipRpcPoint* AddHit(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t time, Double_t length, - Double_t eLoss, Int_t pdgCode); + ShipRpcPoint* AddHit(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t time, + Double_t length, + Double_t eLoss, + Int_t pdgCode); /** The following methods can be implemented if you need to make * any optional action in your detector during the transport. */ - virtual void CopyClones( TClonesArray* cl1, TClonesArray* cl2 , - Int_t offset) {;} - virtual void SetSpecialPhysicsCuts() {;} - virtual void EndOfEvent(); - virtual void FinishPrimary() {;} - virtual void FinishRun() {;} - virtual void BeginPrimary() {;} - virtual void PostTrack() {;} - virtual void PreTrack() {;} - virtual void BeginEvent() {;} - - void DecodeVolumeID(Int_t detID,int &nARM,int &nRPC); + virtual void CopyClones(TClonesArray* cl1, TClonesArray* cl2, Int_t offset) { ; } + virtual void SetSpecialPhysicsCuts() { ; } + virtual void EndOfEvent(); + virtual void FinishPrimary() { ; } + virtual void FinishRun() { ; } + virtual void BeginPrimary() { ; } + virtual void PostTrack() { ; } + virtual void PreTrack() { ; } + virtual void BeginEvent() { ; } -private: + void DecodeVolumeID(Int_t detID, int& nARM, int& nRPC); + private: /** Track information to be stored until the track leaves the active volume. */ - Int_t fTrackID; //! track index - Int_t fPdgCode; //! pdg code - Int_t fVolumeID; //! volume id - TLorentzVector fPos; //! position at entrance - TLorentzVector fMom; //! momentum at entrance - Double32_t fTime; //! time - Double32_t fLength; //! length - Double32_t fELoss; //! energy loss + Int_t fTrackID; //! track index + Int_t fPdgCode; //! pdg code + Int_t fVolumeID; //! volume id + TLorentzVector fPos; //! position at entrance + TLorentzVector fMom; //! momentum at entrance + Double32_t fTime; //! time + Double32_t fLength; //! length + Double32_t fELoss; //! energy loss /** container for data points */ - TClonesArray* fShipRpcPointCollection; + TClonesArray* fShipRpcPointCollection; Int_t InitMedium(const char* name); - - -protected: - + protected: Int_t fDesign; - Double_t fZcenter; //z distance of the center of the spectrometer in cm from the center of the vacuum tube + Double_t fZcenter; // z distance of the center of the spectrometer in cm from the center of the vacuum tube Double_t fXtot; Double_t fYtot; - Double_t fZtot; //Dimension of the whole magnetic spectrometr (1st + 2nd arm + HPTs) alogn beam axis + Double_t fZtot; // Dimension of the whole magnetic spectrometr (1st + 2nd arm + HPTs) alogn beam axis Int_t fNFe; Int_t fNRpc; Double_t fXFe; Double_t fXRpc; Double_t fYFe; Double_t fYRpc; - Double_t fZFe; // Width of the Iron Slabs - Double_t fZRpc; // Width of the Rpc planes - Double_t fZArm; // Width of the Spectrometer Arms - Double_t fGapDown; //distance between the end of the second arm of the spectrometer and the decay vessel - Double_t fGapMiddle; // distance between the two arms of the spectrometer + Double_t fZFe; // Width of the Iron Slabs + Double_t fZRpc; // Width of the Rpc planes + Double_t fZArm; // Width of the Spectrometer Arms + Double_t fGapDown; // distance between the end of the second arm of the spectrometer and the decay vessel + Double_t fGapMiddle; // distance between the two arms of the spectrometer Double_t fField; Double_t fXRyoke; Double_t fYRyoke; Double_t fZRyoke; - //Dimensions of the smaller part of the yoke + // Dimensions of the smaller part of the yoke Double_t fXRyoke_s; Double_t fYRyoke_s; Double_t fZRyoke_s; @@ -140,7 +140,7 @@ class MagneticSpectrometer:public FairDetector Double_t fCoilW; Int_t fNCoil; - //Dimension for detailed RPC simulation: + // Dimension for detailed RPC simulation: Double_t fXStrip; Double_t fYStrip; Double_t fZStrip; @@ -154,18 +154,14 @@ class MagneticSpectrometer:public FairDetector Double_t fYGas; Double_t fZGas; - //Dimension of the pillars + // Dimension of the pillars Double_t fPillarX; Double_t fPillarY; Double_t fPillarZ; - MagneticSpectrometer(const MagneticSpectrometer&); MagneticSpectrometer& operator=(const MagneticSpectrometer&); - ClassDef(MagneticSpectrometer,5) - + ClassDef(MagneticSpectrometer, 5) }; - - -#endif //TAUMAGNETICSPECTROMETER_H +#endif // TAUMAGNETICSPECTROMETER_H diff --git a/nutaudet/NuTauMudet.cxx b/nutaudet/NuTauMudet.cxx index 875bc1e00f..acbe12e312 100644 --- a/nutaudet/NuTauMudet.cxx +++ b/nutaudet/NuTauMudet.cxx @@ -1,942 +1,1073 @@ #include "NuTauMudet.h" + +#include "FairGeoBuilder.h" +#include "FairGeoInterface.h" +#include "FairGeoLoader.h" +#include "FairGeoMedia.h" +#include "FairGeoNode.h" +#include "FairGeoVolume.h" +#include "FairRootManager.h" +#include "FairRun.h" // for FairRun +#include "FairRun.h" +#include "FairRuntimeDb.h" // for FairRuntimeDb +#include "FairRuntimeDb.h" +#include "FairVolume.h" +#include "ShipDetectorList.h" #include "ShipRpcPoint.h" -#include "TGeoManager.h" -#include "FairRun.h" // for FairRun -#include "FairRuntimeDb.h" // for FairRuntimeDb -#include // for ostream -#include "TList.h" // for TListIter, TList (ptr only) -#include "TObjArray.h" // for TObjArray -#include "TString.h" // for TString +#include "ShipStack.h" +#include "ShipUnit.h" #include "TClonesArray.h" -#include "TVirtualMC.h" - -#include "TGeoPara.h" #include "TGeoBBox.h" -#include "TGeoTrd1.h" -#include "TGeoTrd2.h" #include "TGeoCompositeShape.h" -#include "TGeoTube.h" +#include "TGeoManager.h" #include "TGeoMaterial.h" #include "TGeoMedium.h" +#include "TGeoPara.h" +#include "TGeoTrd1.h" +#include "TGeoTrd2.h" +#include "TGeoTube.h" +#include "TGeoUniformMagField.h" +#include "TList.h" // for TListIter, TList (ptr only) +#include "TObjArray.h" // for TObjArray #include "TParticle.h" +#include "TString.h" // for TString #include "TVector3.h" +#include "TVirtualMC.h" -#include "FairVolume.h" -#include "FairGeoVolume.h" -#include "FairGeoNode.h" -#include "FairRootManager.h" -#include "FairGeoLoader.h" -#include "FairGeoInterface.h" -#include "FairGeoMedia.h" -#include "FairGeoBuilder.h" -#include "FairRun.h" -#include "FairRuntimeDb.h" - -#include "ShipDetectorList.h" -#include "ShipUnit.h" -#include "ShipStack.h" - -#include "TGeoUniformMagField.h" -#include // for NULL -#include // for operator<<, basic_ostream, etc +#include // for ostream +#include // for operator<<, basic_ostream, etc +#include // for NULL using std::cout; using std::endl; using namespace ShipUnit; NuTauMudet::NuTauMudet() - : FairDetector("NuTauMudet",kTRUE, ktauRpc), - fTrackID(-1), - fPdgCode(), - fVolumeID(-1), - fPos(), - fMom(), - fTime(-1.), - fLength(-1.), - fELoss(-1), - fShipRpcPointCollection(new TClonesArray("ShipRpcPoint")) -{ -} - -NuTauMudet::NuTauMudet(const char* name, const Double_t Zcenter,Bool_t Active,const char* Title) - : FairDetector(name, Active, ktauRpc), - fTrackID(-1), - fPdgCode(), - fVolumeID(-1), - fPos(), - fMom(), - fTime(-1.), - fLength(-1.), - fELoss(-1), - fShipRpcPointCollection(new TClonesArray("ShipRpcPoint")) -{ - fZcenter = Zcenter; + : FairDetector("NuTauMudet", kTRUE, ktauRpc) + , fTrackID(-1) + , fPdgCode() + , fVolumeID(-1) + , fPos() + , fMom() + , fTime(-1.) + , fLength(-1.) + , fELoss(-1) + , fShipRpcPointCollection(new TClonesArray("ShipRpcPoint")) +{} + +NuTauMudet::NuTauMudet(const char* name, const Double_t Zcenter, Bool_t Active, const char* Title) + : FairDetector(name, Active, ktauRpc) + , fTrackID(-1) + , fPdgCode() + , fVolumeID(-1) + , fPos() + , fMom() + , fTime(-1.) + , fLength(-1.) + , fELoss(-1) + , fShipRpcPointCollection(new TClonesArray("ShipRpcPoint")) +{ + fZcenter = Zcenter; } void NuTauMudet::SetDesign(Int_t Design) { - fDesign = Design; - cout <<" Mag Spectro Design "<< fDesign<Delete(); - delete fShipRpcPointCollection; - } + if (fShipRpcPointCollection) { + fShipRpcPointCollection->Delete(); + delete fShipRpcPointCollection; + } } void NuTauMudet::Initialize() { - FairDetector::Initialize(); + FairDetector::Initialize(); } // ----- Private method InitMedium Int_t NuTauMudet::InitMedium(const char* name) { - static FairGeoLoader *geoLoad=FairGeoLoader::Instance(); - static FairGeoInterface *geoFace=geoLoad->getGeoInterface(); - static FairGeoMedia *media=geoFace->getMedia(); - static FairGeoBuilder *geoBuild=geoLoad->getGeoBuilder(); + static FairGeoLoader* geoLoad = FairGeoLoader::Instance(); + static FairGeoInterface* geoFace = geoLoad->getGeoInterface(); + static FairGeoMedia* media = geoFace->getMedia(); + static FairGeoBuilder* geoBuild = geoLoad->getGeoBuilder(); - FairGeoMedium *ShipMedium=media->getMedium(name); + FairGeoMedium* ShipMedium = media->getMedium(name); - if (!ShipMedium) - { - Fatal("InitMedium","Material %s not defined in media file.", name); - return -1111; + if (!ShipMedium) { + Fatal("InitMedium", "Material %s not defined in media file.", name); + return -1111; } - TGeoMedium* medium=gGeoManager->GetMedium(name); - if (medium!=NULL) - return ShipMedium->getMediumIndex(); - return geoBuild->createMedium(ShipMedium); + TGeoMedium* medium = gGeoManager->GetMedium(name); + if (medium != NULL) + return ShipMedium->getMediumIndex(); + return geoBuild->createMedium(ShipMedium); } void NuTauMudet::ConstructGeometry() { - TGeoVolume *top = gGeoManager->GetTopVolume(); - TGeoVolumeAssembly *tTauNuDet = new TGeoVolumeAssembly("tTauNuDet"); - top->AddNode(tTauNuDet, 1, new TGeoTranslation(0, 0, 0)); - - InitMedium("RPCgas"); - TGeoMedium *RPCmat =gGeoManager->GetMedium("RPCgas"); - - InitMedium("Bakelite"); - TGeoMedium *bakelite =gGeoManager->GetMedium("Bakelite"); - - InitMedium("iron"); - TGeoMedium *Iron =gGeoManager->GetMedium("iron"); - - InitMedium("steel"); - TGeoMedium *Steel =gGeoManager->GetMedium("steel"); - - InitMedium("copper"); - TGeoMedium *Cu =gGeoManager->GetMedium("copper"); - - InitMedium("Concrete"); - TGeoMedium *Conc =gGeoManager->GetMedium("Concrete"); - - InitMedium("air"); - TGeoMedium *air =gGeoManager->GetMedium("air"); - - InitMedium("Aluminum"); //new - TGeoMedium *Al =gGeoManager->GetMedium("Aluminum"); //new - - TGeoUniformMagField *retFieldU = new TGeoUniformMagField(0.,0.,-fField); //magnetic field up return yoke - TGeoUniformMagField *retFieldL = new TGeoUniformMagField(0.,0.,fField); //magnetic field low return yoke - - if(fDesign<3) - { - TGeoVolumeAssembly *volMudetBox = new TGeoVolumeAssembly("volNuTauMudet"); - tTauNuDet->AddNode(volMudetBox, 1, new TGeoTranslation(0,10*cm,fZcenter)); - - TGeoBBox *UpYokeBox = new TGeoBBox("UpYokeBox", fXRyoke/2, fYRyoke/2, fZRyoke/2); - TGeoVolume *volUpYoke = new TGeoVolume("volUpYoke",UpYokeBox,air); - volMudetBox->AddNode(volUpYoke,1,new TGeoTranslation(0,fYtot/2 - fYRyoke/2,0)); - volUpYoke->SetField(retFieldU); - - - TGeoBBox *FeYoke = new TGeoBBox("FeYoke",fXtot/2, fYRyoke/2, fZArm/2); - TGeoVolume *volFeYoke = new TGeoVolume("volFeYoke",FeYoke,Iron); - volFeYoke->SetLineColor(kGray+1); - - TGeoBBox *FeYoke1 = new TGeoBBox("FeYoke1",fXtot/2, fYRyoke_s/2, fZRyoke_s/2); - TGeoVolume *volFeYoke1 = new TGeoVolume("volFeYoke1",FeYoke1,Iron); - volFeYoke1->SetLineColor(kGray+1); - - TGeoBBox *CoilContainer = new TGeoBBox("CoilContainer",fXtot/2, fCoilH/2, 40*cm); - TGeoVolume *volCoilContainer = new TGeoVolume("volCoilContainer",CoilContainer,air); - - TGeoBBox *Coil = new TGeoBBox("Coil",fXtot/2, fCoilH/2, fCoilW/2); - TGeoVolume *volCoil = new TGeoVolume("volCoil",Coil,Cu); - volCoil->SetLineColor(kOrange -5); - for(int i = 0; i < fNCoil; i++) - { - volCoilContainer->AddNode(volCoil, i, new TGeoTranslation(0,0, -40*cm + fCoilW/2 + i*(fCoilGap + fCoilW))); - } - - //vertical coils - TGeoBBox *CoilV = new TGeoBBox("CoilV",fCoilH/2, fYRyoke/2 , fCoilW/2); - TGeoVolume *volCoilV = new TGeoVolume("volCoilV",CoilV,Cu); - volCoilV->SetLineColor(kOrange -5); - for(int i = 0; i < fNCoil; i++) - { - volUpYoke->AddNode(volCoilV, i, new TGeoTranslation(fXRyoke/2 - fCoilH/2,0, -40*cm + fCoilW/2 + i*(fCoilGap + fCoilW))); - } - for(int i = 0; i < fNCoil; i++) - { - volUpYoke->AddNode(volCoilV, i, new TGeoTranslation(-fXRyoke/2 + fCoilH/2,0, -40*cm + fCoilW/2 + i*(fCoilGap + fCoilW))); - } - - //cout <<"fZArm: " << fZArm<< endl; - - volUpYoke->AddNode(volFeYoke,1, new TGeoTranslation(0,0,- (fZArm + fGapMiddle)/2)); - volUpYoke->AddNode(volFeYoke,2, new TGeoTranslation(0,0,(fZArm + fGapMiddle)/2)); - volUpYoke->AddNode(volFeYoke1,1,new TGeoTranslation(0,0,0)); - volUpYoke->AddNode(volCoilContainer,1,new TGeoTranslation(0,fYRyoke/2 - fCoilH/2,0)); //up - volUpYoke->AddNode(volCoilContainer,2,new TGeoTranslation(0,-fYRyoke/2 + fCoilH/2,0)); //low - - TGeoBBox *LowYokeBox = new TGeoBBox("LowYokeBox", fXRyoke/2, fYRyoke/2, fZRyoke/2); - TGeoVolume *volLowYoke = new TGeoVolume("volLowYoke",LowYokeBox,air); - volMudetBox->AddNode(volLowYoke,1,new TGeoTranslation(0,-fYtot/2 + fYRyoke/2,0)); - volLowYoke->SetField(retFieldL); - - //vertical coils - for(int i = 0; i < fNCoil; i++) - { - volLowYoke->AddNode(volCoilV, i, new TGeoTranslation(fXRyoke/2 - fCoilH/2,0, -40*cm + fCoilW/2 + i*(fCoilGap + fCoilW))); - } - for(int i = 0; i < fNCoil; i++) - { - volLowYoke->AddNode(volCoilV, i, new TGeoTranslation(-fXRyoke/2 + fCoilH/2,0, -40*cm + fCoilW/2 + i*(fCoilGap + fCoilW))); - } - - volLowYoke->AddNode(volFeYoke,3, new TGeoTranslation(0,0,- (fZArm + fGapMiddle)/2)); - volLowYoke->AddNode(volFeYoke,4, new TGeoTranslation(0,0,(fZArm + fGapMiddle)/2)); - volLowYoke->AddNode(volFeYoke1,1,new TGeoTranslation(0,0,0)); - volLowYoke->AddNode(volCoilContainer,3,new TGeoTranslation(0,fYRyoke/2- fCoilH/2,0)); //up - volLowYoke->AddNode(volCoilContainer,4,new TGeoTranslation(0,-fYRyoke/2 + fCoilH/2,0)); //low - - Int_t ArmNumber = 1; - TGeoBBox *Arm1Box = new TGeoBBox("Arm1MudetBox", fXFe/2, fYFe/2, fZArm/2); - TGeoVolume *volArm1 = new TGeoVolume("volArm1Mudet", Arm1Box,air); - TGeoUniformMagField *magField1 = new TGeoUniformMagField(0.,-fField,0.); //magnetic field arm1 - volArm1->SetField(magField1); - volMudetBox ->AddNode(volArm1,ArmNumber,new TGeoTranslation(0,0,-(fGapMiddle+fZArm)/2)); - - Int_t nr = ArmNumber*1E4; - - TGeoBBox *IronLayer = new TGeoBBox("Iron",fXFe/2, fYFe/2, fZFe/2); - TGeoVolume *volIron = new TGeoVolume("volIron",IronLayer,Iron); - //volIron->SetField(magField1); - - for(Int_t i = 0; i < fNFe; i++) - { - volArm1->AddNode(volIron,nr + 100 + i, new TGeoTranslation(0, 0, -fZArm/2+i*(fZFe +fZRpc) +fZFe/2)); - } - - - TGeoBBox *RpcContainer = new TGeoBBox("RpcContainer", fXRpc/2, fYRpc/2, fZRpc/2); - TGeoVolume *volRpcContainer = new TGeoVolume("volRpcContainer",RpcContainer,air); - - TGeoBBox *Strip = new TGeoBBox("Strip",fXStrip/2, fYStrip/2, fZStrip/2); - TGeoVolume *volStrip = new TGeoVolume("volStrip",Strip,Cu); - volStrip->SetLineColor(kRed); - volRpcContainer->AddNode(volStrip,1,new TGeoTranslation (0,0,-3.25*mm)); - volRpcContainer->AddNode(volStrip,2,new TGeoTranslation (0,0,3.25*mm)); - TGeoBBox *PETinsulator = new TGeoBBox("PETinsulator", fXPet/2, fYPet/2, fZPet/2); - TGeoVolume *volPETinsulator = new TGeoVolume("volPETinsulator", PETinsulator, bakelite); - volPETinsulator->SetLineColor(kYellow); - volRpcContainer->AddNode(volPETinsulator,1,new TGeoTranslation(0,0,-3.1*mm)); - volRpcContainer->AddNode(volPETinsulator,2,new TGeoTranslation(0,0, 3.1*mm)); - TGeoBBox *Electrode = new TGeoBBox("Electrode",fXEle/2, fYEle/2, fZEle/2); - TGeoVolume *volElectrode = new TGeoVolume("volElectrode",Electrode,bakelite); - volElectrode->SetLineColor(kGreen); - volRpcContainer->AddNode(volElectrode,1,new TGeoTranslation(0,0,-2*mm)); - volRpcContainer->AddNode(volElectrode,2,new TGeoTranslation(0,0, 2*mm)); - TGeoBBox *RpcGas = new TGeoBBox("RpcGas", fXGas/2, fYGas/2, fZGas/2); - TGeoVolume *volRpc = new TGeoVolume("volRpc",RpcGas,RPCmat); - volRpc->SetLineColor(kCyan); - volRpcContainer->AddNode(volRpc,1,new TGeoTranslation(0,0,0)); - - AddSensitiveVolume(volRpc); - - for(Int_t i = 0; i < fNRpc; i++) - { - volArm1->AddNode(volRpcContainer,nr + i,new TGeoTranslation(0, -fYFe/2 + fYRpc/2, -fZArm/2+(i+1)*fZFe + i*fZRpc +fZRpc/2)); - } - - ArmNumber = 2; - nr = ArmNumber*1E4; - - TGeoBBox *Arm2Box = new TGeoBBox("Arm2MudetBox",fXFe/2, fYFe/2, fZArm/2); - TGeoVolume *volArm2 = new TGeoVolume("volArm2Mudet", Arm2Box,air); - TGeoUniformMagField *magField2 = new TGeoUniformMagField(0.,fField,0.); //magnetic field arm2 - volArm2->SetField(magField2); - volMudetBox ->AddNode(volArm2,1,new TGeoTranslation(0,0,(fGapMiddle+fZArm)/2)); - TGeoVolume *volIron2 = new TGeoVolume("volIron2",IronLayer,Iron); - - //different volumes for second arm - - TGeoVolume *volRpcContainer2 = new TGeoVolume("volRpcContainer2",RpcContainer,air); - TGeoVolume *volStrip2 = new TGeoVolume("volStrip2",Strip,Cu); - - volStrip2->SetLineColor(kRed); - volRpcContainer2->AddNode(volStrip2,1,new TGeoTranslation (0,0,-3.25*mm)); - volRpcContainer2->AddNode(volStrip2,2,new TGeoTranslation (0,0,3.25*mm)); - - TGeoVolume *volPETinsulator2 = new TGeoVolume("volPETinsulator2", PETinsulator, bakelite); - volPETinsulator2->SetLineColor(kYellow); - volRpcContainer2->AddNode(volPETinsulator2,1,new TGeoTranslation(0,0,-3.1*mm)); - volRpcContainer2->AddNode(volPETinsulator2,2,new TGeoTranslation(0,0, 3.1*mm)); - - TGeoVolume *volElectrode2 = new TGeoVolume("volElectrode2",Electrode,bakelite); - volElectrode2->SetLineColor(kGreen); - volRpcContainer2->AddNode(volElectrode2,1,new TGeoTranslation(0,0,-2*mm)); - volRpcContainer2->AddNode(volElectrode2,2,new TGeoTranslation(0,0, 2*mm)); - - TGeoVolume *volRpc2 = new TGeoVolume("volRpc2",RpcGas,RPCmat); - volRpc2->SetLineColor(kCyan); - volRpcContainer2->AddNode(volRpc2,1,new TGeoTranslation(0,0,0)); - AddSensitiveVolume(volRpc2); - - for(Int_t i = 0; i < fNFe; i++) - { - volArm2->AddNode(volIron2,nr + 100 + i,new TGeoTranslation(0, 0, -fZArm/2+i*(fZFe +fZRpc) +fZFe/2)); - } - - for(Int_t i = 0; i < fNRpc; i++) - { - volArm2->AddNode(volRpcContainer2, nr + i,new TGeoTranslation(0, -fYFe/2 + fYRpc/2, -fZArm/2+(i+1)*fZFe + i*fZRpc +fZRpc/2)); - } - - //10 cm of Concrete on which the whole Magnetic Spectrometer volume (HPT included) will be placed - TGeoBBox *Base = new TGeoBBox("Base", fXtot/2, 10*cm/2, fZtot/2); - TGeoVolume *volBase = new TGeoVolume("volBase",Base,Conc); - volBase->SetLineColor(kYellow-3); - - tTauNuDet->AddNode(volBase,1, new TGeoTranslation(0,-fYtot/2 + 10*cm/2,fZcenter)); - - - TGeoBBox *Pillar1Box = new TGeoBBox(fPillarX/2,fPillarY/2, fPillarZ/2); - TGeoVolume *Pillar1Vol = new TGeoVolume("Pillar1Vol",Pillar1Box,Steel); - Pillar1Vol->SetLineColor(kGreen+3); - - tTauNuDet->AddNode(Pillar1Vol,1, new TGeoTranslation(-fXtot/2+fPillarX/2,-fYtot/2-fPillarY/2,fZcenter-fZArm/2 - fGapMiddle/2 +fPillarZ/2)); - tTauNuDet->AddNode(Pillar1Vol,2, new TGeoTranslation(fXtot/2-fPillarX/2,-fYtot/2-fPillarY/2,fZcenter-fZArm/2 - fGapMiddle/2 +fPillarZ/2)); - tTauNuDet->AddNode(Pillar1Vol,3, new TGeoTranslation(-fXtot/2+fPillarX/2,-fYtot/2-fPillarY/2,fZcenter+fZArm/2+fGapMiddle/2-fPillarZ/2)); - tTauNuDet->AddNode(Pillar1Vol,4, new TGeoTranslation(fXtot/2-fPillarX/2,-fYtot/2-fPillarY/2,fZcenter+fZArm/2+fGapMiddle/2-fPillarZ/2)); + TGeoVolume* top = gGeoManager->GetTopVolume(); + TGeoVolumeAssembly* tTauNuDet = new TGeoVolumeAssembly("tTauNuDet"); + top->AddNode(tTauNuDet, 1, new TGeoTranslation(0, 0, 0)); + + InitMedium("RPCgas"); + TGeoMedium* RPCmat = gGeoManager->GetMedium("RPCgas"); + + InitMedium("Bakelite"); + TGeoMedium* bakelite = gGeoManager->GetMedium("Bakelite"); + + InitMedium("iron"); + TGeoMedium* Iron = gGeoManager->GetMedium("iron"); + + InitMedium("steel"); + TGeoMedium* Steel = gGeoManager->GetMedium("steel"); + + InitMedium("copper"); + TGeoMedium* Cu = gGeoManager->GetMedium("copper"); + + InitMedium("Concrete"); + TGeoMedium* Conc = gGeoManager->GetMedium("Concrete"); + + InitMedium("air"); + TGeoMedium* air = gGeoManager->GetMedium("air"); + + InitMedium("Aluminum"); // new + TGeoMedium* Al = gGeoManager->GetMedium("Aluminum"); // new + + TGeoUniformMagField* retFieldU = new TGeoUniformMagField(0., 0., -fField); // magnetic field up return yoke + TGeoUniformMagField* retFieldL = new TGeoUniformMagField(0., 0., fField); // magnetic field low return yoke + + if (fDesign < 3) { + TGeoVolumeAssembly* volMudetBox = new TGeoVolumeAssembly("volNuTauMudet"); + tTauNuDet->AddNode(volMudetBox, 1, new TGeoTranslation(0, 10 * cm, fZcenter)); + + TGeoBBox* UpYokeBox = new TGeoBBox("UpYokeBox", fXRyoke / 2, fYRyoke / 2, fZRyoke / 2); + TGeoVolume* volUpYoke = new TGeoVolume("volUpYoke", UpYokeBox, air); + volMudetBox->AddNode(volUpYoke, 1, new TGeoTranslation(0, fYtot / 2 - fYRyoke / 2, 0)); + volUpYoke->SetField(retFieldU); + + TGeoBBox* FeYoke = new TGeoBBox("FeYoke", fXtot / 2, fYRyoke / 2, fZArm / 2); + TGeoVolume* volFeYoke = new TGeoVolume("volFeYoke", FeYoke, Iron); + volFeYoke->SetLineColor(kGray + 1); + + TGeoBBox* FeYoke1 = new TGeoBBox("FeYoke1", fXtot / 2, fYRyoke_s / 2, fZRyoke_s / 2); + TGeoVolume* volFeYoke1 = new TGeoVolume("volFeYoke1", FeYoke1, Iron); + volFeYoke1->SetLineColor(kGray + 1); + + TGeoBBox* CoilContainer = new TGeoBBox("CoilContainer", fXtot / 2, fCoilH / 2, 40 * cm); + TGeoVolume* volCoilContainer = new TGeoVolume("volCoilContainer", CoilContainer, air); + + TGeoBBox* Coil = new TGeoBBox("Coil", fXtot / 2, fCoilH / 2, fCoilW / 2); + TGeoVolume* volCoil = new TGeoVolume("volCoil", Coil, Cu); + volCoil->SetLineColor(kOrange - 5); + for (int i = 0; i < fNCoil; i++) { + volCoilContainer->AddNode( + volCoil, i, new TGeoTranslation(0, 0, -40 * cm + fCoilW / 2 + i * (fCoilGap + fCoilW))); + } + + // vertical coils + TGeoBBox* CoilV = new TGeoBBox("CoilV", fCoilH / 2, fYRyoke / 2, fCoilW / 2); + TGeoVolume* volCoilV = new TGeoVolume("volCoilV", CoilV, Cu); + volCoilV->SetLineColor(kOrange - 5); + for (int i = 0; i < fNCoil; i++) { + volUpYoke->AddNode( + volCoilV, + i, + new TGeoTranslation(fXRyoke / 2 - fCoilH / 2, 0, -40 * cm + fCoilW / 2 + i * (fCoilGap + fCoilW))); + } + for (int i = 0; i < fNCoil; i++) { + volUpYoke->AddNode( + volCoilV, + i, + new TGeoTranslation(-fXRyoke / 2 + fCoilH / 2, 0, -40 * cm + fCoilW / 2 + i * (fCoilGap + fCoilW))); + } + + // cout <<"fZArm: " << fZArm<< endl; + + volUpYoke->AddNode(volFeYoke, 1, new TGeoTranslation(0, 0, -(fZArm + fGapMiddle) / 2)); + volUpYoke->AddNode(volFeYoke, 2, new TGeoTranslation(0, 0, (fZArm + fGapMiddle) / 2)); + volUpYoke->AddNode(volFeYoke1, 1, new TGeoTranslation(0, 0, 0)); + volUpYoke->AddNode(volCoilContainer, 1, new TGeoTranslation(0, fYRyoke / 2 - fCoilH / 2, 0)); // up + volUpYoke->AddNode(volCoilContainer, 2, new TGeoTranslation(0, -fYRyoke / 2 + fCoilH / 2, 0)); // low + + TGeoBBox* LowYokeBox = new TGeoBBox("LowYokeBox", fXRyoke / 2, fYRyoke / 2, fZRyoke / 2); + TGeoVolume* volLowYoke = new TGeoVolume("volLowYoke", LowYokeBox, air); + volMudetBox->AddNode(volLowYoke, 1, new TGeoTranslation(0, -fYtot / 2 + fYRyoke / 2, 0)); + volLowYoke->SetField(retFieldL); + + // vertical coils + for (int i = 0; i < fNCoil; i++) { + volLowYoke->AddNode( + volCoilV, + i, + new TGeoTranslation(fXRyoke / 2 - fCoilH / 2, 0, -40 * cm + fCoilW / 2 + i * (fCoilGap + fCoilW))); + } + for (int i = 0; i < fNCoil; i++) { + volLowYoke->AddNode( + volCoilV, + i, + new TGeoTranslation(-fXRyoke / 2 + fCoilH / 2, 0, -40 * cm + fCoilW / 2 + i * (fCoilGap + fCoilW))); + } + + volLowYoke->AddNode(volFeYoke, 3, new TGeoTranslation(0, 0, -(fZArm + fGapMiddle) / 2)); + volLowYoke->AddNode(volFeYoke, 4, new TGeoTranslation(0, 0, (fZArm + fGapMiddle) / 2)); + volLowYoke->AddNode(volFeYoke1, 1, new TGeoTranslation(0, 0, 0)); + volLowYoke->AddNode(volCoilContainer, 3, new TGeoTranslation(0, fYRyoke / 2 - fCoilH / 2, 0)); // up + volLowYoke->AddNode(volCoilContainer, 4, new TGeoTranslation(0, -fYRyoke / 2 + fCoilH / 2, 0)); // low + + Int_t ArmNumber = 1; + TGeoBBox* Arm1Box = new TGeoBBox("Arm1MudetBox", fXFe / 2, fYFe / 2, fZArm / 2); + TGeoVolume* volArm1 = new TGeoVolume("volArm1Mudet", Arm1Box, air); + TGeoUniformMagField* magField1 = new TGeoUniformMagField(0., -fField, 0.); // magnetic field arm1 + volArm1->SetField(magField1); + volMudetBox->AddNode(volArm1, ArmNumber, new TGeoTranslation(0, 0, -(fGapMiddle + fZArm) / 2)); + + Int_t nr = ArmNumber * 1E4; + + TGeoBBox* IronLayer = new TGeoBBox("Iron", fXFe / 2, fYFe / 2, fZFe / 2); + TGeoVolume* volIron = new TGeoVolume("volIron", IronLayer, Iron); + // volIron->SetField(magField1); + + for (Int_t i = 0; i < fNFe; i++) { + volArm1->AddNode( + volIron, nr + 100 + i, new TGeoTranslation(0, 0, -fZArm / 2 + i * (fZFe + fZRpc) + fZFe / 2)); + } + + TGeoBBox* RpcContainer = new TGeoBBox("RpcContainer", fXRpc / 2, fYRpc / 2, fZRpc / 2); + TGeoVolume* volRpcContainer = new TGeoVolume("volRpcContainer", RpcContainer, air); + + TGeoBBox* Strip = new TGeoBBox("Strip", fXStrip / 2, fYStrip / 2, fZStrip / 2); + TGeoVolume* volStrip = new TGeoVolume("volStrip", Strip, Cu); + volStrip->SetLineColor(kRed); + volRpcContainer->AddNode(volStrip, 1, new TGeoTranslation(0, 0, -3.25 * mm)); + volRpcContainer->AddNode(volStrip, 2, new TGeoTranslation(0, 0, 3.25 * mm)); + TGeoBBox* PETinsulator = new TGeoBBox("PETinsulator", fXPet / 2, fYPet / 2, fZPet / 2); + TGeoVolume* volPETinsulator = new TGeoVolume("volPETinsulator", PETinsulator, bakelite); + volPETinsulator->SetLineColor(kYellow); + volRpcContainer->AddNode(volPETinsulator, 1, new TGeoTranslation(0, 0, -3.1 * mm)); + volRpcContainer->AddNode(volPETinsulator, 2, new TGeoTranslation(0, 0, 3.1 * mm)); + TGeoBBox* Electrode = new TGeoBBox("Electrode", fXEle / 2, fYEle / 2, fZEle / 2); + TGeoVolume* volElectrode = new TGeoVolume("volElectrode", Electrode, bakelite); + volElectrode->SetLineColor(kGreen); + volRpcContainer->AddNode(volElectrode, 1, new TGeoTranslation(0, 0, -2 * mm)); + volRpcContainer->AddNode(volElectrode, 2, new TGeoTranslation(0, 0, 2 * mm)); + TGeoBBox* RpcGas = new TGeoBBox("RpcGas", fXGas / 2, fYGas / 2, fZGas / 2); + TGeoVolume* volRpc = new TGeoVolume("volRpc", RpcGas, RPCmat); + volRpc->SetLineColor(kCyan); + volRpcContainer->AddNode(volRpc, 1, new TGeoTranslation(0, 0, 0)); + + AddSensitiveVolume(volRpc); + + for (Int_t i = 0; i < fNRpc; i++) { + volArm1->AddNode( + volRpcContainer, + nr + i, + new TGeoTranslation(0, -fYFe / 2 + fYRpc / 2, -fZArm / 2 + (i + 1) * fZFe + i * fZRpc + fZRpc / 2)); + } + + ArmNumber = 2; + nr = ArmNumber * 1E4; + + TGeoBBox* Arm2Box = new TGeoBBox("Arm2MudetBox", fXFe / 2, fYFe / 2, fZArm / 2); + TGeoVolume* volArm2 = new TGeoVolume("volArm2Mudet", Arm2Box, air); + TGeoUniformMagField* magField2 = new TGeoUniformMagField(0., fField, 0.); // magnetic field arm2 + volArm2->SetField(magField2); + volMudetBox->AddNode(volArm2, 1, new TGeoTranslation(0, 0, (fGapMiddle + fZArm) / 2)); + TGeoVolume* volIron2 = new TGeoVolume("volIron2", IronLayer, Iron); + + // different volumes for second arm + + TGeoVolume* volRpcContainer2 = new TGeoVolume("volRpcContainer2", RpcContainer, air); + TGeoVolume* volStrip2 = new TGeoVolume("volStrip2", Strip, Cu); + + volStrip2->SetLineColor(kRed); + volRpcContainer2->AddNode(volStrip2, 1, new TGeoTranslation(0, 0, -3.25 * mm)); + volRpcContainer2->AddNode(volStrip2, 2, new TGeoTranslation(0, 0, 3.25 * mm)); + + TGeoVolume* volPETinsulator2 = new TGeoVolume("volPETinsulator2", PETinsulator, bakelite); + volPETinsulator2->SetLineColor(kYellow); + volRpcContainer2->AddNode(volPETinsulator2, 1, new TGeoTranslation(0, 0, -3.1 * mm)); + volRpcContainer2->AddNode(volPETinsulator2, 2, new TGeoTranslation(0, 0, 3.1 * mm)); + + TGeoVolume* volElectrode2 = new TGeoVolume("volElectrode2", Electrode, bakelite); + volElectrode2->SetLineColor(kGreen); + volRpcContainer2->AddNode(volElectrode2, 1, new TGeoTranslation(0, 0, -2 * mm)); + volRpcContainer2->AddNode(volElectrode2, 2, new TGeoTranslation(0, 0, 2 * mm)); + + TGeoVolume* volRpc2 = new TGeoVolume("volRpc2", RpcGas, RPCmat); + volRpc2->SetLineColor(kCyan); + volRpcContainer2->AddNode(volRpc2, 1, new TGeoTranslation(0, 0, 0)); + AddSensitiveVolume(volRpc2); + + for (Int_t i = 0; i < fNFe; i++) { + volArm2->AddNode( + volIron2, nr + 100 + i, new TGeoTranslation(0, 0, -fZArm / 2 + i * (fZFe + fZRpc) + fZFe / 2)); + } + + for (Int_t i = 0; i < fNRpc; i++) { + volArm2->AddNode( + volRpcContainer2, + nr + i, + new TGeoTranslation(0, -fYFe / 2 + fYRpc / 2, -fZArm / 2 + (i + 1) * fZFe + i * fZRpc + fZRpc / 2)); + } + + // 10 cm of Concrete on which the whole Magnetic Spectrometer volume (HPT included) will be placed + TGeoBBox* Base = new TGeoBBox("Base", fXtot / 2, 10 * cm / 2, fZtot / 2); + TGeoVolume* volBase = new TGeoVolume("volBase", Base, Conc); + volBase->SetLineColor(kYellow - 3); + + tTauNuDet->AddNode(volBase, 1, new TGeoTranslation(0, -fYtot / 2 + 10 * cm / 2, fZcenter)); + + TGeoBBox* Pillar1Box = new TGeoBBox(fPillarX / 2, fPillarY / 2, fPillarZ / 2); + TGeoVolume* Pillar1Vol = new TGeoVolume("Pillar1Vol", Pillar1Box, Steel); + Pillar1Vol->SetLineColor(kGreen + 3); + + tTauNuDet->AddNode(Pillar1Vol, + 1, + new TGeoTranslation(-fXtot / 2 + fPillarX / 2, + -fYtot / 2 - fPillarY / 2, + fZcenter - fZArm / 2 - fGapMiddle / 2 + fPillarZ / 2)); + tTauNuDet->AddNode(Pillar1Vol, + 2, + new TGeoTranslation(fXtot / 2 - fPillarX / 2, + -fYtot / 2 - fPillarY / 2, + fZcenter - fZArm / 2 - fGapMiddle / 2 + fPillarZ / 2)); + tTauNuDet->AddNode(Pillar1Vol, + 3, + new TGeoTranslation(-fXtot / 2 + fPillarX / 2, + -fYtot / 2 - fPillarY / 2, + fZcenter + fZArm / 2 + fGapMiddle / 2 - fPillarZ / 2)); + tTauNuDet->AddNode(Pillar1Vol, + 4, + new TGeoTranslation(fXtot / 2 - fPillarX / 2, + -fYtot / 2 - fPillarY / 2, + fZcenter + fZArm / 2 + fGapMiddle / 2 - fPillarZ / 2)); + } + if (fDesign == 3) { + Int_t nr = 1E4; + + TGeoVolumeAssembly* volMudetBox = new TGeoVolumeAssembly("volTauNuMudet"); + tTauNuDet->AddNode(volMudetBox, 1, new TGeoTranslation(0, 0, fZcenter)); + + TGeoBBox* IronLayer = new TGeoBBox("MUDETIRON", fXFe / 2, fYFe / 2, fZFe / 2); + TGeoVolume* volIron = new TGeoVolume("volIron", IronLayer, Iron); + volIron->SetLineColor(kGray); + + auto* IronLayer1 = new TGeoBBox("MUDETIRON1", fXFe / 2, fYFe / 2, fZFethin / 2); + //***********************ADDING EXTERNAL DETAILS TO THE MUON FILTER + + //********UPPER COVER*********** + + TGeoBBox* UpperCover = new TGeoBBox("UpperCover", fXCov / 2, fYCov / 2, fZCov / 2); + TGeoVolume* volUpperCover = new TGeoVolume("volUpperCover", UpperCover, Al); + volUpperCover->SetLineColor(kYellow - 7); + volMudetBox->AddNode( + volUpperCover, 1, new TGeoTranslation(0, fYFe / 2 + fYCov / 2 + fUpSuppY, -fZtot / 2 + fZCov / 2)); + + //**********LATERAL COVER********** + + TGeoBBox* LateralCover = new TGeoBBox("LateralCover", fXLateral / 2, fYLateral / 2, fZLateral / 2); + TGeoVolume* volLateralCover = new TGeoVolume("volLateralCover", LateralCover, Al); + volLateralCover->SetLineColor(kYellow - 7); + volMudetBox->AddNode(volLateralCover, + 1, + new TGeoTranslation(-fXFe / 2. - fLatSuppX - fXLateral / 2., + -fYFe / 2. + fYLateral / 2. + fYSpacing + 4. * cm, + -fZtot / 2 + fZLateral / 2)); // low right + volMudetBox->AddNode(volLateralCover, + 2, + new TGeoTranslation(+fXFe / 2. + fLatSuppX + fXLateral / 2., + -fYFe / 2. + fYLateral / 2. + fYSpacing + 4. * cm, + -fZtot / 2 + fZLateral / 2)); // low left + volMudetBox->AddNode(volLateralCover, + 3, + new TGeoTranslation(-fXFe / 2. - fLatSuppX - fXLateral / 2., + +fYFe / 2. - fYLateral / 2. - fYSpacing - 4. * cm, + -fZtot / 2 + fZLateral / 2)); // up right + volMudetBox->AddNode(volLateralCover, + 4, + new TGeoTranslation(+fXFe / 2. + fLatSuppX + fXLateral / 2., + +fYFe / 2. - fYLateral / 2. - fYSpacing - 4. * cm, + -fZtot / 2 + fZLateral / 2)); // up left + + //*********** LATERAL CROSSES************ + + Double_t Inclination = TMath::Pi() / 2 - TMath::ATan(fYCross / (fZCross - fWidthArm)); + TGeoRotation* Crossrot1 = new TGeoRotation("Crossrot1", 0., 0., 0.); + TGeoRotation* Crossrot2 = new TGeoRotation("Crossrot2", 0., 0., 0.); + Crossrot1->RotateY(-90); + Crossrot2->RotateY(90); + Crossrot1->SetName("NegativeRot"); + Crossrot2->SetName("PositiveRot"); + Crossrot1->RegisterYourself(); + Crossrot2->RegisterYourself(); + + TGeoPara* ArmCross1 = new TGeoPara("ArmCross1", + fWidthArm / 2., + fYCross / 2, + fXCross / 2., + TMath::RadToDeg() * Inclination, + 0., + 0.); // length and height are not x and y here, because it will be rotated! + ArmCross1->SetName("ARMCROSS1"); + TGeoPara* ArmCross2 = new TGeoPara("ArmCross2", + fWidthArm / 2., + fYCross / 2, + fXCross / 2., + TMath::RadToDeg() * Inclination, + 0., + 0.); // length and height are not x and y here, because it will be rotated! + ArmCross2->SetName("ARMCROSS2"); + TGeoCompositeShape* MuCross = + new TGeoCompositeShape("MUFILTERCROSS", "ARMCROSS1:NegativeRot+ARMCROSS2:PositiveRot"); + TGeoVolume* volMuDetCross = new TGeoVolume("volMuDetCross", MuCross, Al); + volMuDetCross->SetLineColor(kYellow - 7); + volMudetBox->AddNode(volMuDetCross, + 1, + new TGeoTranslation(-fXFe / 2. - fLatSuppX - fXLateral + fXCross / 2., + 0., + -fZtot / 2 + fZCross / 2)); // right + volMudetBox->AddNode(volMuDetCross, + 2, + new TGeoTranslation(+fXFe / 2. + fLatSuppX + fXLateral - fXCross / 2., + 0., + -fZtot / 2 + fZCross / 2)); // left + + //***********************ADDING CUTS AT MID-LATERAL IN WALLS + + Double_t delta = 0.1; // to avoid border effects in the cuts (cut is not visualized in viewer, I do not know + // if it can affect simulation) + TGeoTrd2* Model = new TGeoTrd2( + "Model", + fCutHeight / 2, + 0, + (fZFe + delta) / 2, + (fZFe + delta) / 2, + (fCutLength + delta) / 2); // length and height are not x and y here, because it will be rotated! + Model->SetName("MUDETTRIANGLE"); + + TGeoRotation rot("rot", 90, 90, 0); + TGeoRotation rot1("rot1", -90, 90, 0); + // cut on the right (seen from beam) + const TGeoTranslation transright("trans", -fXFe / 2. + fCutLength / 2, 0, 0); + TGeoCombiTrans* combright = new TGeoCombiTrans(transright, rot); + combright->SetName("MuDetcombright"); + combright->RegisterYourself(); + // cut on the left (seen from beam) + const TGeoTranslation transleft("transleft", +fXFe / 2. - fCutLength / 2, 0, 0); + TGeoCombiTrans* combleft = new TGeoCombiTrans(transleft, rot1); + combleft->SetName("MuDetcombleft"); + combleft->RegisterYourself(); + // unique volume, we cut the triangles + TGeoCompositeShape* mudetcut = + new TGeoCompositeShape("MUDETCUT", "(MUDETIRON-MUDETTRIANGLE:MuDetcombright)-MUDETTRIANGLE:MuDetcombleft"); + mudetcut->SetName("MUDETTRIANGCUT"); + // same, for the thin layers + TGeoCompositeShape* mudetcut1 = new TGeoCompositeShape( + "MUDETCUT1", "(MUDETIRON1-MUDETTRIANGLE:MuDetcombright)-MUDETTRIANGLE:MuDetcombleft"); + mudetcut1->SetName("MUDETTRIANGCUT1"); + // addition of iron support structures + // support layers, fot thick layers upstream + TGeoBBox* UpperSupport = new TGeoBBox(fUpSuppX / 2., fUpSuppY / 2., fZFe / 2.); + UpperSupport->SetName("MUDETUPSUPPORT"); + TGeoBBox* LowerSupport = new TGeoBBox(fLowSuppX / 2., fLowSuppY / 2., fZFe / 2.); + LowerSupport->SetName("MUDETLOWSUPPORT"); + TGeoBBox* LateralSupport = new TGeoBBox(fLatSuppX / 2., fLatSuppY / 2., fZFe / 2.); + LateralSupport->SetName("MUDETLATERALSUPPORT"); + // support layers, for thin layers downstream + TGeoBBox* UpperSupport1 = + new TGeoBBox(fUpSuppX / 2., fUpSuppY / 2., fZFethin / 2.); // The 1 shapes have less z thickness + UpperSupport1->SetName("MUDETUPSUPPORT1"); + TGeoBBox* LowerSupport1 = new TGeoBBox(fLowSuppX / 2., fLowSuppY / 2., fZFethin / 2.); + LowerSupport1->SetName("MUDETLOWSUPPORT1"); + TGeoBBox* LateralSupport1 = new TGeoBBox(fLatSuppX / 2., fLatSuppY / 2., fZFethin / 2.); + LateralSupport1->SetName("MUDETLATERALSUPPORT1"); + // Translations (left is considered from the beam, positive x) + + TGeoTranslation* upright = + new TGeoTranslation("MuDetupright", -fXFe / 2. + fUpSuppX / 2., fYFe / 2 + fUpSuppY / 2., 0); + TGeoTranslation* upleft = + new TGeoTranslation("MuDetupleft", +fXFe / 2. - fUpSuppX / 2., fYFe / 2 + fUpSuppY / 2., 0); + TGeoTranslation* lateralupleft = new TGeoTranslation( + "MuDetlateralupleft", +fXFe / 2. + fLowSuppX / 2., fYFe / 2 - fLowSuppY / 2. - fYSpacing, 0); + TGeoTranslation* lateralupright = new TGeoTranslation( + "MuDetlateralupright", -fXFe / 2. - fLowSuppX / 2., fYFe / 2 - fLowSuppY / 2. - fYSpacing, 0); + TGeoTranslation* laterallowleft = new TGeoTranslation( + "MuDetlaterallowleft", +fXFe / 2. + fLowSuppX / 2., -fYFe / 2 + fLowSuppY / 2. + fYSpacing, 0); + TGeoTranslation* laterallowright = new TGeoTranslation( + "MuDetlaterallowright", -fXFe / 2. - fLowSuppX / 2., -fYFe / 2 + fLowSuppY / 2. + fYSpacing, 0); + TGeoTranslation* lowright = + new TGeoTranslation("MuDetlowright", -fXFe / 2. + fLowSuppX / 2., -fYFe / 2 - fLowSuppY / 2., 0); + TGeoTranslation* lowleft = + new TGeoTranslation("MuDetlowleft", +fXFe / 2. - fLowSuppX / 2., -fYFe / 2 - fLowSuppY / 2., 0); + // necessary to put SetName, otherwise it will not find them + upright->SetName("MuDetupright"); + upright->RegisterYourself(); + upleft->SetName("MuDetupleft"); + upleft->RegisterYourself(); + lowright->SetName("MuDetlowright"); + lowright->RegisterYourself(); + lowleft->SetName("MuDetlowleft"); + lowleft->RegisterYourself(); + + lateralupleft->SetName("MuDetlateralupleft"); + lateralupleft->RegisterYourself(); + lateralupright->SetName("MuDetlateralupright"); + lateralupright->RegisterYourself(); + laterallowleft->SetName("MuDetlaterallowleft"); + laterallowleft->RegisterYourself(); + laterallowright->SetName("MuDetlaterallowright"); + laterallowright->RegisterYourself(); + // building composite shapes, writing compositions as TString first to improve readibility + TString* supportaddition = new TString( + "MUDETTRIANGCUT+MUDETUPSUPPORT:MuDetupright+MUDETUPSUPPORT:MuDetupleft+MUDETLOWSUPPORT:MuDetlowright+" + "MUDETLOWSUPPORT:MuDetlowleft+MUDETLATERALSUPPORT:MuDetlateralupleft+MUDETLATERALSUPPORT:" + "MuDetlateralupright+MUDETLATERALSUPPORT:MuDetlaterallowleft+MUDETLATERALSUPPORT:MuDetlaterallowright"); + TString* supportaddition1 = + new TString("MUDETTRIANGCUT1+MUDETUPSUPPORT1:MuDetupright+MUDETUPSUPPORT1:MuDetupleft+MUDETLOWSUPPORT1:" + "MuDetlowright+MUDETLOWSUPPORT1:MuDetlowleft+MUDETLOWSUPPORT1:MuDetlowleft+" + "MUDETLATERALSUPPORT1:MuDetlateralupleft+MUDETLATERALSUPPORT1:MuDetlateralupright+" + "MUDETLATERALSUPPORT1:MuDetlaterallowleft+MUDETLATERALSUPPORT1:MuDetlaterallowright"); + TGeoCompositeShape* SupportedIronLayer = new TGeoCompositeShape("SupportedIronLayer", supportaddition->Data()); + TGeoCompositeShape* SupportedIronLayer1 = + new TGeoCompositeShape("SupportedIronLayer1", supportaddition1->Data()); + + TGeoVolume* MudetIronLayer = new TGeoVolume("MudetIronLayer", SupportedIronLayer, Iron); + MudetIronLayer->SetLineColor(kRed + 2); + TGeoVolume* MudetIronLayer1 = new TGeoVolume("MudetIronLayer1", SupportedIronLayer1, Iron); + MudetIronLayer1->SetLineColor(kRed + 2); + + for (Int_t i = 0; i < fNFe; i++) { + double dz = -fZtot / 2 + i * fZFe + fZFe / 2 + i * fZRpc; + volMudetBox->AddNode(MudetIronLayer, nr + 100 + i, new TGeoTranslation(0, 0, dz)); + } + for (Int_t i = 0; i < fNFethin; i++) { + double dz = -fZtot / 2 + fNFe * (fZRpc + fZFe) + i * fZFethin + fZFethin / 2 + i * fZRpc; + volMudetBox->AddNode(MudetIronLayer1, nr + 100 + fNFe + i, new TGeoTranslation(0, 0, dz)); + } + //*****************************RPC LAYERS**************************************** + + TGeoBBox* RpcContainer_0 = new TGeoBBox("RpcContainer", fXRpc_outer / 2, fYRpc_outer / 2, fZRpc / 2); + RpcContainer_0->SetName("RPCCOINTAINER_0"); + + /* + TGeoBBox *Strip = new TGeoBBox("Strip",fXStrip/2, fYStrip/2, fZStrip/2); + TGeoVolume *volStrip = new TGeoVolume("volStrip",Strip,Cu); + volStrip->SetLineColor(kGreen); + volRpcContainer->AddNode(volStrip,1,new TGeoTranslation (0,0,-3.25*mm)); + volRpcContainer->AddNode(volStrip,2,new TGeoTranslation (0,0,3.25*mm)); + TGeoBBox *PETinsulator = new TGeoBBox("PETinsulator", fXPet/2, fYPet/2, fZPet/2); + TGeoVolume *volPETinsulator = new TGeoVolume("volPETinsulator", PETinsulator, bakelite); + volPETinsulator->SetLineColor(kYellow); + volRpcContainer->AddNode(volPETinsulator,1,new TGeoTranslation(0,0,-3.1*mm)); + volRpcContainer->AddNode(volPETinsulator,2,new TGeoTranslation(0,0, 3.1*mm)); + TGeoBBox *Electrode = new TGeoBBox("Electrode",fXEle/2, fYEle/2, fZEle/2); + TGeoVolume *volElectrode = new TGeoVolume("volElectrode",Electrode,bakelite); + volElectrode->SetLineColor(kGreen); + volRpcContainer->AddNode(volElectrode,1,new TGeoTranslation(0,0,-2*mm)); + volRpcContainer->AddNode(volElectrode,2,new TGeoTranslation(0,0, 2*mm)); + TGeoBBox *RpcGas = new TGeoBBox("RpcGas", fXRpcGap/2, fYRpc_inner/2, fZGas/2); + TGeoVolume *volRpc = new TGeoVolume("volRpc",RpcGas,RPCmat); + volRpc->SetLineColor(kCyan); + volRpcContainer->AddNode(volRpc,1,new TGeoTranslation(0,0,0)); + */ + + TGeoBBox* RpcOuter = new TGeoBBox("RpcOuter", fXRpc_outer / 2, fYRpc_outer / 2, fZRpc_outer / 2); + RpcOuter->SetName("RPCOUTER"); + TGeoTrd2* Indentation = new TGeoTrd2("Indentation", + (fYRpc_outer - 2 * (31.2 * cm + 15. * cm)) / 2, + (fYRpc_outer - 2 * 31.2 * cm) / 2, + (fZRpc_outer + 0.1 * cm) / 2, + (fZRpc_outer + 0.1 * cm) / 2, + (15. * cm + 0.1 * cm) / 2); // (b, B, Z_up, Z_down, h) + Indentation->SetName("INDENTATION"); + const TGeoTranslation leftindent("leftindent", (fXRpc_outer - 15. * cm) / 2, 0, 0); + TGeoCombiTrans* left_ind = new TGeoCombiTrans(leftindent, rot); + left_ind->SetName("LEFTINDENT"); + left_ind->RegisterYourself(); + const TGeoTranslation rightindent("rightindent", (-fXRpc_outer + 15. * cm) / 2, 0, 0); + TGeoCombiTrans* right_ind = new TGeoCombiTrans(rightindent, rot1); + right_ind->SetName("RIGHTINDENT"); + right_ind->RegisterYourself(); + TGeoBBox* RpcInner = new TGeoBBox("RpcInner", fXRpc_inner / 2, fYRpc_inner / 2, fZRpc_inner / 2); + RpcInner->SetName("RPCINNER"); + TGeoTranslation* exclusion = new TGeoTranslation(0, 0, (-fZRpc_inner / 2) - 0.6 * cm); + exclusion->SetName("EXCLUSION"); + exclusion->RegisterYourself(); + TGeoCompositeShape* RpcShell = new TGeoCompositeShape( + "RpcShell", "RPCOUTER-INDENTATION:RIGHTINDENT-INDENTATION:LEFTINDENT-RPCINNER:EXCLUSION"); + TGeoVolume* volRpcShell = new TGeoVolume("volRpcShell", RpcShell, Al); + volRpcShell->SetLineColor(kGray); + + TGeoBBox* GasShape = new TGeoBBox("GasShape", fXRpcGap / 2, fYRpc_inner / 2, fZGas / 2); + GasShape->SetName("RPCGAS"); + TGeoBBox* GapSpacing = new TGeoBBox("GapSpacing", fXRpcGap / 2, 6. / 2 * cm, (fZGas + 0.01 * cm) / 2); + GapSpacing->SetName("GAPSPACE"); + TGeoTranslation* mdown = + new TGeoTranslation("mdown", 0., -(fYRpcGap + 6 * cm) / 2, 0.); // 6 cm is the spacing between two gaps + mdown->SetName("MDOWN"); + mdown->RegisterYourself(); + TGeoTranslation* mup = new TGeoTranslation("mup", 0., (fYRpcGap + 6 * cm) / 2, 0.); + mup->SetName("MUP"); + mup->RegisterYourself(); + TGeoCompositeShape* RpcGas = new TGeoCompositeShape("RpcGas", "RPCGAS-GAPSPACE:MUP-GAPSPACE:MDOWN"); + TGeoVolume* volRpc = new TGeoVolume("volRpc", RpcGas, RPCmat); + volRpc->SetLineColor(kCyan); + + //****RPC container framing********* + TGeoTrd2* Indentation_0 = new TGeoTrd2("Indentation_0", + (fYRpc_outer - 2 * (31.2 * cm + 15. * cm)) / 2, + (fYRpc_outer - 2 * 31.2 * cm) / 2, + (fZRpc) / 2, + (fZRpc) / 2, + (15. * cm + 0.1 * cm) / 2); + Indentation_0->SetName("INDENTATION_0"); + TGeoCompositeShape* RpcContainer = new TGeoCompositeShape( + "RpcContainer", "RPCCOINTAINER_0-INDENTATION_0:RIGHTINDENT-INDENTATION_0:LEFTINDENT"); + TGeoVolume* volRpcContainer = new TGeoVolume("volRpcContainer", RpcContainer, air); + //*********************************** + + TGeoBBox* GapShape = new TGeoBBox("GapShape", fXRpcGap / 2, fYRpc_inner / 2, fZRpcGap / 2); + GapShape->SetName("RPCGAP"); + TGeoBBox* GapSpacing1 = new TGeoBBox("GapSpacing1", fXRpcGap / 2, 6. / 2 * cm, (fZRpcGap + 0.01 * cm) / 2); + GapSpacing1->SetName("GAPSPACE1"); + TGeoCompositeShape* RpcGap = new TGeoCompositeShape("RpcGap", "RPCGAP-GAPSPACE1:MUP-GAPSPACE1:MDOWN"); + TGeoVolume* volRpcGap = new TGeoVolume("volRpcGap", RpcGap, bakelite); + volRpcGap->SetLineColor(kOrange); + + TGeoBBox* Strip = new TGeoBBox("Strip", fXRpc_inner / 2, fYRpc_inner / 2, fZStrip / 2); + TGeoVolume* volStrip = new TGeoVolume("volStrip", Strip, Cu); + volStrip->SetLineColor(kOrange + 5); + TGeoRotation rot2("rot2", 0., 0., 0.); + rot2.RotateY(180); + const TGeoTranslation trans_rot(0., 0., fZGas / 2 + fZRpcGap + fZStrip + fZRpc_outer / 2); + TGeoCombiTrans* comb_1 = new TGeoCombiTrans(trans_rot, rot2); + + volRpcContainer->AddNode( + volRpcShell, 1, new TGeoTranslation(0., 0., -fZGas / 2 - fZRpcGap - fZStrip - fZRpc_outer / 2)); + volRpcContainer->AddNode(volRpcShell, 2, comb_1); + volRpcContainer->AddNode(volStrip, 1, new TGeoTranslation(0., 0., fZGas / 2 + fZRpcGap + fZStrip / 2)); + volRpcContainer->AddNode(volStrip, 2, new TGeoTranslation(0., 0., -fZGas / 2 - fZRpcGap - fZStrip / 2)); + volRpcContainer->AddNode(volRpcGap, 1, new TGeoTranslation(0., 0., (fZGas + fZRpcGap) / 2)); + volRpcContainer->AddNode(volRpcGap, 2, new TGeoTranslation(0., 0., -(fZGas + fZRpcGap) / 2)); + volRpcContainer->AddNode(volRpc, 1, new TGeoTranslation(0., 0., 0.)); + + AddSensitiveVolume(volRpc); + + for (Int_t i = 0; i < fNRpc; i++) { + double dy = 5. * cm; + double dz = -fZtot / 2 + (i + 1) * fZFe + i * fZRpc + fZRpc / 2; + if (i >= fNFe) + dz = dz - (i + 1 - fNFe) * (fZFe - fZFethin); + if (i % 2) + volMudetBox->AddNode(volRpcContainer, nr + i, new TGeoTranslation(0, -dy, dz)); // staggering + else { + volMudetBox->AddNode(volRpcContainer, nr + i, new TGeoTranslation(0, dy, dz)); + } + } + + TGeoBBox* Pillar1Box = new TGeoBBox(fPillarX / 2, fPillarY / 2, fPillarZ / 2); + TGeoVolume* Pillar1Vol = new TGeoVolume("Pillar1Vol", Pillar1Box, Steel); + Pillar1Vol->SetLineColor(kGreen + 3); + + // tTauNuDet->AddNode(Pillar1Vol,1, new + // TGeoTranslation(-fXtot/2+fPillarX/2,-fYtot/2-fPillarY/2,fZcenter-fZtot/2+fPillarZ/2)); + // tTauNuDet->AddNode(Pillar1Vol,2, new TGeoTranslation(fXtot/2-fPillarX/2,-fYtot/2-fPillarY/2,fZcenter-fZtot/2 + // +fPillarZ/2)); + // tTauNuDet->AddNode(Pillar1Vol,3, new + // TGeoTranslation(-fXtot/2+fPillarX/2,-fYtot/2-fPillarY/2,fZcenter+fZtot/2-fPillarZ/2)); //eventually two + // pillars at the end. Now muon det is followed by veto, so its steel pillar supports both + // tTauNuDet->AddNode(Pillar1Vol,4, new + // TGeoTranslation(fXtot/2-fPillarX/2,-fYtot/2-fPillarY/2,fZcenter+fZtot/2-fPillarZ/2)); } - if(fDesign==3) - { - Int_t nr = 1E4; - - TGeoVolumeAssembly *volMudetBox = new TGeoVolumeAssembly("volTauNuMudet"); - tTauNuDet->AddNode(volMudetBox, 1, new TGeoTranslation(0,0,fZcenter)); - - TGeoBBox *IronLayer = new TGeoBBox("MUDETIRON",fXFe/2, fYFe/2, fZFe/2); - TGeoVolume *volIron = new TGeoVolume("volIron",IronLayer,Iron); - volIron->SetLineColor(kGray); - - auto* IronLayer1 = new TGeoBBox("MUDETIRON1",fXFe/2, fYFe/2, fZFethin/2); - //***********************ADDING EXTERNAL DETAILS TO THE MUON FILTER - - //********UPPER COVER*********** - - TGeoBBox *UpperCover = new TGeoBBox("UpperCover",fXCov/2, fYCov/2, fZCov/2); - TGeoVolume *volUpperCover = new TGeoVolume("volUpperCover",UpperCover, Al); - volUpperCover->SetLineColor(kYellow-7); - volMudetBox->AddNode(volUpperCover, 1, new TGeoTranslation(0, fYFe/2+fYCov/2+fUpSuppY, -fZtot/2 + fZCov/2)); - - //**********LATERAL COVER********** - - TGeoBBox *LateralCover = new TGeoBBox("LateralCover",fXLateral/2, fYLateral/2, fZLateral/2); - TGeoVolume *volLateralCover = new TGeoVolume("volLateralCover",LateralCover, Al); - volLateralCover->SetLineColor(kYellow-7); - volMudetBox->AddNode(volLateralCover, 1, new TGeoTranslation(-fXFe/2.-fLatSuppX-fXLateral/2., -fYFe/2.+fYLateral/2.+fYSpacing+ 4.*cm, -fZtot/2 + fZLateral/2)); //low right - volMudetBox->AddNode(volLateralCover, 2, new TGeoTranslation(+fXFe/2.+fLatSuppX+fXLateral/2., -fYFe/2.+fYLateral/2.+fYSpacing+ 4.*cm, -fZtot/2 + fZLateral/2)); //low left - volMudetBox->AddNode(volLateralCover, 3, new TGeoTranslation(-fXFe/2.-fLatSuppX-fXLateral/2., +fYFe/2.-fYLateral/2.-fYSpacing- 4.*cm, -fZtot/2 + fZLateral/2)); //up right - volMudetBox->AddNode(volLateralCover, 4, new TGeoTranslation(+fXFe/2.+fLatSuppX+fXLateral/2., +fYFe/2.-fYLateral/2.-fYSpacing- 4.*cm, -fZtot/2 + fZLateral/2)); //up left - - //*********** LATERAL CROSSES************ - - Double_t Inclination =TMath::Pi()/2 - TMath::ATan(fYCross/(fZCross - fWidthArm)); - TGeoRotation *Crossrot1 = new TGeoRotation("Crossrot1", 0., 0.,0.); TGeoRotation *Crossrot2 = new TGeoRotation("Crossrot2", 0., 0.,0.); - Crossrot1->RotateY(-90); Crossrot2->RotateY(90); - Crossrot1->SetName("NegativeRot"); Crossrot2->SetName("PositiveRot"); - Crossrot1->RegisterYourself(); Crossrot2->RegisterYourself(); - - TGeoPara *ArmCross1 = new TGeoPara ("ArmCross1", fWidthArm/2., fYCross/2, fXCross/2., TMath::RadToDeg()*Inclination, 0., 0.);//length and height are not x and y here, because it will be rotated! - ArmCross1->SetName("ARMCROSS1"); - TGeoPara *ArmCross2 = new TGeoPara ("ArmCross2", fWidthArm/2., fYCross/2, fXCross/2., TMath::RadToDeg()*Inclination, 0., 0.);//length and height are not x and y here, because it will be rotated! - ArmCross2->SetName("ARMCROSS2"); - TGeoCompositeShape *MuCross = new TGeoCompositeShape("MUFILTERCROSS", "ARMCROSS1:NegativeRot+ARMCROSS2:PositiveRot"); - TGeoVolume *volMuDetCross = new TGeoVolume("volMuDetCross",MuCross, Al); - volMuDetCross->SetLineColor(kYellow-7); - volMudetBox->AddNode(volMuDetCross, 1, new TGeoTranslation(-fXFe/2.-fLatSuppX-fXLateral+fXCross/2., 0., -fZtot/2 + fZCross/2)); // right - volMudetBox->AddNode(volMuDetCross, 2, new TGeoTranslation(+fXFe/2.+fLatSuppX+fXLateral-fXCross/2., 0., -fZtot/2 + fZCross/2)); // left - - //***********************ADDING CUTS AT MID-LATERAL IN WALLS - - Double_t delta = 0.1; //to avoid border effects in the cuts (cut is not visualized in viewer, I do not know if it can affect simulation) - TGeoTrd2 * Model= new TGeoTrd2("Model",fCutHeight/2,0, (fZFe+delta)/2,(fZFe+delta)/2,(fCutLength+delta)/2); //length and height are not x and y here, because it will be rotated! - Model->SetName("MUDETTRIANGLE"); - - TGeoRotation rot("rot",90,90,0); - TGeoRotation rot1("rot1",-90,90,0); - //cut on the right (seen from beam) - const TGeoTranslation transright("trans",-fXFe/2.+ fCutLength/2,0,0); - TGeoCombiTrans* combright = new TGeoCombiTrans(transright,rot); - combright->SetName("MuDetcombright"); - combright->RegisterYourself(); - //cut on the left (seen from beam) - const TGeoTranslation transleft("transleft",+fXFe/2.- fCutLength/2,0,0); - TGeoCombiTrans* combleft = new TGeoCombiTrans(transleft,rot1); - combleft->SetName("MuDetcombleft"); - combleft->RegisterYourself(); - //unique volume, we cut the triangles - TGeoCompositeShape *mudetcut = new TGeoCompositeShape("MUDETCUT", "(MUDETIRON-MUDETTRIANGLE:MuDetcombright)-MUDETTRIANGLE:MuDetcombleft"); - mudetcut->SetName("MUDETTRIANGCUT"); - //same, for the thin layers - TGeoCompositeShape *mudetcut1 = new TGeoCompositeShape("MUDETCUT1", "(MUDETIRON1-MUDETTRIANGLE:MuDetcombright)-MUDETTRIANGLE:MuDetcombleft"); - mudetcut1->SetName("MUDETTRIANGCUT1"); - //addition of iron support structures - //support layers, fot thick layers upstream - TGeoBBox *UpperSupport = new TGeoBBox(fUpSuppX/2., fUpSuppY/2.,fZFe/2.); - UpperSupport->SetName("MUDETUPSUPPORT"); - TGeoBBox *LowerSupport = new TGeoBBox(fLowSuppX/2., fLowSuppY/2.,fZFe/2.); - LowerSupport->SetName("MUDETLOWSUPPORT"); - TGeoBBox *LateralSupport = new TGeoBBox(fLatSuppX/2., fLatSuppY/2., fZFe/2.); - LateralSupport->SetName("MUDETLATERALSUPPORT"); - //support layers, for thin layers downstream - TGeoBBox *UpperSupport1 = new TGeoBBox(fUpSuppX/2., fUpSuppY/2.,fZFethin/2.); //The 1 shapes have less z thickness - UpperSupport1->SetName("MUDETUPSUPPORT1"); - TGeoBBox *LowerSupport1 = new TGeoBBox(fLowSuppX/2., fLowSuppY/2.,fZFethin/2.); - LowerSupport1->SetName("MUDETLOWSUPPORT1"); - TGeoBBox *LateralSupport1 = new TGeoBBox(fLatSuppX/2., fLatSuppY/2.,fZFethin/2.); - LateralSupport1->SetName("MUDETLATERALSUPPORT1"); - //Translations (left is considered from the beam, positive x) - - TGeoTranslation * upright = new TGeoTranslation("MuDetupright",-fXFe/2.+fUpSuppX/2.,fYFe/2+fUpSuppY/2.,0); - TGeoTranslation * upleft = new TGeoTranslation("MuDetupleft",+fXFe/2.-fUpSuppX/2.,fYFe/2+fUpSuppY/2.,0); - TGeoTranslation * lateralupleft = new TGeoTranslation("MuDetlateralupleft",+fXFe/2.+fLowSuppX/2.,fYFe/2-fLowSuppY/2.-fYSpacing,0); - TGeoTranslation * lateralupright = new TGeoTranslation("MuDetlateralupright",-fXFe/2.-fLowSuppX/2.,fYFe/2-fLowSuppY/2.-fYSpacing,0); - TGeoTranslation * laterallowleft = new TGeoTranslation("MuDetlaterallowleft",+fXFe/2.+fLowSuppX/2.,-fYFe/2+fLowSuppY/2.+fYSpacing,0); - TGeoTranslation * laterallowright = new TGeoTranslation("MuDetlaterallowright",-fXFe/2.-fLowSuppX/2.,-fYFe/2+fLowSuppY/2.+fYSpacing,0); - TGeoTranslation * lowright = new TGeoTranslation("MuDetlowright",-fXFe/2.+fLowSuppX/2.,-fYFe/2-fLowSuppY/2.,0); - TGeoTranslation * lowleft = new TGeoTranslation("MuDetlowleft",+fXFe/2.-fLowSuppX/2.,-fYFe/2-fLowSuppY/2.,0); - //necessary to put SetName, otherwise it will not find them - upright->SetName("MuDetupright"); - upright->RegisterYourself(); - upleft->SetName("MuDetupleft"); - upleft->RegisterYourself(); - lowright->SetName("MuDetlowright"); - lowright->RegisterYourself(); - lowleft->SetName("MuDetlowleft"); - lowleft->RegisterYourself(); - - lateralupleft->SetName("MuDetlateralupleft"); - lateralupleft->RegisterYourself(); - lateralupright->SetName("MuDetlateralupright"); - lateralupright->RegisterYourself(); - laterallowleft->SetName("MuDetlaterallowleft"); - laterallowleft->RegisterYourself(); - laterallowright->SetName("MuDetlaterallowright"); - laterallowright->RegisterYourself(); - //building composite shapes, writing compositions as TString first to improve readibility - TString *supportaddition = new TString("MUDETTRIANGCUT+MUDETUPSUPPORT:MuDetupright+MUDETUPSUPPORT:MuDetupleft+MUDETLOWSUPPORT:MuDetlowright+MUDETLOWSUPPORT:MuDetlowleft+MUDETLATERALSUPPORT:MuDetlateralupleft+MUDETLATERALSUPPORT:MuDetlateralupright+MUDETLATERALSUPPORT:MuDetlaterallowleft+MUDETLATERALSUPPORT:MuDetlaterallowright"); - TString *supportaddition1 = new TString("MUDETTRIANGCUT1+MUDETUPSUPPORT1:MuDetupright+MUDETUPSUPPORT1:MuDetupleft+MUDETLOWSUPPORT1:MuDetlowright+MUDETLOWSUPPORT1:MuDetlowleft+MUDETLOWSUPPORT1:MuDetlowleft+MUDETLATERALSUPPORT1:MuDetlateralupleft+MUDETLATERALSUPPORT1:MuDetlateralupright+MUDETLATERALSUPPORT1:MuDetlaterallowleft+MUDETLATERALSUPPORT1:MuDetlaterallowright"); - TGeoCompositeShape * SupportedIronLayer = new TGeoCompositeShape("SupportedIronLayer",supportaddition->Data()); - TGeoCompositeShape * SupportedIronLayer1 = new TGeoCompositeShape("SupportedIronLayer1",supportaddition1->Data()); - - TGeoVolume *MudetIronLayer = new TGeoVolume("MudetIronLayer", SupportedIronLayer, Iron); - MudetIronLayer->SetLineColor(kRed+2); - TGeoVolume *MudetIronLayer1 = new TGeoVolume("MudetIronLayer1", SupportedIronLayer1, Iron); - MudetIronLayer1->SetLineColor(kRed+2); - - for(Int_t i = 0; i < fNFe; i++) - { - double dz = -fZtot/2+i*fZFe+fZFe/2+i*fZRpc; - volMudetBox->AddNode(MudetIronLayer,nr + 100 + i, new TGeoTranslation(0, 0, dz)); - } - for(Int_t i = 0; i < fNFethin; i++) - { - double dz = -fZtot/2+fNFe*(fZRpc+fZFe)+i*fZFethin+fZFethin/2+i*fZRpc; - volMudetBox->AddNode(MudetIronLayer1,nr + 100 + fNFe + i, new TGeoTranslation(0, 0,dz)); - } - //*****************************RPC LAYERS**************************************** - - TGeoBBox *RpcContainer_0 = new TGeoBBox("RpcContainer", fXRpc_outer/2, fYRpc_outer/2, fZRpc/2); - RpcContainer_0->SetName("RPCCOINTAINER_0"); - - /* - TGeoBBox *Strip = new TGeoBBox("Strip",fXStrip/2, fYStrip/2, fZStrip/2); - TGeoVolume *volStrip = new TGeoVolume("volStrip",Strip,Cu); - volStrip->SetLineColor(kGreen); - volRpcContainer->AddNode(volStrip,1,new TGeoTranslation (0,0,-3.25*mm)); - volRpcContainer->AddNode(volStrip,2,new TGeoTranslation (0,0,3.25*mm)); - TGeoBBox *PETinsulator = new TGeoBBox("PETinsulator", fXPet/2, fYPet/2, fZPet/2); - TGeoVolume *volPETinsulator = new TGeoVolume("volPETinsulator", PETinsulator, bakelite); - volPETinsulator->SetLineColor(kYellow); - volRpcContainer->AddNode(volPETinsulator,1,new TGeoTranslation(0,0,-3.1*mm)); - volRpcContainer->AddNode(volPETinsulator,2,new TGeoTranslation(0,0, 3.1*mm)); - TGeoBBox *Electrode = new TGeoBBox("Electrode",fXEle/2, fYEle/2, fZEle/2); - TGeoVolume *volElectrode = new TGeoVolume("volElectrode",Electrode,bakelite); - volElectrode->SetLineColor(kGreen); - volRpcContainer->AddNode(volElectrode,1,new TGeoTranslation(0,0,-2*mm)); - volRpcContainer->AddNode(volElectrode,2,new TGeoTranslation(0,0, 2*mm)); - TGeoBBox *RpcGas = new TGeoBBox("RpcGas", fXRpcGap/2, fYRpc_inner/2, fZGas/2); - TGeoVolume *volRpc = new TGeoVolume("volRpc",RpcGas,RPCmat); - volRpc->SetLineColor(kCyan); - volRpcContainer->AddNode(volRpc,1,new TGeoTranslation(0,0,0)); - */ - - TGeoBBox *RpcOuter = new TGeoBBox("RpcOuter", fXRpc_outer/2, fYRpc_outer/2, fZRpc_outer/2); - RpcOuter->SetName("RPCOUTER"); - TGeoTrd2 *Indentation = new TGeoTrd2("Indentation", (fYRpc_outer- 2*(31.2*cm+15.*cm))/2, (fYRpc_outer-2*31.2*cm)/2, (fZRpc_outer+0.1*cm)/2,(fZRpc_outer+0.1*cm)/2,(15.*cm+0.1*cm)/2); // (b, B, Z_up, Z_down, h) - Indentation->SetName("INDENTATION"); - const TGeoTranslation leftindent("leftindent", (fXRpc_outer-15.*cm)/2, 0, 0); - TGeoCombiTrans* left_ind = new TGeoCombiTrans(leftindent, rot); - left_ind->SetName("LEFTINDENT"); - left_ind->RegisterYourself(); - const TGeoTranslation rightindent("rightindent", (-fXRpc_outer+15.*cm)/2, 0, 0); - TGeoCombiTrans* right_ind = new TGeoCombiTrans(rightindent, rot1); - right_ind->SetName("RIGHTINDENT"); - right_ind->RegisterYourself(); - TGeoBBox *RpcInner = new TGeoBBox("RpcInner", fXRpc_inner/2, fYRpc_inner/2, fZRpc_inner/2); - RpcInner->SetName("RPCINNER"); - TGeoTranslation *exclusion = new TGeoTranslation(0, 0, (-fZRpc_inner/2) -0.6*cm); - exclusion->SetName("EXCLUSION"); - exclusion->RegisterYourself(); - TGeoCompositeShape *RpcShell = new TGeoCompositeShape("RpcShell", "RPCOUTER-INDENTATION:RIGHTINDENT-INDENTATION:LEFTINDENT-RPCINNER:EXCLUSION"); - TGeoVolume *volRpcShell = new TGeoVolume("volRpcShell", RpcShell, Al); - volRpcShell->SetLineColor(kGray); - - TGeoBBox *GasShape = new TGeoBBox("GasShape", fXRpcGap/2, fYRpc_inner/2, fZGas/2); - GasShape->SetName("RPCGAS"); - TGeoBBox *GapSpacing = new TGeoBBox("GapSpacing", fXRpcGap/2, 6./2*cm, (fZGas+0.01*cm)/2 ); - GapSpacing->SetName("GAPSPACE"); - TGeoTranslation *mdown = new TGeoTranslation("mdown", 0., -(fYRpcGap+6*cm)/2, 0.); // 6 cm is the spacing between two gaps - mdown->SetName("MDOWN"); - mdown->RegisterYourself(); - TGeoTranslation *mup = new TGeoTranslation("mup",0., (fYRpcGap+6*cm)/2, 0.); - mup->SetName("MUP"); - mup->RegisterYourself(); - TGeoCompositeShape *RpcGas = new TGeoCompositeShape("RpcGas", "RPCGAS-GAPSPACE:MUP-GAPSPACE:MDOWN"); - TGeoVolume *volRpc = new TGeoVolume("volRpc",RpcGas, RPCmat); - volRpc->SetLineColor(kCyan); - - //****RPC container framing********* - TGeoTrd2 *Indentation_0 = new TGeoTrd2("Indentation_0", (fYRpc_outer- 2*(31.2*cm+15.*cm))/2, (fYRpc_outer-2*31.2*cm)/2, (fZRpc)/2,(fZRpc)/2,(15.*cm+0.1*cm)/2); - Indentation_0->SetName("INDENTATION_0"); - TGeoCompositeShape *RpcContainer = new TGeoCompositeShape("RpcContainer", "RPCCOINTAINER_0-INDENTATION_0:RIGHTINDENT-INDENTATION_0:LEFTINDENT"); - TGeoVolume *volRpcContainer = new TGeoVolume("volRpcContainer",RpcContainer,air); - //*********************************** - - TGeoBBox *GapShape = new TGeoBBox("GapShape", fXRpcGap/2, fYRpc_inner/2, fZRpcGap/2); - GapShape->SetName("RPCGAP"); - TGeoBBox *GapSpacing1 = new TGeoBBox("GapSpacing1", fXRpcGap/2, 6./2*cm, (fZRpcGap+0.01*cm)/2); - GapSpacing1->SetName("GAPSPACE1"); - TGeoCompositeShape *RpcGap = new TGeoCompositeShape("RpcGap", "RPCGAP-GAPSPACE1:MUP-GAPSPACE1:MDOWN"); - TGeoVolume *volRpcGap = new TGeoVolume("volRpcGap",RpcGap, bakelite); - volRpcGap->SetLineColor(kOrange); - - TGeoBBox *Strip = new TGeoBBox("Strip", fXRpc_inner/2, fYRpc_inner/2, fZStrip/2); - TGeoVolume *volStrip= new TGeoVolume("volStrip", Strip, Cu); - volStrip->SetLineColor(kOrange+5); - TGeoRotation rot2("rot2", 0., 0.,0.); - rot2.RotateY(180); - const TGeoTranslation trans_rot(0., 0., fZGas/2+fZRpcGap+fZStrip+fZRpc_outer/2); - TGeoCombiTrans *comb_1 = new TGeoCombiTrans(trans_rot, rot2); - - volRpcContainer->AddNode(volRpcShell,1, new TGeoTranslation(0., 0., -fZGas/2-fZRpcGap-fZStrip-fZRpc_outer/2)); - volRpcContainer->AddNode(volRpcShell,2, comb_1); - volRpcContainer->AddNode(volStrip, 1, new TGeoTranslation(0., 0., fZGas/2+fZRpcGap+fZStrip/2)); - volRpcContainer->AddNode(volStrip, 2, new TGeoTranslation(0., 0., -fZGas/2-fZRpcGap-fZStrip/2)); - volRpcContainer->AddNode(volRpcGap, 1, new TGeoTranslation(0., 0., (fZGas+fZRpcGap)/2)); - volRpcContainer->AddNode(volRpcGap, 2, new TGeoTranslation(0., 0., -(fZGas+fZRpcGap)/2)); - volRpcContainer->AddNode(volRpc, 1, new TGeoTranslation(0., 0., 0.)); - - AddSensitiveVolume(volRpc); - - for(Int_t i = 0; i < fNRpc; i++) - { - double dy = 5.*cm; - double dz = -fZtot/2 + (i+1)*fZFe + i*fZRpc + fZRpc/2; - if (i >= fNFe) dz = dz - (i + 1 - fNFe) * (fZFe - fZFethin); - if(i%2)volMudetBox->AddNode(volRpcContainer,nr + i,new TGeoTranslation(0, -dy, dz)); //staggering - else{volMudetBox->AddNode(volRpcContainer,nr + i,new TGeoTranslation(0, dy, dz));} - } - - TGeoBBox *Pillar1Box = new TGeoBBox(fPillarX/2,fPillarY/2, fPillarZ/2); - TGeoVolume *Pillar1Vol = new TGeoVolume("Pillar1Vol",Pillar1Box,Steel); - Pillar1Vol->SetLineColor(kGreen+3); - - //tTauNuDet->AddNode(Pillar1Vol,1, new TGeoTranslation(-fXtot/2+fPillarX/2,-fYtot/2-fPillarY/2,fZcenter-fZtot/2+fPillarZ/2)); - //tTauNuDet->AddNode(Pillar1Vol,2, new TGeoTranslation(fXtot/2-fPillarX/2,-fYtot/2-fPillarY/2,fZcenter-fZtot/2 +fPillarZ/2)); - // tTauNuDet->AddNode(Pillar1Vol,3, new TGeoTranslation(-fXtot/2+fPillarX/2,-fYtot/2-fPillarY/2,fZcenter+fZtot/2-fPillarZ/2)); //eventually two pillars at the end. Now muon det is followed by veto, so its steel pillar supports both - //tTauNuDet->AddNode(Pillar1Vol,4, new TGeoTranslation(fXtot/2-fPillarX/2,-fYtot/2-fPillarY/2,fZcenter+fZtot/2-fPillarZ/2)); + if (fDesign == 4) { + // Now the filter is replaced by a magnetic spectrometer + + TGeoBBox* MuFilter = new TGeoBBox("MuFilter", fXtot / 2., fYtot / 2., fZtot / 2.); + TGeoVolume* volMuFilter = new TGeoVolume("volMuFilter", MuFilter, air); // MuFilter + volMuFilter->SetLineColor(kGray); + + TGeoUniformMagField* magcheckfield = new TGeoUniformMagField(fField, 0., 0.); // along x direction; + + tTauNuDet->AddNode(volMuFilter, 1, new TGeoTranslation(0, 0, fZcenter)); + + // adapting code from AdvSND + // code by Daniele from ADVSND air core magnet + Double_t fOutMagX = fXtot; + Double_t fOutMagY = fYtot; + Double_t fMagZ = fZtot - 0.5 * 2; + + Double_t fInMagX = fXRpc; + Double_t fInMagY = fYRpc; + + TGeoBBox* RPC = new TGeoBBox("RPC", fXRpc / 2., fYRpc / 2., fZRpc / 2.); + TGeoVolume* volRPC = new TGeoVolume("volRPC", RPC, RPCmat); // RPC + volRPC->SetLineColor(kRed); + AddSensitiveVolume(volRPC); + // applying the values in the geometry + + // Shapes creation + [[maybe_unused]] auto* CoilContainer = new TGeoBBox("CoilContainer", fOutMagX / 2., fOutMagY / 2., fMagZ / 2.); + TGeoBBox* MagRegion = new TGeoBBox("MagRegion", fInMagX / 2., fInMagY / 2., fMagZ / 2. + 0.5); + TGeoBBox* Coil = new TGeoBBox("Coil", fCoilW / 2., fCoilH / 2., fMagZ / 2. + 0.5); + + // Translations + TGeoTranslation* CoilUpPos = new TGeoTranslation("CoilUpPos", 0, (fInMagY + fCoilH) / 2. - 0.001, 0); + TGeoTranslation* CoilDownPos = new TGeoTranslation("CoilDownPos", 0, -(fInMagY + fCoilH) / 2. + 0.001, 0); + CoilUpPos->RegisterYourself(); + CoilDownPos->RegisterYourself(); + + // Yoke shape + TGeoCompositeShape* FeYoke = + new TGeoCompositeShape("FeYoke", "CoilContainer-MagRegion-(Coil:CoilUpPos)-(Coil:CoilDownPos)"); + + // Volumes + TGeoVolume* volFeYoke = new TGeoVolume("volFeYoke", FeYoke, Iron); + volFeYoke->SetLineColor(kGray); + TGeoVolume* volCoil = new TGeoVolume("volCoil", Coil, Cu); + volCoil->SetLineColor(kOrange + 1); + TGeoVolume* volMagRegion = new TGeoVolume("volMagRegion", MagRegion, air); + volMagRegion->SetField(magcheckfield); + + // Positioning + volMuFilter->AddNode(volFeYoke, 0); + volMuFilter->AddNode(volCoil, 0, new TGeoTranslation(0, (fInMagY + fCoilH) / 2. - 0.001, 0)); + volMuFilter->AddNode(volCoil, 1, new TGeoTranslation(0, -(fInMagY + fCoilH) / 2. + 0.001, 0)); + volMuFilter->AddNode(volMagRegion, 0, 0); + + volMagRegion->SetField(magcheckfield); + // first two counters upstream + volMagRegion->AddNode(volRPC, 1, new TGeoTranslation(0, 0, -fZtot / 2. + fZRpc / 2.)); + // magnetized region in the first quarter + volMagRegion->AddNode( + volRPC, + 2, + new TGeoTranslation( + 0, 0, -fZtot / 4. - fGapMiddle / 2. - fZRpc / 2.)); // these are INSIDE the magnetized region + volMagRegion->AddNode(volRPC, 3, new TGeoTranslation(0, 0, -fZtot / 4. + fGapMiddle / 2. + fZRpc / 2.)); + // magnetized region in the middle + volMagRegion->AddNode( + volRPC, + 4, + new TGeoTranslation(0, 0, -fGapMiddle / 2. - fZRpc / 2.)); // these are INSIDE the magnetized region + volMagRegion->AddNode(volRPC, 5, new TGeoTranslation(0, 0, +fGapMiddle / 2. + fZRpc / 2.)); + // magnetized region in the third quarter + volMagRegion->AddNode( + volRPC, + 6, + new TGeoTranslation( + 0, 0, +fZtot / 4. - fGapMiddle / 2. - fZRpc / 2.)); // these are INSIDE the magnetized region + volMagRegion->AddNode(volRPC, 7, new TGeoTranslation(0, 0, +fZtot / 4. + fGapMiddle / 2. + fZRpc / 2.)); + // last two counters downstream + volMagRegion->AddNode(volRPC, 8, new TGeoTranslation(0, 0, +fZtot / 2. - fZRpc / 2.)); + + } // end option 4 +} +Bool_t NuTauMudet::ProcessHits(FairVolume* vol) +{ + /** This method is called from the MC stepping */ + // Set parameters at entrance of volume. Reset ELoss. + if (gMC->IsTrackEntering()) { + fELoss = 0.; + fTime = gMC->TrackTime() * 1.0e09; + fLength = gMC->TrackLength(); + gMC->TrackPosition(fPos); + gMC->TrackMomentum(fMom); + } + // Sum energy loss for all steps in the active volume + fELoss += gMC->Edep(); + + // Create muonPoint at exit of active volume + if (gMC->IsTrackExiting() || gMC->IsTrackStop() || gMC->IsTrackDisappeared()) { + fTrackID = gMC->GetStack()->GetCurrentTrackNumber(); + fVolumeID = vol->getMCid(); + if (fELoss == 0.) { + return kFALSE; + } + TParticle* p = gMC->GetStack()->GetCurrentTrack(); + Int_t pdgCode = p->GetPdgCode(); + Int_t detID = 0; + gMC->CurrentVolID(detID); + // cutting this part, does not work in this new layout, since we only have simple planes + // cout<<"THIS HIT"<GetMother(1)->GetNumber();} + else{motherID = gGeoManager->GetMother(0)->GetNumber();} + // This up here is made because of a strange behaviour of the script, volRpc gets different + //Mother volume number even if it has the correct path + const char *mumname = gMC->CurrentVolOffName(1);*/ + // cout<SetLineColor(kGray); - - TGeoUniformMagField *magcheckfield = new TGeoUniformMagField(fField,0.,0.); //along x direction; - - tTauNuDet->AddNode(volMuFilter,1,new TGeoTranslation(0,0,fZcenter)); - - //adapting code from AdvSND - //code by Daniele from ADVSND air core magnet - Double_t fOutMagX = fXtot; - Double_t fOutMagY = fYtot; - Double_t fMagZ = fZtot-0.5*2; - - Double_t fInMagX = fXRpc; - Double_t fInMagY = fYRpc; - - TGeoBBox *RPC = new TGeoBBox("RPC", fXRpc/2.,fYRpc/2.,fZRpc/2.); - TGeoVolume *volRPC = new TGeoVolume("volRPC",RPC,RPCmat); //RPC - volRPC->SetLineColor(kRed); - AddSensitiveVolume(volRPC); - //applying the values in the geometry - - - // Shapes creation - [[maybe_unused]] auto *CoilContainer = new TGeoBBox("CoilContainer", fOutMagX/2., fOutMagY/2., fMagZ/2.); - TGeoBBox *MagRegion = new TGeoBBox("MagRegion", fInMagX/2., fInMagY/2., fMagZ/2.+0.5); - TGeoBBox *Coil = new TGeoBBox("Coil", fCoilW/2., fCoilH/2., fMagZ/2.+0.5); - - // Translations - TGeoTranslation *CoilUpPos = new TGeoTranslation("CoilUpPos", 0, (fInMagY+fCoilH)/2.-0.001, 0); - TGeoTranslation *CoilDownPos = new TGeoTranslation("CoilDownPos", 0, -(fInMagY+fCoilH)/2.+0.001, 0); - CoilUpPos->RegisterYourself(); - CoilDownPos->RegisterYourself(); - - // Yoke shape - TGeoCompositeShape *FeYoke = new TGeoCompositeShape("FeYoke", "CoilContainer-MagRegion-(Coil:CoilUpPos)-(Coil:CoilDownPos)"); - - // Volumes - TGeoVolume *volFeYoke = new TGeoVolume("volFeYoke", FeYoke, Iron); - volFeYoke->SetLineColor(kGray); - TGeoVolume *volCoil = new TGeoVolume("volCoil", Coil, Cu); - volCoil->SetLineColor(kOrange+1); - TGeoVolume *volMagRegion = new TGeoVolume("volMagRegion", MagRegion, air); - volMagRegion->SetField(magcheckfield); - - // Positioning - volMuFilter->AddNode(volFeYoke, 0); - volMuFilter->AddNode(volCoil, 0, new TGeoTranslation(0, (fInMagY+fCoilH)/2.-0.001, 0)); - volMuFilter->AddNode(volCoil, 1, new TGeoTranslation(0, -(fInMagY+fCoilH)/2.+0.001, 0)); - volMuFilter->AddNode(volMagRegion, 0, 0); - - volMagRegion->SetField(magcheckfield); - //first two counters upstream - volMagRegion->AddNode(volRPC,1,new TGeoTranslation(0,0,-fZtot/2. + fZRpc/2.)); - //magnetized region in the first quarter - volMagRegion->AddNode(volRPC,2,new TGeoTranslation(0,0,-fZtot/4.-fGapMiddle/2. - fZRpc/2.)); //these are INSIDE the magnetized region - volMagRegion->AddNode(volRPC,3,new TGeoTranslation(0,0,-fZtot/4.+fGapMiddle/2. + fZRpc/2.)); - //magnetized region in the middle - volMagRegion->AddNode(volRPC,4,new TGeoTranslation(0,0,-fGapMiddle/2. - fZRpc/2.)); //these are INSIDE the magnetized region - volMagRegion->AddNode(volRPC,5,new TGeoTranslation(0,0,+fGapMiddle/2. + fZRpc/2.)); - //magnetized region in the third quarter - volMagRegion->AddNode(volRPC,6,new TGeoTranslation(0,0,+fZtot/4.-fGapMiddle/2. - fZRpc/2.)); //these are INSIDE the magnetized region - volMagRegion->AddNode(volRPC,7,new TGeoTranslation(0,0,+fZtot/4.+fGapMiddle/2. + fZRpc/2.)); - //last two counters downstream - volMagRegion->AddNode(volRPC,8,new TGeoTranslation(0,0,+fZtot/2. - fZRpc/2.)); - - } //end option 4 - -} - - -Bool_t NuTauMudet::ProcessHits(FairVolume* vol) -{ - /** This method is called from the MC stepping */ - //Set parameters at entrance of volume. Reset ELoss. - if ( gMC->IsTrackEntering() ) { - fELoss = 0.; - fTime = gMC->TrackTime() * 1.0e09; - fLength = gMC->TrackLength(); - gMC->TrackPosition(fPos); - gMC->TrackMomentum(fMom); - } - // Sum energy loss for all steps in the active volume - fELoss += gMC->Edep(); - - // Create muonPoint at exit of active volume - if ( gMC->IsTrackExiting() || - gMC->IsTrackStop() || - gMC->IsTrackDisappeared() ) { - fTrackID = gMC->GetStack()->GetCurrentTrackNumber(); - fVolumeID = vol->getMCid(); - if (fELoss == 0. ) { return kFALSE; } - TParticle* p=gMC->GetStack()->GetCurrentTrack(); - Int_t pdgCode = p->GetPdgCode(); - Int_t detID=0; - gMC->CurrentVolID(detID); - //cutting this part, does not work in this new layout, since we only have simple planes - //cout<<"THIS HIT"<GetMother(1)->GetNumber();} - else{motherID = gGeoManager->GetMother(0)->GetNumber();} - // This up here is made because of a strange behaviour of the script, volRpc gets different - //Mother volume number even if it has the correct path - const char *mumname = gMC->CurrentVolOffName(1);*/ - //cout<Register("ShipRpcPoint", "NuTauMudet", fShipRpcPointCollection, kTRUE); } // ----- Public method to Decode volume info ------------------------------------------- // ----- returns hpt, arm, rpc numbers ----------------------------------- -void NuTauMudet::DecodeVolumeID(Int_t detID,int &nARM,int &nRPC) +void NuTauMudet::DecodeVolumeID(Int_t detID, int& nARM, int& nRPC) { - nARM = detID/1E4; - nRPC = detID - nARM*1E4; + nARM = detID / 1E4; + nRPC = detID - nARM * 1E4; } TClonesArray* NuTauMudet::GetCollection(Int_t iColl) const { - if (iColl == 0) { return fShipRpcPointCollection; } - else { return NULL; } + if (iColl == 0) { + return fShipRpcPointCollection; + } else { + return NULL; + } } void NuTauMudet::Reset() { - fShipRpcPointCollection->Clear(); + fShipRpcPointCollection->Clear(); } - -ShipRpcPoint* NuTauMudet::AddHit(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t time, Double_t length, - Double_t eLoss, Int_t pdgCode) +ShipRpcPoint* NuTauMudet::AddHit(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t time, + Double_t length, + Double_t eLoss, + Int_t pdgCode) { - TClonesArray& clref = *fShipRpcPointCollection; - Int_t size = clref.GetEntriesFast(); - //cout << "ShipRpctau hit called"<< pos.z()< // for string - -#include "TVector3.h" +#include "FairDetector.h" // for FairDetector +#include "FairModule.h" // for FairModule +#include "Rtypes.h" // for ShipMuonShield::Class, Bool_t, etc #include "TLorentzVector.h" +#include "TVector3.h" + +#include // for string class ShipRpcPoint; class FairVolume; class TClonesArray; -class NuTauMudet:public FairDetector +class NuTauMudet : public FairDetector { public: - NuTauMudet(const char* name, const Double_t Zcenter, Bool_t Active, const char* Title="NuTauMudet"); + NuTauMudet(const char* name, const Double_t Zcenter, Bool_t Active, const char* Title = "NuTauMudet"); NuTauMudet(); virtual ~NuTauMudet(); void SetDesign(Int_t Design); void SetTotDimensions(Double_t X, Double_t Y, Double_t Z); - void SetFeDimensions(Double_t X, Double_t Y, Double_t Z, Double_t Zthin=0.); + void SetFeDimensions(Double_t X, Double_t Y, Double_t Z, Double_t Zthin = 0.); void SetRpcDimensions(Double_t X, Double_t Y, Double_t Z); void SetRpcStripDimensions(Double_t X, Double_t Y, Double_t Z); void SetRpcGasDimensions(Double_t X, Double_t Y, Double_t Z); void SetRpcElectrodeDimensions(Double_t X, Double_t Y, Double_t Z); void SetRpcPETDimensions(Double_t X, Double_t Y, Double_t Z); - void SetNFeInArm(Int_t N, Int_t Nthin= 0); + void SetNFeInArm(Int_t N, Int_t Nthin = 0); void SetNRpcInArm(Int_t N); void SetZDimensionArm(Double_t Z); void SetGapDownstream(Double_t Gap); @@ -39,8 +37,14 @@ class NuTauMudet:public FairDetector void SetReturnYokeDimensions(Double_t X, Double_t Y, Double_t Z); void SetSmallerYokeDimensions(Double_t X, Double_t Y, Double_t Z); void SetCoilParameters(Double_t CoilH, Double_t CoilW, Int_t N, Double_t CoilG); - void SetSupportTransverseDimensions(Double_t UpperSupportX, Double_t UpperSupportY, Double_t LowerSupportX, Double_t LowerSupportY, Double_t LateralSupportX, Double_t LateralSupportY, Double_t YSpacing); - void SetLateralCutSize(Double_t CutHeight , Double_t CutLength); //lateral triangular cuts + void SetSupportTransverseDimensions(Double_t UpperSupportX, + Double_t UpperSupportY, + Double_t LowerSupportX, + Double_t LowerSupportY, + Double_t LateralSupportX, + Double_t LateralSupportY, + Double_t YSpacing); + void SetLateralCutSize(Double_t CutHeight, Double_t CutLength); // lateral triangular cuts void SetPillarDimensions(Double_t X, Double_t Y, Double_t Z); void SetUpperCoverDimensions(Double_t X, Double_t Y, Double_t Z); void SetLateralCoverDimensions(Double_t X, Double_t Y, Double_t Z); @@ -57,88 +61,87 @@ class NuTauMudet:public FairDetector /** this method is called for each step during simulation * (see FairMCApplication::Stepping()) */ - virtual Bool_t ProcessHits( FairVolume* v=0); + virtual Bool_t ProcessHits(FairVolume* v = 0); /** Registers the produced collections in FAIRRootManager. */ - virtual void Register(); + virtual void Register(); /** Gets the produced collections */ - virtual TClonesArray* GetCollection(Int_t iColl) const ; + virtual TClonesArray* GetCollection(Int_t iColl) const; /** has to be called after each event to reset the containers */ - virtual void Reset(); + virtual void Reset(); /** This method is an example of how to add your own point * of type muonPoint to the clones array */ - ShipRpcPoint* AddHit(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t time, Double_t length, - Double_t eLoss, Int_t pdgCode); + ShipRpcPoint* AddHit(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t time, + Double_t length, + Double_t eLoss, + Int_t pdgCode); /** The following methods can be implemented if you need to make * any optional action in your detector during the transport. */ - virtual void CopyClones( TClonesArray* cl1, TClonesArray* cl2 , - Int_t offset) {;} - virtual void SetSpecialPhysicsCuts() {;} - virtual void EndOfEvent(); - virtual void FinishPrimary() {;} - virtual void FinishRun() {;} - virtual void BeginPrimary() {;} - virtual void PostTrack() {;} - virtual void PreTrack() {;} - virtual void BeginEvent() {;} + virtual void CopyClones(TClonesArray* cl1, TClonesArray* cl2, Int_t offset) { ; } + virtual void SetSpecialPhysicsCuts() { ; } + virtual void EndOfEvent(); + virtual void FinishPrimary() { ; } + virtual void FinishRun() { ; } + virtual void BeginPrimary() { ; } + virtual void PostTrack() { ; } + virtual void PreTrack() { ; } + virtual void BeginEvent() { ; } - void DecodeVolumeID(Int_t detID,int &nARM,int &nRPC); - -private: + void DecodeVolumeID(Int_t detID, int& nARM, int& nRPC); + private: /** Track information to be stored until the track leaves the active volume. */ - Int_t fTrackID; //! track index - Int_t fPdgCode; //! pdg code - Int_t fVolumeID; //! volume id - TLorentzVector fPos; //! position at entrance - TLorentzVector fMom; //! momentum at entrance - Double32_t fTime; //! time - Double32_t fLength; //! length - Double32_t fELoss; //! energy loss + Int_t fTrackID; //! track index + Int_t fPdgCode; //! pdg code + Int_t fVolumeID; //! volume id + TLorentzVector fPos; //! position at entrance + TLorentzVector fMom; //! momentum at entrance + Double32_t fTime; //! time + Double32_t fLength; //! length + Double32_t fELoss; //! energy loss /** container for data points */ - TClonesArray* fShipRpcPointCollection; + TClonesArray* fShipRpcPointCollection; Int_t InitMedium(const char* name); - - -protected: - + protected: Int_t fDesign; - Double_t fZcenter; //z distance of the center of the spectrometer in cm from the center of the vacuum tube + Double_t fZcenter; // z distance of the center of the spectrometer in cm from the center of the vacuum tube Double_t fXtot; Double_t fYtot; - Double_t fZtot; //Dimension of the whole magnetic spectrometr (1st + 2nd arm + HPTs) alogn beam axis + Double_t fZtot; // Dimension of the whole magnetic spectrometr (1st + 2nd arm + HPTs) alogn beam axis Int_t fNFe, fNFethin; Int_t fNRpc; Double_t fXFe; Double_t fXRpc; Double_t fYFe; Double_t fYRpc; - Double_t fZFe, fZFethin; // Width of the Iron Slabs - Double_t fZRpc; // Width of the Rpc planes - Double_t fZArm; // Width of the Spectrometer Arms - Double_t fGapDown; //distance between the end of the second arm of the spectrometer and the decay vessel - Double_t fGapMiddle; // distance between the two arms of the spectrometer + Double_t fZFe, fZFethin; // Width of the Iron Slabs + Double_t fZRpc; // Width of the Rpc planes + Double_t fZArm; // Width of the Spectrometer Arms + Double_t fGapDown; // distance between the end of the second arm of the spectrometer and the decay vessel + Double_t fGapMiddle; // distance between the two arms of the spectrometer Double_t fField; Double_t fXRyoke; Double_t fYRyoke; Double_t fZRyoke; - //Dimensions of the smaller part of the yoke + // Dimensions of the smaller part of the yoke Double_t fXRyoke_s; Double_t fYRyoke_s; Double_t fZRyoke_s; @@ -148,7 +151,7 @@ class NuTauMudet:public FairDetector Double_t fCoilW; Int_t fNCoil; - //Dimension for detailed RPC simulation: + // Dimension for detailed RPC simulation: Double_t fXStrip; Double_t fYStrip; Double_t fZStrip; @@ -161,50 +164,45 @@ class NuTauMudet:public FairDetector Double_t fXGas; Double_t fYGas; Double_t fZGas; - Double_t fUpSuppX, fUpSuppY;//Dimensions of iron support structures + Double_t fUpSuppX, fUpSuppY; // Dimensions of iron support structures Double_t fLowSuppX, fLowSuppY; - Double_t fLatSuppX, fLatSuppY; //lateral supports + Double_t fLatSuppX, fLatSuppY; // lateral supports Double_t fYSpacing; - Double_t fCutHeight, fCutLength; //Cut dimensions - //Dimension of steel pillars + Double_t fCutHeight, fCutLength; // Cut dimensions + // Dimension of steel pillars Double_t fPillarX; Double_t fPillarY; Double_t fPillarZ; - //Dimension of upper cover on the RPC + // Dimension of upper cover on the RPC Double_t fXCov; Double_t fYCov; Double_t fZCov; - //Dimension of lateral covers on RPC + // Dimension of lateral covers on RPC Double_t fXLateral; Double_t fYLateral; Double_t fZLateral; - //Dimension of lateral crosses on RPC + // Dimension of lateral crosses on RPC Double_t fXCross; Double_t fYCross; Double_t fZCross; Double_t fWidthArm; - //Dimension of outer frame of RPC + // Dimension of outer frame of RPC Double_t fXRpc_outer; Double_t fYRpc_outer; Double_t fZRpc_outer; - //Dimension of inner frame of RPC + // Dimension of inner frame of RPC Double_t fXRpc_inner; Double_t fYRpc_inner; Double_t fZRpc_inner; - //Dimension of gaps in RPC + // Dimension of gaps in RPC Double_t fXRpcGap; Double_t fYRpcGap; Double_t fZRpcGap; - - NuTauMudet(const NuTauMudet&); NuTauMudet& operator=(const NuTauMudet&); - ClassDef(NuTauMudet,8) - + ClassDef(NuTauMudet, 8) }; - - -#endif //NuTauMudet_H +#endif // NuTauMudet_H diff --git a/nutaudet/NutaudetContFact.cxx b/nutaudet/NutaudetContFact.cxx index aec8ba3983..a5e8b4bc57 100644 --- a/nutaudet/NutaudetContFact.cxx +++ b/nutaudet/NutaudetContFact.cxx @@ -10,54 +10,51 @@ ///////////////////////////////////////////////////////////// #include "NutaudetContFact.h" -#include "FairRuntimeDb.h" // for FairRuntimeDb +#include "FairRuntimeDb.h" // for FairRuntimeDb +#include "TList.h" // for TList +#include "TString.h" // for TString -#include "TList.h" // for TList -#include "TString.h" // for TString - -#include // for strcmp, NULL +#include // for strcmp, NULL class FairParSet; using namespace std; - -//static NutaudetContFact gNutaudetContFact; +// static NutaudetContFact gNutaudetContFact; NutaudetContFact::NutaudetContFact() - : FairContFact() + : FairContFact() { - // Constructor (called when the library is loaded) - fName="NutaudetContFact"; - fTitle="Factory for parameter containers in libTauSensitive"; - setAllContainers(); - FairRuntimeDb::instance()->addContFactory(this); + // Constructor (called when the library is loaded) + fName = "NutaudetContFact"; + fTitle = "Factory for parameter containers in libTauSensitive"; + setAllContainers(); + FairRuntimeDb::instance()->addContFactory(this); } void NutaudetContFact::setAllContainers() { - /** Creates the Container objects with all accepted contexts and adds them to - * the list of containers for the STS library.*/ + /** Creates the Container objects with all accepted contexts and adds them to + * the list of containers for the STS library.*/ - FairContainer* p= new FairContainer("FairGeoTauSensitivePar", - "TauSensitive Geometry Parameters", - "TestDefaultContext"); - p->addContext("TestNonDefaultContext"); + FairContainer* p = + new FairContainer("FairGeoTauSensitivePar", "TauSensitive Geometry Parameters", "TestDefaultContext"); + p->addContext("TestNonDefaultContext"); - containers->Add(p); + containers->Add(p); } FairParSet* NutaudetContFact::createContainer(FairContainer* c) { - /** Calls the constructor of the corresponding parameter container. - * For an actual context, which is not an empty string and not the default context - * of this container, the name is concatinated with the context. */ - /* const char* name=c->GetName(); - FairParSet* p=NULL; - if (strcmp(name,"FairGeoTauSensitivePar")==0) { - p=new FairGeoTauSensitivePar(c->getConcatName().Data(),c->GetTitle(),c->getContext()); - } - return p; -*/ - return 0; + /** Calls the constructor of the corresponding parameter container. + * For an actual context, which is not an empty string and not the default context + * of this container, the name is concatinated with the context. */ + /* const char* name=c->GetName(); + FairParSet* p=NULL; + if (strcmp(name,"FairGeoTauSensitivePar")==0) { + p=new FairGeoTauSensitivePar(c->getConcatName().Data(),c->GetTitle(),c->getContext()); + } + return p; + */ + return 0; } diff --git a/nutaudet/NutaudetContFact.h b/nutaudet/NutaudetContFact.h index dc00264a0a..bdf15ea488 100644 --- a/nutaudet/NutaudetContFact.h +++ b/nutaudet/NutaudetContFact.h @@ -1,9 +1,8 @@ #ifndef NUTAUDETCONTFACT_H #define NUTAUDETCONTFACT_H -#include "FairContFact.h" // for FairContFact, etc - -#include "Rtypes.h" // for ShipPassiveContFact::Class, etc +#include "FairContFact.h" // for FairContFact, etc +#include "Rtypes.h" // for ShipPassiveContFact::Class, etc class FairParSet; @@ -11,11 +10,12 @@ class NutaudetContFact : public FairContFact { private: void setAllContainers(); + public: NutaudetContFact(); ~NutaudetContFact() {} FairParSet* createContainer(FairContainer*); - ClassDef(NutaudetContFact,0) // Factory for all Passive parameter containers + ClassDef(NutaudetContFact, 0) // Factory for all Passive parameter containers }; -#endif /* !PNDPASSIVECONTFACT_H */ +#endif /* !PNDPASSIVECONTFACT_H */ diff --git a/nutaudet/ShipRpcPoint.cxx b/nutaudet/ShipRpcPoint.cxx index 83bde1a8d8..a89745ead4 100644 --- a/nutaudet/ShipRpcPoint.cxx +++ b/nutaudet/ShipRpcPoint.cxx @@ -4,48 +4,47 @@ using std::cout; using std::endl; - // ----- Default constructor ------------------------------------------- ShipRpcPoint::ShipRpcPoint() - : FairMCPoint() -{ -} + : FairMCPoint() +{} // ------------------------------------------------------------------------- // ----- Standard constructor ------------------------------------------ /*ShipRpcPoint::ShipRpcPoint(Int_t trackID, Int_t detID, TVector3 pos, TVector3 mom, Double_t tof, Double_t length, - Double_t eLoss, Int_t pdgcode, Int_t nArm, Int_t nRpc, Int_t nHpt) + Double_t eLoss, Int_t pdgcode, Int_t nArm, Int_t nRpc, Int_t nHpt) : FairMCPoint(trackID, detID, pos, mom, tof, length, eLoss), fPdgCode(pdgcode), fNArm(nArm), fNRpc(nRpc), fNHpt(nHpt) { } */ -ShipRpcPoint::ShipRpcPoint(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t tof, Double_t length, - Double_t eLoss, Int_t pdgcode) - : FairMCPoint(trackID, detID, pos, mom, tof, length, eLoss), fPdgCode(pdgcode) -{ -} +ShipRpcPoint::ShipRpcPoint(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t tof, + Double_t length, + Double_t eLoss, + Int_t pdgcode) + : FairMCPoint(trackID, detID, pos, mom, tof, length, eLoss) + , fPdgCode(pdgcode) +{} // ------------------------------------------------------------------------- // ----- Destructor ---------------------------------------------------- -ShipRpcPoint::~ShipRpcPoint() { } +ShipRpcPoint::~ShipRpcPoint() {} // ------------------------------------------------------------------------- // ----- Public method Print ------------------------------------------- void ShipRpcPoint::Print(const Option_t* opt) const { - cout << "-I- ShipRpcPoint: ShipRpc point for track " << fTrackID - << " in detector " << fDetectorID << endl; - cout << " Position (" << fX << ", " << fY << ", " << fZ - << ") cm" << endl; - cout << " Momentum (" << fPx << ", " << fPy << ", " << fPz - << ") GeV" << endl; - cout << " Time " << fTime << " ns, Length " << fLength - << " cm, Energy loss " << fELoss*1.0e06 << " keV" << endl; + cout << "-I- ShipRpcPoint: ShipRpc point for track " << fTrackID << " in detector " << fDetectorID << endl; + cout << " Position (" << fX << ", " << fY << ", " << fZ << ") cm" << endl; + cout << " Momentum (" << fPx << ", " << fPy << ", " << fPz << ") GeV" << endl; + cout << " Time " << fTime << " ns, Length " << fLength << " cm, Energy loss " << fELoss * 1.0e06 << " keV" + << endl; } // ------------------------------------------------------------------------- diff --git a/nutaudet/ShipRpcPoint.h b/nutaudet/ShipRpcPoint.h index 28bafa05f0..f69deb5711 100644 --- a/nutaudet/ShipRpcPoint.h +++ b/nutaudet/ShipRpcPoint.h @@ -1,9 +1,7 @@ #ifndef RPCPOINT_H #define RPCPOINT_H 1 - #include "FairMCPoint.h" - #include "TObject.h" #include "TVector3.h" @@ -11,11 +9,9 @@ class ShipRpcPoint : public FairMCPoint { public: - /** Default constructor **/ ShipRpcPoint(); - /** Constructor with arguments *@param trackID Index of MCTrack *@param detID Detector ID @@ -29,21 +25,26 @@ class ShipRpcPoint : public FairMCPoint Double_t tof, Double_t length, Double_t eLoss, Int_t pdgcode, Int_t nArm, Int_t nRpc, Int_t nHpt); */ - ShipRpcPoint(Int_t trackID, Int_t detID, TVector3 pos, TVector3 mom, - Double_t tof, Double_t length, Double_t eLoss, Int_t pdgcode); - + ShipRpcPoint(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t tof, + Double_t length, + Double_t eLoss, + Int_t pdgcode); /** Destructor **/ virtual ~ShipRpcPoint(); /** Output to screen **/ virtual void Print(const Option_t* opt) const; - Int_t PdgCode() const {return fPdgCode;} -/* - Int_t NArm() const {return fNArm;} - Int_t NRpc() const {return fNRpc;} - Int_t NHpt() const {return fNHpt;} - */ + Int_t PdgCode() const { return fPdgCode; } + /* + Int_t NArm() const {return fNArm;} + Int_t NRpc() const {return fNRpc;} + Int_t NHpt() const {return fNHpt;} + */ private: /** Copy constructor **/ @@ -57,8 +58,7 @@ class ShipRpcPoint : public FairMCPoint ShipRpcPoint(const ShipRpcPoint& point); ShipRpcPoint operator=(const ShipRpcPoint& point); - ClassDef(ShipRpcPoint,2) - + ClassDef(ShipRpcPoint, 2) }; #endif diff --git a/nutaudet/TTPoint.cxx b/nutaudet/TTPoint.cxx index 57a65cc95c..ba4abccf64 100644 --- a/nutaudet/TTPoint.cxx +++ b/nutaudet/TTPoint.cxx @@ -4,36 +4,37 @@ using std::cout; using std::endl; - // ----- Default constructor ------------------------------------------- TTPoint::TTPoint() - : FairMCPoint() -{ -} + : FairMCPoint() +{} // ------------------------------------------------------------------------- -TTPoint::TTPoint(Int_t trackID, Int_t detID,TVector3 pos, TVector3 mom, - Double_t tof, Double_t length, - Double_t eLoss, Int_t pdgcode) - : FairMCPoint(trackID, detID, pos, mom, tof, length, eLoss),fPdgCode(pdgcode) -{ } +TTPoint::TTPoint(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t tof, + Double_t length, + Double_t eLoss, + Int_t pdgcode) + : FairMCPoint(trackID, detID, pos, mom, tof, length, eLoss) + , fPdgCode(pdgcode) +{} // ------------------------------------------------------------------------- // ----- Destructor ---------------------------------------------------- -TTPoint::~TTPoint() { } +TTPoint::~TTPoint() {} // ------------------------------------------------------------------------- // ----- Public method Print ------------------------------------------- void TTPoint::Print(const Option_t* opt) const { - cout << "-I- TargetPoint: ShipRpc point for track " << fTrackID - << " in detector " << fDetectorID << endl; - cout << " Position (" << fX << ", " << fY << ", " << fZ - << ") cm" << endl; - cout << " Momentum (" << fPx << ", " << fPy << ", " << fPz - << ") GeV" << endl; - cout << " Time " << fTime << " ns, Length " << fLength - << " cm, Energy loss " << fELoss*1.0e06 << " keV" << endl; + cout << "-I- TargetPoint: ShipRpc point for track " << fTrackID << " in detector " << fDetectorID << endl; + cout << " Position (" << fX << ", " << fY << ", " << fZ << ") cm" << endl; + cout << " Momentum (" << fPx << ", " << fPy << ", " << fPz << ") GeV" << endl; + cout << " Time " << fTime << " ns, Length " << fLength << " cm, Energy loss " << fELoss * 1.0e06 << " keV" + << endl; } // ------------------------------------------------------------------------- diff --git a/nutaudet/TTPoint.h b/nutaudet/TTPoint.h index e12bec3841..731f1e60cb 100644 --- a/nutaudet/TTPoint.h +++ b/nutaudet/TTPoint.h @@ -1,9 +1,7 @@ #ifndef TTPOINT_H #define TTPOINT_H 1 - #include "FairMCPoint.h" - #include "TObject.h" #include "TVector3.h" @@ -11,11 +9,9 @@ class TTPoint : public FairMCPoint { public: - /** Default constructor **/ TTPoint(); - /** Constructor with arguments *@param trackID Index of MCTrack *@param detID Detector ID @@ -28,11 +24,17 @@ class TTPoint : public FairMCPoint /*TargetPoint(Int_t trackID, Int_t detID, TVector3 pos, TVector3 mom, Double_t tof, Double_t length, Double_t eLoss, Int_t pdgCode, - Bool_t emTop, Bool_t emBot,Bool_t emCESTop, Bool_t emCESBot, Bool_t tt, - Int_t nPlate, Int_t nColumn, Int_t nRow, Int_t nWall);*/ - - TTPoint(Int_t trackID, Int_t detID, TVector3 pos, TVector3 mom, - Double_t tof, Double_t length, Double_t eLoss, Int_t pdgCode); + Bool_t emTop, Bool_t emBot,Bool_t emCESTop, Bool_t emCESBot, Bool_t tt, + Int_t nPlate, Int_t nColumn, Int_t nRow, Int_t nWall);*/ + + TTPoint(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t tof, + Double_t length, + Double_t eLoss, + Int_t pdgCode); /** Destructor **/ virtual ~TTPoint(); @@ -40,22 +42,17 @@ class TTPoint : public FairMCPoint /** Output to screen **/ virtual void Print(const Option_t* opt) const; - - Int_t PdgCode() const {return fPdgCode;} - + Int_t PdgCode() const { return fPdgCode; } private: - - Int_t fPdgCode; - /** Copy constructor **/ TTPoint(const TTPoint& point); TTPoint operator=(const TTPoint& point); - ClassDef(TTPoint,2) + ClassDef(TTPoint, 2) }; #endif diff --git a/nutaudet/Target.cxx b/nutaudet/Target.cxx index 644d9383aa..aca32afe64 100644 --- a/nutaudet/Target.cxx +++ b/nutaudet/Target.cxx @@ -8,56 +8,48 @@ #include "Target.h" -#include "TargetPoint.h" - -#include "TGeoManager.h" -#include "FairRun.h" // for FairRun -#include "FairRuntimeDb.h" // for FairRuntimeDb -#include // for ostream -#include "TList.h" // for TListIter, TList (ptr only) -#include "TObjArray.h" // for TObjArray -#include "TString.h" // for TString - -#include "TClonesArray.h" -#include "TVirtualMC.h" - -#include "TGeoBBox.h" -#include "TGeoTrd1.h" -#include "TGeoCompositeShape.h" -#include "TGeoTube.h" -#include "TGeoMaterial.h" -#include "TGeoMedium.h" -#include "TGeoTrd1.h" -#include "TGeoArb8.h" - -#include "TParticle.h" -#include "TParticlePDG.h" -#include "TParticleClassPDG.h" -#include "TVirtualMCStack.h" - -#include "FairVolume.h" -#include "FairGeoVolume.h" -#include "FairGeoNode.h" -#include "FairRootManager.h" -#include "FairGeoLoader.h" +#include "EmulsionMagnet.h" +#include "FairGeoBuilder.h" #include "FairGeoInterface.h" -#include "FairGeoTransform.h" +#include "FairGeoLoader.h" #include "FairGeoMedia.h" #include "FairGeoMedium.h" -#include "FairGeoBuilder.h" +#include "FairGeoNode.h" +#include "FairGeoTransform.h" +#include "FairGeoVolume.h" +#include "FairRootManager.h" +#include "FairRun.h" // for FairRun #include "FairRun.h" +#include "FairRuntimeDb.h" // for FairRuntimeDb #include "FairRuntimeDb.h" - +#include "FairVolume.h" #include "ShipDetectorList.h" -#include "ShipUnit.h" #include "ShipStack.h" -#include "EmulsionMagnet.h" - +#include "ShipUnit.h" +#include "TClonesArray.h" +#include "TGeoArb8.h" +#include "TGeoBBox.h" +#include "TGeoCompositeShape.h" +#include "TGeoManager.h" +#include "TGeoMaterial.h" +#include "TGeoMedium.h" +#include "TGeoTrd1.h" +#include "TGeoTube.h" #include "TGeoUniformMagField.h" +#include "TList.h" // for TListIter, TList (ptr only) +#include "TObjArray.h" // for TObjArray +#include "TParticle.h" +#include "TParticleClassPDG.h" +#include "TParticlePDG.h" +#include "TString.h" // for TString #include "TVector3.h" +#include "TVirtualMC.h" +#include "TVirtualMCStack.h" +#include "TargetPoint.h" -#include // for NULL -#include // for operator<<, basic_ostream,etc +#include // for ostream +#include // for operator<<, basic_ostream,etc +#include // for NULL #include using std::cout; @@ -66,728 +58,791 @@ using std::endl; using namespace ShipUnit; Target::Target() - : FairDetector("Target", "",kTRUE), - fTrackID(-1), - fVolumeID(-1), - fPos(), - fMom(), - fTime(-1.), - fLength(-1.), - fELoss(-1), - fTargetPointCollection(new TClonesArray("TargetPoint")) -{ -} + : FairDetector("Target", "", kTRUE) + , fTrackID(-1) + , fVolumeID(-1) + , fPos() + , fMom() + , fTime(-1.) + , fLength(-1.) + , fELoss(-1) + , fTargetPointCollection(new TClonesArray("TargetPoint")) +{} Target::Target(const char* name, const Double_t Ydist, Bool_t Active, const char* Title) - : FairDetector(name, true, ktauTarget), - fTrackID(-1), - fVolumeID(-1), - fPos(), - fMom(), - fTime(-1.), - fLength(-1.), - fELoss(-1), - fTargetPointCollection(new TClonesArray("TargetPoint")) + : FairDetector(name, true, ktauTarget) + , fTrackID(-1) + , fVolumeID(-1) + , fPos() + , fMom() + , fTime(-1.) + , fLength(-1.) + , fELoss(-1) + , fTargetPointCollection(new TClonesArray("TargetPoint")) { - Ydistance = Ydist; + Ydistance = Ydist; } Target::~Target() { - if (fTargetPointCollection) { - fTargetPointCollection->Delete(); - delete fTargetPointCollection; - } + if (fTargetPointCollection) { + fTargetPointCollection->Delete(); + delete fTargetPointCollection; + } } void Target::Initialize() { - FairDetector::Initialize(); + FairDetector::Initialize(); } // ----- Private method InitMedium Int_t Target::InitMedium(const char* name) { - static FairGeoLoader *geoLoad=FairGeoLoader::Instance(); - static FairGeoInterface *geoFace=geoLoad->getGeoInterface(); - static FairGeoMedia *media=geoFace->getMedia(); - static FairGeoBuilder *geoBuild=geoLoad->getGeoBuilder(); + static FairGeoLoader* geoLoad = FairGeoLoader::Instance(); + static FairGeoInterface* geoFace = geoLoad->getGeoInterface(); + static FairGeoMedia* media = geoFace->getMedia(); + static FairGeoBuilder* geoBuild = geoLoad->getGeoBuilder(); - FairGeoMedium *ShipMedium=media->getMedium(name); + FairGeoMedium* ShipMedium = media->getMedium(name); - if (!ShipMedium) - { - Fatal("InitMedium","Material %s not defined in media file.", name); - return -1111; + if (!ShipMedium) { + Fatal("InitMedium", "Material %s not defined in media file.", name); + return -1111; } - TGeoMedium* medium=gGeoManager->GetMedium(name); - if (medium!=NULL) - return ShipMedium->getMediumIndex(); - return geoBuild->createMedium(ShipMedium); + TGeoMedium* medium = gGeoManager->GetMedium(name); + if (medium != NULL) + return ShipMedium->getMediumIndex(); + return geoBuild->createMedium(ShipMedium); } //--------------Options for detector construction void Target::SetDetectorDesign(Int_t Design) { - fDesign = Design; - Info("SetDetectorDesign"," to %i", fDesign); + fDesign = Design; + Info("SetDetectorDesign", " to %i", fDesign); } void Target::MakeNuTargetPassive(Bool_t a) { - fPassive=a; + fPassive = a; } void Target::MergeTopBot(Bool_t SingleEmFilm) { - fsingleemulsionfilm=SingleEmFilm; + fsingleemulsionfilm = SingleEmFilm; } //-------------------------- void Target::SetNumberBricks(Double_t col, Double_t row, Double_t wall) { - fNCol = col; - fNRow = row; - fNWall = wall; + fNCol = col; + fNRow = row; + fNWall = wall; } void Target::SetNumberTargets(Int_t target) { - fNTarget = target; + fNTarget = target; } void Target::SetTargetWallDimension(Double_t WallXDim_, Double_t WallYDim_, Double_t WallZDim_) { - WallXDim = WallXDim_; - WallYDim = WallYDim_; - WallZDim = WallZDim_; + WallXDim = WallXDim_; + WallYDim = WallYDim_; + WallZDim = WallZDim_; } void Target::SetDetectorDimension(Double_t xdim, Double_t ydim, Double_t zdim) { - XDimension = xdim; - YDimension = ydim; - ZDimension = zdim; + XDimension = xdim; + YDimension = ydim; + ZDimension = zdim; } -void Target::SetEmulsionParam(Double_t EmTh, Double_t EmX, Double_t EmY, Double_t PBTh, Double_t EPlW,Double_t LeadTh, Double_t AllPW) +void Target::SetEmulsionParam(Double_t EmTh, + Double_t EmX, + Double_t EmY, + Double_t PBTh, + Double_t EPlW, + Double_t LeadTh, + Double_t AllPW) { - EmulsionThickness = EmTh; - EmulsionX = EmX; - EmulsionY = EmY; - PlasticBaseThickness = PBTh; - EmPlateWidth = EPlW; - LeadThickness = LeadTh; - AllPlateWidth = AllPW; + EmulsionThickness = EmTh; + EmulsionX = EmX; + EmulsionY = EmY; + PlasticBaseThickness = PBTh; + EmPlateWidth = EPlW; + LeadThickness = LeadTh; + AllPlateWidth = AllPW; } - -void Target::SetBrickParam(Double_t BrX, Double_t BrY, Double_t BrZ, Double_t BrPackX, Double_t BrPackY, Double_t BrPackZ, Int_t number_of_plates_) +void Target::SetBrickParam(Double_t BrX, + Double_t BrY, + Double_t BrZ, + Double_t BrPackX, + Double_t BrPackY, + Double_t BrPackZ, + Int_t number_of_plates_) { - BrickPackageX = BrPackX; - BrickPackageY = BrPackY; - BrickPackageZ = BrPackZ; - BrickX = BrX; - BrickY = BrY; - BrickZ = BrZ; - number_of_plates = number_of_plates_; + BrickPackageX = BrPackX; + BrickPackageY = BrPackY; + BrickPackageZ = BrPackZ; + BrickX = BrX; + BrickY = BrY; + BrickZ = BrZ; + number_of_plates = number_of_plates_; } -void Target::SetCESParam(Double_t RohG, Double_t LayerCESW,Double_t CESW, Double_t CESPack) +void Target::SetCESParam(Double_t RohG, Double_t LayerCESW, Double_t CESW, Double_t CESPack) { - CESPackageZ = CESPack; - LayerCESWidth = LayerCESW; - RohacellGap = RohG; - CESWidth = CESW; + CESPackageZ = CESPack; + LayerCESWidth = LayerCESW; + RohacellGap = RohG; + CESWidth = CESW; } void Target::SetCellParam(Double_t CellW) { - CellWidth = CellW; + CellWidth = CellW; } void Target::SetTTzdimension(Double_t TTZ) { - TTrackerZ = TTZ; + TTrackerZ = TTZ; } void Target::SetMagnetHeight(Double_t Y) { - fMagnetY=Y; + fMagnetY = Y; } void Target::SetColumnHeight(Double_t Y) { - fColumnY=Y; + fColumnY = Y; } void Target::SetBaseHeight(Double_t Y) { - fMagnetBaseY=Y; + fMagnetBaseY = Y; } void Target::SetCoilUpHeight(Double_t H1) { - fCoilH1=H1; + fCoilH1 = H1; } void Target::SetCoilDownHeight(Double_t H2) { - fCoilH2=H2; + fCoilH2 = H2; } void Target::SetMagneticField(Double_t B) { - fField = B; + fField = B; } void Target::SetCenterZ(Double_t z) { - fCenterZ = z; + fCenterZ = z; } void Target::SetBaseDimension(Double_t x, Double_t y, Double_t z) { - fBaseX=x; - fBaseY=y; - fBaseZ=z; + fBaseX = x; + fBaseY = y; + fBaseZ = z; } - void Target::SetPillarDimension(Double_t x, Double_t y, Double_t z) { - fPillarX=x; - fPillarY=y; - fPillarZ=z; + fPillarX = x; + fPillarY = y; + fPillarZ = z; } -void Target::SetHpTParam(Int_t n, Double_t dd, Double_t DZ) //need to know about HPT.cxx geometry to place additional targets +void Target::SetHpTParam(Int_t n, + Double_t dd, + Double_t DZ) // need to know about HPT.cxx geometry to place additional targets { - fnHpT = n; - fHpTDistance = dd; - fHpTDZ = DZ; + fnHpT = n; + fHpTDistance = dd; + fHpTDZ = DZ; } void Target::ConstructGeometry() { - // cout << "Design = " << fDesign << endl; + // cout << "Design = " << fDesign << endl; + + InitMedium("air"); + TGeoMedium* air = gGeoManager->GetMedium("air"); + + InitMedium("PlasticBase"); + TGeoMedium* PBase = gGeoManager->GetMedium("PlasticBase"); - InitMedium("air"); - TGeoMedium *air =gGeoManager->GetMedium("air"); + InitMedium("NuclearEmulsion"); + TGeoMedium* NEmu = gGeoManager->GetMedium("NuclearEmulsion"); - InitMedium("PlasticBase"); - TGeoMedium *PBase =gGeoManager->GetMedium("PlasticBase"); + TGeoMaterial* NEmuMat = NEmu->GetMaterial(); // I need the materials to build the mixture + TGeoMaterial* PBaseMat = PBase->GetMaterial(); - InitMedium("NuclearEmulsion"); - TGeoMedium *NEmu =gGeoManager->GetMedium("NuclearEmulsion"); + Double_t rho_film = (NEmuMat->GetDensity() * 2 * EmulsionThickness + PBaseMat->GetDensity() * PlasticBaseThickness) + / (2 * EmulsionThickness + PlasticBaseThickness); + Double_t frac_emu = + NEmuMat->GetDensity() * 2 * EmulsionThickness + / (NEmuMat->GetDensity() * 2 * EmulsionThickness + PBaseMat->GetDensity() * PlasticBaseThickness); - TGeoMaterial *NEmuMat = NEmu->GetMaterial(); //I need the materials to build the mixture - TGeoMaterial *PBaseMat = PBase->GetMaterial(); + if (fsingleemulsionfilm) + cout << "TARGET PRINTOUT: Single volume for emulsion film chosen: average density: " << rho_film + << " fraction in mass of emulsion " << frac_emu << endl; - Double_t rho_film = (NEmuMat->GetDensity() * 2 * EmulsionThickness + PBaseMat->GetDensity() * PlasticBaseThickness)/(2* EmulsionThickness + PlasticBaseThickness); - Double_t frac_emu = NEmuMat->GetDensity() * 2 * EmulsionThickness /(NEmuMat->GetDensity() * 2 * EmulsionThickness + PBaseMat->GetDensity() * PlasticBaseThickness); + TGeoMixture* emufilmmixture = + new TGeoMixture("EmulsionFilmMixture", 2.00); // two nuclear emulsions separated by the plastic base - if (fsingleemulsionfilm) cout<<"TARGET PRINTOUT: Single volume for emulsion film chosen: average density: "<AddElement(NEmuMat, frac_emu); + emufilmmixture->AddElement(PBaseMat, 1. - frac_emu); - TGeoMixture * emufilmmixture = new TGeoMixture("EmulsionFilmMixture", 2.00); // two nuclear emulsions separated by the plastic base + TGeoMedium* Emufilm = new TGeoMedium("EmulsionFilm", 100, emufilmmixture); - emufilmmixture->AddElement(NEmuMat,frac_emu); - emufilmmixture->AddElement(PBaseMat,1. - frac_emu); + InitMedium("lead"); + TGeoMedium* lead = gGeoManager->GetMedium("lead"); - TGeoMedium *Emufilm = new TGeoMedium("EmulsionFilm",100,emufilmmixture); + InitMedium("tungsten"); + TGeoMedium* tungsten = gGeoManager->GetMedium("tungsten"); - InitMedium("lead"); - TGeoMedium *lead = gGeoManager->GetMedium("lead"); + InitMedium("Concrete"); + TGeoMedium* Conc = gGeoManager->GetMedium("Concrete"); - InitMedium("tungsten"); - TGeoMedium *tungsten = gGeoManager->GetMedium("tungsten"); + InitMedium("steel"); + TGeoMedium* Steel = gGeoManager->GetMedium("steel"); - InitMedium("Concrete"); - TGeoMedium *Conc =gGeoManager->GetMedium("Concrete"); + Int_t NPlates = number_of_plates; // Number of doublets emulsion + Pb + Int_t NRohacellGap = 2; - InitMedium("steel"); - TGeoMedium *Steel =gGeoManager->GetMedium("steel"); + // Definition of the target box containing emulsion bricks + (CES if fDesign = 0 o 1) + target trackers (TT) + TGeoBBox* TargetBox = new TGeoBBox("TargetBox", XDimension / 2, YDimension / 2, ZDimension / 2); + TGeoVolume* volTarget = new TGeoVolume("volTarget", TargetBox, air); - Int_t NPlates = number_of_plates; //Number of doublets emulsion + Pb - Int_t NRohacellGap = 2; + // In both fDesign=0 & fDesign=1 the emulsion target is inserted within a magnet + if (fDesign != 2 && fDesign != 4) { + TGeoVolume* MagnetVol = nullptr; - //Definition of the target box containing emulsion bricks + (CES if fDesign = 0 o 1) + target trackers (TT) - TGeoBBox *TargetBox = new TGeoBBox("TargetBox",XDimension/2, YDimension/2, ZDimension/2); - TGeoVolume *volTarget = new TGeoVolume("volTarget",TargetBox, air); + // magnetic field in target + TGeoUniformMagField* magField2 = new TGeoUniformMagField(); - // In both fDesign=0 & fDesign=1 the emulsion target is inserted within a magnet - if(fDesign!=2 && fDesign!=4) - { - TGeoVolume *MagnetVol = nullptr; + if (fDesign == 1) // TP + { + magField2->SetFieldValue(fField, 0, 0.); + MagnetVol = gGeoManager->GetVolume("Davide"); + } + if (fDesign == 0) // NEW + { + MagnetVol = gGeoManager->GetVolume("Goliath"); + magField2->SetFieldValue(0., fField, 0.); + } + if (fDesign == 3) { + magField2->SetFieldValue(fField, 0, 0.); + MagnetVol = gGeoManager->GetVolume("NudetMagnet"); + } - //magnetic field in target - TGeoUniformMagField *magField2 = new TGeoUniformMagField(); + // Definition of the target box containing emulsion bricks + CES + target trackers (TT) + if (fDesign != 3 && fDesign != 4) + volTarget->SetField(magField2); + volTarget->SetVisibility(1); + volTarget->SetVisDaughters(1); + if (fDesign == 0) // TP + MagnetVol->AddNode( + volTarget, 1, new TGeoTranslation(0, -fMagnetY / 2 + fColumnY + fCoilH2 + YDimension / 2, 0)); + if (fDesign == 1) // NEW + MagnetVol->AddNode(volTarget, 1, new TGeoTranslation(0, -fMagnetY / 2 + fColumnY + YDimension / 2, 0)); + if (fDesign == 3) { + TGeoVolume* volMagRegion = gGeoManager->GetVolume("volMagRegion"); + Double_t ZDimMagnetizedRegion = + ((TGeoBBox*)volMagRegion->GetShape())->GetDZ() * 2.; // n.d.r. DZ is the semidimension + for (int i = 0; i < fNTarget; i++) { + volMagRegion->AddNode(volTarget, + i + 1, + new TGeoTranslation(0, + 0, + -ZDimMagnetizedRegion / 2 + ZDimension / 2. + + i * (ZDimension + 3 * fHpTDZ + 2 * fHpTDistance))); + } + } + } + + // + // Volumes definition + // + + TGeoBBox* Cell = new TGeoBBox("cell", BrickX / 2, BrickY / 2, CellWidth / 2); + TGeoVolume* volCell = new TGeoVolume("Cell", Cell, air); + + // Brick + TGeoBBox* Brick = new TGeoBBox("brick", BrickX / 2, BrickY / 2, BrickZ / 2); + TGeoVolume* volBrick = new TGeoVolume("Brick", Brick, air); + volBrick->SetLineColor(kCyan); + volBrick->SetTransparency(1); + // need to separate the two cases, now with a ternary operator + auto* Absorber = new TGeoBBox("Absorber", EmulsionX / 2, EmulsionY / 2, LeadThickness / 2); + auto* volAbsorber = new TGeoVolume("volAbsorber", Absorber, (fDesign < 4) ? lead : tungsten); + + volAbsorber->SetTransparency(1); + volAbsorber->SetLineColor(kGray); + + for (Int_t n = 0; n < NPlates; n++) { + // decide to use lead or tungsten, according to fDesign + volBrick->AddNode( + volAbsorber, + n, + new TGeoTranslation( + 0, 0, -BrickZ / 2 + BrickPackageZ / 2 + EmPlateWidth + LeadThickness / 2 + n * AllPlateWidth)); + } + if (fsingleemulsionfilm) { // simplified configuration, unique sensitive layer for the whole emulsion plate + TGeoBBox* EmulsionFilm = new TGeoBBox("EmulsionFilm", EmulsionX / 2, EmulsionY / 2, EmPlateWidth / 2); + TGeoVolume* volEmulsionFilm = new TGeoVolume("Emulsion", EmulsionFilm, Emufilm); // TOP + volEmulsionFilm->SetLineColor(kBlue); - if(fDesign==1) //TP - { - magField2->SetFieldValue(fField,0,0.); - MagnetVol=gGeoManager->GetVolume("Davide"); - } - if(fDesign==0) //NEW - { - MagnetVol=gGeoManager->GetVolume("Goliath"); - magField2->SetFieldValue(0.,fField,0.); - } - if(fDesign==3) - { - magField2->SetFieldValue(fField,0,0.); - MagnetVol=gGeoManager->GetVolume("NudetMagnet"); - } + if (fPassive == 0) { + AddSensitiveVolume(volEmulsionFilm); + } - //Definition of the target box containing emulsion bricks + CES + target trackers (TT) - if (fDesign != 3 && fDesign != 4) volTarget->SetField(magField2); - volTarget->SetVisibility(1); - volTarget->SetVisDaughters(1); - if(fDesign==0) //TP - MagnetVol->AddNode(volTarget,1,new TGeoTranslation(0,-fMagnetY/2+fColumnY+fCoilH2+YDimension/2,0)); - if(fDesign==1) //NEW - MagnetVol->AddNode(volTarget,1,new TGeoTranslation(0,-fMagnetY/2+fColumnY+YDimension/2,0)); - if(fDesign==3){ - TGeoVolume *volMagRegion=gGeoManager->GetVolume("volMagRegion"); - Double_t ZDimMagnetizedRegion = ((TGeoBBox*) volMagRegion->GetShape())->GetDZ() * 2.; //n.d.r. DZ is the semidimension - for (int i = 0; i < fNTarget; i++){ - volMagRegion->AddNode(volTarget,i+1,new TGeoTranslation(0,0, -ZDimMagnetizedRegion/2 + ZDimension/2. + i*(ZDimension + 3 * fHpTDZ + 2* fHpTDistance))); + for (Int_t n = 0; n < NPlates + 1; n++) { + volBrick->AddNode( + volEmulsionFilm, + n, + new TGeoTranslation(0, 0, -BrickZ / 2 + BrickPackageZ / 2 + EmPlateWidth / 2 + n * AllPlateWidth)); + } + } else { // more accurate configuration, two emulsion films divided by a plastic base + TGeoBBox* EmulsionFilm = new TGeoBBox("EmulsionFilm", EmulsionX / 2, EmulsionY / 2, EmulsionThickness / 2); + TGeoVolume* volEmulsionFilm = new TGeoVolume("Emulsion", EmulsionFilm, NEmu); // TOP + TGeoVolume* volEmulsionFilm2 = new TGeoVolume("Emulsion2", EmulsionFilm, NEmu); // BOTTOM + volEmulsionFilm->SetLineColor(kBlue); + volEmulsionFilm2->SetLineColor(kBlue); + + if (fPassive == 0) { + AddSensitiveVolume(volEmulsionFilm); + AddSensitiveVolume(volEmulsionFilm2); + } + TGeoBBox* PlBase = new TGeoBBox("PlBase", EmulsionX / 2, EmulsionY / 2, PlasticBaseThickness / 2); + TGeoVolume* volPlBase = new TGeoVolume("PlasticBase", PlBase, PBase); + volPlBase->SetLineColor(kYellow - 4); + for (Int_t n = 0; n < NPlates + 1; n++) { + volBrick->AddNode( + volEmulsionFilm2, + n, + new TGeoTranslation( + 0, 0, -BrickZ / 2 + BrickPackageZ / 2 + EmulsionThickness / 2 + n * AllPlateWidth)); // BOTTOM + volBrick->AddNode(volEmulsionFilm, + n, + new TGeoTranslation(0, + 0, + -BrickZ / 2 + BrickPackageZ / 2 + 3 * EmulsionThickness / 2 + + PlasticBaseThickness + n * AllPlateWidth)); // TOP + volBrick->AddNode(volPlBase, + n, + new TGeoTranslation(0, + 0, + -BrickZ / 2 + BrickPackageZ / 2 + EmulsionThickness + + PlasticBaseThickness / 2 + + n * AllPlateWidth)); // PLASTIC BASE } - } } + volBrick->SetVisibility(kTRUE); + + // The CES is required only in the option with magnet surrounding the emulsion target + if (fDesign != 2 && fDesign != 4) { + // CES + + TGeoBBox* CES = new TGeoBBox("ces", EmulsionX / 2, EmulsionY / 2, CESWidth / 2); + TGeoVolume* volCES = new TGeoVolume("CES", CES, air); + volCES->SetTransparency(5); + volCES->SetLineColor(kYellow - 10); + volCES->SetVisibility(kTRUE); + + TGeoBBox* RohGap = new TGeoBBox("RohGap", EmulsionX / 2, EmulsionY / 2, RohacellGap / 2); + TGeoVolume* volRohGap = new TGeoVolume("RohacellGap", RohGap, air); // using AIR for CES, not rohacell + volRohGap->SetTransparency(1); + volRohGap->SetLineColor(kYellow); + + for (Int_t n = 0; n < NRohacellGap; n++) { + volCES->AddNode(volRohGap, + n, + new TGeoTranslation(0, + 0, + -CESWidth / 2 + CESPackageZ / 2 + EmPlateWidth + RohacellGap / 2 + + n * LayerCESWidth)); // ROHACELL + } + if (fsingleemulsionfilm) { // simplified configuration, unique sensitive layer for the whole emulsion plate + TGeoBBox* EmulsionFilmCES = new TGeoBBox("EmulsionFilmCES", EmulsionX / 2, EmulsionY / 2, EmPlateWidth / 2); + TGeoVolume* volEmulsionFilmCES = new TGeoVolume("EmulsionCES", EmulsionFilmCES, Emufilm); // TOP + volEmulsionFilmCES->SetLineColor(kBlue); + if (fPassive == 0) { + AddSensitiveVolume(volEmulsionFilmCES); + } + + for (Int_t n = 0; n < NRohacellGap + 1; n++) { + volCES->AddNode( + volEmulsionFilmCES, + n, + new TGeoTranslation(0, 0, -CESWidth / 2 + CESPackageZ / 2 + EmPlateWidth / 2 + n * LayerCESWidth)); + } + + } else { // more accurate configuration, two emulsion films divided by a plastic base + + TGeoBBox* EmulsionFilmCES = + new TGeoBBox("EmulsionFilmCES", EmulsionX / 2, EmulsionY / 2, EmulsionThickness / 2); + TGeoVolume* volEmulsionFilmCES = new TGeoVolume("EmulsionCES", EmulsionFilmCES, NEmu); // TOP + TGeoVolume* volEmulsionFilm2CES = new TGeoVolume("Emulsion2CES", EmulsionFilmCES, NEmu); // BOTTOM + volEmulsionFilmCES->SetLineColor(kBlue); + volEmulsionFilm2CES->SetLineColor(kBlue); + if (fPassive == 0) { + AddSensitiveVolume(volEmulsionFilmCES); + AddSensitiveVolume(volEmulsionFilm2CES); + } + // CES PLASTIC BASE + TGeoBBox* PlBaseCES = new TGeoBBox("PlBaseCES", EmulsionX / 2, EmulsionY / 2, PlasticBaseThickness / 2); + TGeoVolume* volPlBaseCES = new TGeoVolume("PlasticBaseCES", PlBaseCES, PBase); + volPlBaseCES->SetLineColor(kYellow); + for (Int_t n = 0; n < NRohacellGap + 1; n++) { + volCES->AddNode( + volEmulsionFilm2CES, + n, + new TGeoTranslation( + 0, 0, -CESWidth / 2 + CESPackageZ / 2 + EmulsionThickness / 2 + n * LayerCESWidth)); // BOTTOM + volCES->AddNode(volEmulsionFilmCES, + n, + new TGeoTranslation(0, + 0, + -CESWidth / 2 + CESPackageZ / 2 + 3 * EmulsionThickness / 2 + + PlasticBaseThickness + n * LayerCESWidth)); // TOP + volCES->AddNode(volPlBaseCES, + n, + new TGeoTranslation(0, + 0, + -CESWidth / 2 + CESPackageZ / 2 + EmulsionThickness + + PlasticBaseThickness / 2 + + n * LayerCESWidth)); // PLASTIC BASE + // if(n == 2) + // cout << "-CESWidth/2+3*EmulsionThickness/2+PlasticBaseThickness+n*LayerCESWidth = " << + // -CESWidth/2+3*EmulsionThickness/2+PlasticBaseThickness+n*LayerCESWidth << endl; + } + } + volCell->AddNode(volBrick, 1, new TGeoTranslation(0, 0, -CellWidth / 2 + BrickZ / 2)); + volCell->AddNode(volCES, 1, new TGeoTranslation(0, 0, -CellWidth / 2 + BrickZ + CESWidth / 2)); + TGeoBBox* Row = new TGeoBBox("row", WallXDim / 2, BrickY / 2, CellWidth / 2); + TGeoVolume* volRow = new TGeoVolume("Row", Row, air); + volRow->SetLineColor(20); + Double_t d_cl_x = -WallXDim / 2; + for (int j = 0; j < fNCol; j++) { + volRow->AddNode(volCell, j, new TGeoTranslation(d_cl_x + BrickX / 2, 0, 0)); + d_cl_x += BrickX; + } + TGeoBBox* Wall = new TGeoBBox("wall", WallXDim / 2, WallYDim / 2, CellWidth / 2); + TGeoVolume* volWall = new TGeoVolume("Wall", Wall, air); + Double_t d_cl_y = -WallYDim / 2; + for (int k = 0; k < fNRow; k++) { + volWall->AddNode(volRow, k, new TGeoTranslation(0, d_cl_y + BrickY / 2, 0)); - // - //Volumes definition - // + // 2mm is the distance for the structure that holds the brick + d_cl_y += BrickY + Ydistance; + } - TGeoBBox *Cell = new TGeoBBox("cell", BrickX/2, BrickY/2, CellWidth/2); - TGeoVolume *volCell = new TGeoVolume("Cell",Cell,air); + // Columns - //Brick - TGeoBBox *Brick = new TGeoBBox("brick", BrickX/2, BrickY/2, BrickZ/2); - TGeoVolume *volBrick = new TGeoVolume("Brick",Brick,air); - volBrick->SetLineColor(kCyan); - volBrick->SetTransparency(1); - //need to separate the two cases, now with a ternary operator - auto *Absorber = new TGeoBBox("Absorber", EmulsionX/2, EmulsionY/2, LeadThickness/2); - auto *volAbsorber = new TGeoVolume("volAbsorber", Absorber, (fDesign < 4) ? lead : tungsten); + Double_t d_cl_z = -ZDimension / 2 + TTrackerZ; - volAbsorber->SetTransparency(1); - volAbsorber->SetLineColor(kGray); + for (int l = 0; l < fNWall; l++) { + volTarget->AddNode(volWall, l, new TGeoTranslation(0, 0, d_cl_z + CellWidth / 2)); - for(Int_t n=0; nAddNode(volAbsorber, n, new TGeoTranslation(0,0,-BrickZ/2+BrickPackageZ/2+ EmPlateWidth + LeadThickness/2 + n*AllPlateWidth)); - } - if (fsingleemulsionfilm){ //simplified configuration, unique sensitive layer for the whole emulsion plate - TGeoBBox *EmulsionFilm = new TGeoBBox("EmulsionFilm", EmulsionX/2, EmulsionY/2, EmPlateWidth/2); - TGeoVolume *volEmulsionFilm = new TGeoVolume("Emulsion",EmulsionFilm,Emufilm); //TOP - volEmulsionFilm->SetLineColor(kBlue); - - if(fPassive==0) - { - AddSensitiveVolume(volEmulsionFilm); + // 6 cm is the distance between 2 columns of consecutive Target for TT placement + d_cl_z += CellWidth + TTrackerZ; + } } - for(Int_t n=0; nAddNode(volEmulsionFilm, n, new TGeoTranslation(0,0,-BrickZ/2+BrickPackageZ/2+ EmPlateWidth/2 + n*AllPlateWidth)); - } - } - else { //more accurate configuration, two emulsion films divided by a plastic base - TGeoBBox *EmulsionFilm = new TGeoBBox("EmulsionFilm", EmulsionX/2, EmulsionY/2, EmulsionThickness/2); - TGeoVolume *volEmulsionFilm = new TGeoVolume("Emulsion",EmulsionFilm,NEmu); //TOP - TGeoVolume *volEmulsionFilm2 = new TGeoVolume("Emulsion2",EmulsionFilm,NEmu); //BOTTOM - volEmulsionFilm->SetLineColor(kBlue); - volEmulsionFilm2->SetLineColor(kBlue); - - if(fPassive==0) - { - AddSensitiveVolume(volEmulsionFilm); - AddSensitiveVolume(volEmulsionFilm2); - } - TGeoBBox *PlBase = new TGeoBBox("PlBase", EmulsionX/2, EmulsionY/2, PlasticBaseThickness/2); - TGeoVolume *volPlBase = new TGeoVolume("PlasticBase",PlBase,PBase); - volPlBase->SetLineColor(kYellow-4); - for(Int_t n=0; nAddNode(volEmulsionFilm2, n, new TGeoTranslation(0,0,-BrickZ/2+BrickPackageZ/2+ EmulsionThickness/2 + n*AllPlateWidth)); //BOTTOM - volBrick->AddNode(volEmulsionFilm, n, new TGeoTranslation(0,0,-BrickZ/2+BrickPackageZ/2+3*EmulsionThickness/2+PlasticBaseThickness+n*AllPlateWidth)); //TOP - volBrick->AddNode(volPlBase, n, new TGeoTranslation(0,0,-BrickZ/2+BrickPackageZ/2+EmulsionThickness+PlasticBaseThickness/2+n*AllPlateWidth)); //PLASTIC BASE + // in fDesign==2 and fDesign==4 the emulsion target is not surrounded by a magnet => no magnetic field inside + // In the no Magnetic field option, no CES is needed => only brick walls + TT + if (fDesign == 2 || fDesign == 4) { + EmulsionMagnet emuMag; + + TGeoVolume* tTauNuDet = gGeoManager->GetVolume("tTauNuDet"); + cout << "Tau Nu Detector fMagnetConfig: " << fDesign << endl; + + tTauNuDet->AddNode(volTarget, 1, new TGeoTranslation(0, 0, fCenterZ)); + + TGeoBBox* Row = new TGeoBBox("row", WallXDim / 2, BrickY / 2, WallZDim / 2); + TGeoVolume* volRow = new TGeoVolume("Row", Row, air); + volRow->SetLineColor(20); + + Double_t d_cl_x = -WallXDim / 2; + for (int j = 0; j < fNCol; j++) { + volRow->AddNode(volBrick, j, new TGeoTranslation(d_cl_x + BrickX / 2, 0, 0)); + d_cl_x += BrickX; + } + TGeoBBox* Wall = new TGeoBBox("wall", WallXDim / 2, WallYDim / 2, WallZDim / 2); + TGeoVolume* volWall = new TGeoVolume("Wall", Wall, air); + volWall->SetLineColor(kGreen); + + Double_t d_cl_y = -WallYDim / 2; + for (int k = 0; k < fNRow; k++) { + volWall->AddNode(volRow, k, new TGeoTranslation(0, d_cl_y + BrickY / 2, 0)); + + // 2mm is the distance for the structure that holds the brick + d_cl_y += BrickY + Ydistance; + } + // Columns + + Double_t d_cl_z = -ZDimension / 2 + TTrackerZ; + + for (int l = 0; l < fNWall; l++) { + volTarget->AddNode(volWall, l, new TGeoTranslation(0, 0, d_cl_z + BrickZ / 2)); + + // 6 cm is the distance between 2 columns of consecutive Target for TT placement + d_cl_z += BrickZ + TTrackerZ; + } + if (fDesign == 2) { + TGeoBBox* Base = new TGeoBBox("Base", fBaseX / 2, fBaseY / 2, fBaseZ / 2); + TGeoVolume* volBase = new TGeoVolume("volBase", Base, Conc); + volBase->SetLineColor(kYellow - 3); + tTauNuDet->AddNode(volBase, 1, new TGeoTranslation(0, -WallYDim / 2 - fBaseY / 2, fCenterZ)); + + TGeoBBox* PillarBox = new TGeoBBox(fPillarX / 2, fPillarY / 2, fPillarZ / 2); + TGeoVolume* PillarVol = new TGeoVolume("PillarVol", PillarBox, Steel); + PillarVol->SetLineColor(kGreen + 3); + tTauNuDet->AddNode(PillarVol, + 1, + new TGeoTranslation(-XDimension / 2 + fPillarX / 2, + -YDimension / 2 - fBaseY - fPillarY / 2, + fCenterZ - ZDimension / 2 + fPillarZ / 2)); + tTauNuDet->AddNode(PillarVol, + 2, + new TGeoTranslation(XDimension / 2 - fPillarX / 2, + -YDimension / 2 - fBaseY - fPillarY / 2, + fCenterZ - ZDimension / 2 + fPillarZ / 2)); + tTauNuDet->AddNode(PillarVol, + 3, + new TGeoTranslation(-XDimension / 2 + fPillarX / 2, + -YDimension / 2 - fBaseY - fPillarY / 2, + fCenterZ + ZDimension / 2 - fPillarZ / 2)); + tTauNuDet->AddNode(PillarVol, + 4, + new TGeoTranslation(XDimension / 2 - fPillarX / 2, + -YDimension / 2 - fBaseY - fPillarY / 2, + fCenterZ + ZDimension / 2 - fPillarZ / 2)); + } } - } - - volBrick->SetVisibility(kTRUE); - - //The CES is required only in the option with magnet surrounding the emulsion target - if(fDesign!=2 && fDesign!=4) - { - //CES - - TGeoBBox *CES = new TGeoBBox("ces", EmulsionX/2, EmulsionY/2, CESWidth/2); - TGeoVolume *volCES = new TGeoVolume("CES", CES, air); - volCES->SetTransparency(5); - volCES->SetLineColor(kYellow-10); - volCES->SetVisibility(kTRUE); - - TGeoBBox *RohGap = new TGeoBBox("RohGap", EmulsionX/2, EmulsionY/2, RohacellGap/2); - TGeoVolume *volRohGap = new TGeoVolume("RohacellGap",RohGap,air); //using AIR for CES, not rohacell - volRohGap->SetTransparency(1); - volRohGap->SetLineColor(kYellow); - - for(Int_t n=0; nAddNode(volRohGap, n, new TGeoTranslation(0,0,-CESWidth/2 +CESPackageZ/2+ EmPlateWidth + RohacellGap/2 + n*LayerCESWidth)); //ROHACELL - } - if(fsingleemulsionfilm){ //simplified configuration, unique sensitive layer for the whole emulsion plate - TGeoBBox *EmulsionFilmCES = new TGeoBBox("EmulsionFilmCES", EmulsionX/2, EmulsionY/2, EmPlateWidth/2); - TGeoVolume *volEmulsionFilmCES = new TGeoVolume("EmulsionCES",EmulsionFilmCES,Emufilm); //TOP - volEmulsionFilmCES->SetLineColor(kBlue); - if(fPassive==0) - { - AddSensitiveVolume(volEmulsionFilmCES); - } - - for(Int_t n=0; nAddNode(volEmulsionFilmCES,n, new TGeoTranslation(0,0,-CESWidth/2+CESPackageZ/2+EmPlateWidth/2+n*LayerCESWidth)); - } - - } - else{ //more accurate configuration, two emulsion films divided by a plastic base - - TGeoBBox *EmulsionFilmCES = new TGeoBBox("EmulsionFilmCES", EmulsionX/2, EmulsionY/2, EmulsionThickness/2); - TGeoVolume *volEmulsionFilmCES = new TGeoVolume("EmulsionCES",EmulsionFilmCES,NEmu); //TOP - TGeoVolume *volEmulsionFilm2CES = new TGeoVolume("Emulsion2CES",EmulsionFilmCES,NEmu); //BOTTOM - volEmulsionFilmCES->SetLineColor(kBlue); - volEmulsionFilm2CES->SetLineColor(kBlue); - if(fPassive==0) - { - AddSensitiveVolume(volEmulsionFilmCES); - AddSensitiveVolume(volEmulsionFilm2CES); - } - //CES PLASTIC BASE - TGeoBBox *PlBaseCES = new TGeoBBox("PlBaseCES", EmulsionX/2, EmulsionY/2, PlasticBaseThickness/2); - TGeoVolume *volPlBaseCES = new TGeoVolume("PlasticBaseCES",PlBaseCES,PBase); - volPlBaseCES->SetLineColor(kYellow); - for(Int_t n=0; nAddNode(volEmulsionFilm2CES,n, new TGeoTranslation(0,0,-CESWidth/2+CESPackageZ/2+EmulsionThickness/2+n*LayerCESWidth)); //BOTTOM - volCES->AddNode(volEmulsionFilmCES, n, new TGeoTranslation(0,0,-CESWidth/2+CESPackageZ/2+3*EmulsionThickness/2+PlasticBaseThickness+n*LayerCESWidth)); //TOP - volCES->AddNode(volPlBaseCES, n, new TGeoTranslation(0,0,-CESWidth/2+CESPackageZ/2+EmulsionThickness+PlasticBaseThickness/2+n*LayerCESWidth)); //PLASTIC BASE - // if(n == 2) - // cout << "-CESWidth/2+3*EmulsionThickness/2+PlasticBaseThickness+n*LayerCESWidth = " << -CESWidth/2+3*EmulsionThickness/2+PlasticBaseThickness+n*LayerCESWidth << endl; - } - - } - - volCell->AddNode(volBrick,1,new TGeoTranslation(0,0,-CellWidth/2 + BrickZ/2)); - volCell->AddNode(volCES,1,new TGeoTranslation(0,0,-CellWidth/2 + BrickZ + CESWidth/2)); - - TGeoBBox *Row = new TGeoBBox("row",WallXDim/2, BrickY/2, CellWidth/2); - TGeoVolume *volRow = new TGeoVolume("Row",Row,air); - volRow->SetLineColor(20); - - Double_t d_cl_x = -WallXDim/2; - for(int j= 0; j < fNCol; j++) - { - volRow->AddNode(volCell,j,new TGeoTranslation(d_cl_x+BrickX/2, 0, 0)); - d_cl_x += BrickX; - } - - TGeoBBox *Wall = new TGeoBBox("wall",WallXDim/2, WallYDim/2, CellWidth/2); - TGeoVolume *volWall = new TGeoVolume("Wall",Wall,air); - - Double_t d_cl_y = -WallYDim/2; - for(int k= 0; k< fNRow; k++) - { - volWall->AddNode(volRow,k,new TGeoTranslation(0, d_cl_y + BrickY/2, 0)); - - // 2mm is the distance for the structure that holds the brick - d_cl_y += BrickY + Ydistance; - } - - //Columns - - Double_t d_cl_z = - ZDimension/2 + TTrackerZ; - - for(int l = 0; l < fNWall; l++) - { - volTarget->AddNode(volWall,l,new TGeoTranslation(0, 0, d_cl_z +CellWidth/2)); - - //6 cm is the distance between 2 columns of consecutive Target for TT placement - d_cl_z += CellWidth + TTrackerZ; - } +} // end construct geometry + +Bool_t Target::ProcessHits(FairVolume* vol) +{ + /** This method is called from the MC stepping */ + // Set parameters at entrance of volume. Reset ELoss. + if (gMC->IsTrackEntering()) { + fELoss = 0.; + fTime = gMC->TrackTime() * 1.0e09; + fLength = gMC->TrackLength(); + gMC->TrackPosition(fPos); + gMC->TrackMomentum(fMom); } + // Sum energy loss for all steps in the active volume + fELoss += gMC->Edep(); + + // Create muonPoint at exit of active volume + if (gMC->IsTrackExiting() || gMC->IsTrackStop() || gMC->IsTrackDisappeared()) { + fTrackID = gMC->GetStack()->GetCurrentTrackNumber(); + // Int_t fTrackID = gMC->GetStack()->GetCurrentTrackNumber(); + gMC->CurrentVolID(fVolumeID); + Int_t detID = fVolumeID; + // gGeoManager->PrintOverlaps(); + + // cout<< "detID = " << detID << endl; + Int_t MaxLevel = gGeoManager->GetLevel(); + const Int_t MaxL = MaxLevel; + // cout << "MaxLevel = " << MaxL << endl; + // cout << gMC->CurrentVolPath()<< endl; + + Int_t motherV[MaxL]; + // Bool_t EmTop = 0, EmBot = 0, EmCESTop = 0, EmCESBot = 0; + Bool_t EmBrick = false; + Bool_t EmTop = false; + Int_t NPlate = 0; + const char* name; + + name = gMC->CurrentVolName(); + // cout << name << endl; + + if (strcmp(name, "Emulsion") == 0) { + EmBrick = 1; + NPlate = detID; + EmTop = 1; + } + if (strcmp(name, "Emulsion2") == 0) { + EmBrick = 1; + NPlate = detID; + EmTop = 0; + } + if (strcmp(name, "EmulsionCES") == 0) { + NPlate = detID; + EmTop = 1; + } + if (strcmp(name, "Emulsion2CES") == 0) { + NPlate = detID; + EmTop = 0; + } + Int_t NWall = 0, NColumn = 0, NRow = 0; + + for (Int_t i = 0; i < MaxL; i++) { + motherV[i] = gGeoManager->GetMother(i)->GetNumber(); + const char* mumname = gMC->CurrentVolOffName(i); + if (motherV[0] == 1 && motherV[0] != detID) { + if (strcmp(mumname, "Brick") == 0 || strcmp(mumname, "CES") == 0) + NColumn = motherV[i]; + if (strcmp(mumname, "Cell") == 0) + NRow = motherV[i]; + if (strcmp(mumname, "Row") == 0) + NWall = motherV[i]; + if ((strcmp(mumname, "Wall") == 0) && (motherV[i] == 2)) + NWall += fNWall; + } else { + + if (strcmp(mumname, "Cell") == 0) + NColumn = motherV[i]; + if (strcmp(mumname, "Row") == 0) + NRow = motherV[i]; + if (strcmp(mumname, "Wall") == 0) + NWall = motherV[i]; + if ((strcmp(mumname, "volTarget") == 0) && (motherV[i] == 2)) + NWall += fNWall; + } + // cout << i << " " << motherV[i] << " name = " << mumname << endl; + } - //in fDesign==2 and fDesign==4 the emulsion target is not surrounded by a magnet => no magnetic field inside - //In the no Magnetic field option, no CES is needed => only brick walls + TT - if(fDesign==2 || fDesign == 4) - { - EmulsionMagnet emuMag; - - TGeoVolume *tTauNuDet = gGeoManager->GetVolume("tTauNuDet"); - cout<< "Tau Nu Detector fMagnetConfig: "<< fDesign<AddNode(volTarget,1,new TGeoTranslation(0,0,fCenterZ)); - - TGeoBBox *Row = new TGeoBBox("row",WallXDim/2, BrickY/2, WallZDim/2); - TGeoVolume *volRow = new TGeoVolume("Row",Row,air); - volRow->SetLineColor(20); - - Double_t d_cl_x = -WallXDim/2; - for(int j= 0; j < fNCol; j++) - { - volRow->AddNode(volBrick,j,new TGeoTranslation(d_cl_x+BrickX/2, 0, 0)); - d_cl_x += BrickX; - } - TGeoBBox *Wall = new TGeoBBox("wall",WallXDim/2, WallYDim/2, WallZDim/2); - TGeoVolume *volWall = new TGeoVolume("Wall",Wall,air); - volWall->SetLineColor(kGreen); - - Double_t d_cl_y = -WallYDim/2; - for(int k= 0; k< fNRow; k++) - { - volWall->AddNode(volRow,k,new TGeoTranslation(0, d_cl_y + BrickY/2, 0)); - - // 2mm is the distance for the structure that holds the brick - d_cl_y += BrickY + Ydistance; - } - //Columns - - Double_t d_cl_z = - ZDimension/2 + TTrackerZ; - - for(int l = 0; l < fNWall; l++) - { - volTarget->AddNode(volWall,l,new TGeoTranslation(0, 0, d_cl_z +BrickZ/2)); - - //6 cm is the distance between 2 columns of consecutive Target for TT placement - d_cl_z += BrickZ + TTrackerZ; - } - if(fDesign==2) - { - TGeoBBox *Base = new TGeoBBox("Base", fBaseX/2, fBaseY/2, fBaseZ/2); - TGeoVolume *volBase = new TGeoVolume("volBase",Base,Conc); - volBase->SetLineColor(kYellow-3); - tTauNuDet->AddNode(volBase,1, new TGeoTranslation(0,-WallYDim/2 - fBaseY/2,fCenterZ)); - - TGeoBBox *PillarBox = new TGeoBBox(fPillarX/2,fPillarY/2, fPillarZ/2); - TGeoVolume *PillarVol = new TGeoVolume("PillarVol",PillarBox,Steel); - PillarVol->SetLineColor(kGreen+3); - tTauNuDet->AddNode(PillarVol,1, new TGeoTranslation(-XDimension/2+fPillarX/2,-YDimension/2-fBaseY-fPillarY/2, fCenterZ-ZDimension/2+fPillarZ/2)); - tTauNuDet->AddNode(PillarVol,2, new TGeoTranslation(XDimension/2-fPillarX/2,-YDimension/2-fBaseY-fPillarY/2, fCenterZ-ZDimension/2+fPillarZ/2)); - tTauNuDet->AddNode(PillarVol,3, new TGeoTranslation(-XDimension/2+fPillarX/2,-YDimension/2-fBaseY-fPillarY/2, fCenterZ+ZDimension/2-fPillarZ/2)); - tTauNuDet->AddNode(PillarVol,4, new TGeoTranslation(XDimension/2-fPillarX/2,-YDimension/2-fBaseY-fPillarY/2, fCenterZ+ZDimension/2-fPillarZ/2)); + Bool_t BrickorCES = EmBrick == 1; + + detID = (NWall + 1) * 1E7 + (NRow + 1) * 1E6 + (NColumn + 1) * 1E4 + BrickorCES * 1E3 + (NPlate + 1) * 1E1 + + EmTop * 1; + + fVolumeID = detID; + + if (fELoss == 0.) { + return kFALSE; + } + TParticle* p = gMC->GetStack()->GetCurrentTrack(); + // Int_t MotherID =gMC->GetStack()->GetCurrentParentTrackNumber(); + Int_t pdgCode = p->GetPdgCode(); + + TLorentzVector Pos; + gMC->TrackPosition(Pos); + Double_t xmean = (fPos.X() + Pos.X()) / 2.; + Double_t ymean = (fPos.Y() + Pos.Y()) / 2.; + Double_t zmean = (fPos.Z() + Pos.Z()) / 2.; + + AddHit(fTrackID, + fVolumeID, + TVector3(xmean, ymean, zmean), + TVector3(fMom.Px(), fMom.Py(), fMom.Pz()), + fTime, + fLength, + fELoss, + pdgCode); + + // Increment number of muon det points in TParticle + ShipStack* stack = (ShipStack*)gMC->GetStack(); + stack->AddPoint(ktauTarget); } - } -}//end construct geometry - -Bool_t Target::ProcessHits(FairVolume* vol) -{ - /** This method is called from the MC stepping */ - //Set parameters at entrance of volume. Reset ELoss. - if ( gMC->IsTrackEntering() ) { - fELoss = 0.; - fTime = gMC->TrackTime() * 1.0e09; - fLength = gMC->TrackLength(); - gMC->TrackPosition(fPos); - gMC->TrackMomentum(fMom); - } - // Sum energy loss for all steps in the active volume - fELoss += gMC->Edep(); - - // Create muonPoint at exit of active volume - if ( gMC->IsTrackExiting() || - gMC->IsTrackStop() || - gMC->IsTrackDisappeared() ) { - fTrackID = gMC->GetStack()->GetCurrentTrackNumber(); - //Int_t fTrackID = gMC->GetStack()->GetCurrentTrackNumber(); - gMC->CurrentVolID(fVolumeID); - Int_t detID = fVolumeID; - //gGeoManager->PrintOverlaps(); - - //cout<< "detID = " << detID << endl; - Int_t MaxLevel = gGeoManager->GetLevel(); - const Int_t MaxL = MaxLevel; - //cout << "MaxLevel = " << MaxL << endl; - //cout << gMC->CurrentVolPath()<< endl; - - - Int_t motherV[MaxL]; -// Bool_t EmTop = 0, EmBot = 0, EmCESTop = 0, EmCESBot = 0; - Bool_t EmBrick = false; - Bool_t EmTop = false; - Int_t NPlate =0; - const char *name; - - name = gMC->CurrentVolName(); - //cout << name << endl; - - if(strcmp(name, "Emulsion") == 0) - { - EmBrick=1; - NPlate = detID; - EmTop=1; - } - if(strcmp(name, "Emulsion2") == 0) - { - EmBrick=1; - NPlate = detID; - EmTop=0; - } - if(strcmp(name, "EmulsionCES") == 0) - { - NPlate = detID; - EmTop=1; - } - if(strcmp(name, "Emulsion2CES") == 0) - { - NPlate = detID; - EmTop=0; - } - - Int_t NWall = 0, NColumn =0, NRow =0; - - for(Int_t i = 0; i < MaxL;i++) - { - motherV[i] = gGeoManager->GetMother(i)->GetNumber(); - const char *mumname = gMC->CurrentVolOffName(i); - if(motherV[0]==1 && motherV[0]!=detID) - { - if(strcmp(mumname, "Brick") == 0 ||strcmp(mumname, "CES") == 0) NColumn = motherV[i]; - if(strcmp(mumname, "Cell") == 0) NRow = motherV[i]; - if(strcmp(mumname, "Row") == 0) NWall = motherV[i]; - if((strcmp(mumname, "Wall") == 0)&& (motherV[i]==2)) NWall += fNWall; - } - else - { - - if(strcmp(mumname, "Cell") == 0) NColumn = motherV[i]; - if(strcmp(mumname, "Row") == 0) NRow = motherV[i]; - if(strcmp(mumname, "Wall") == 0) NWall = motherV[i]; - if((strcmp(mumname, "volTarget") == 0) && (motherV[i]==2)) NWall += fNWall; - } - //cout << i << " " << motherV[i] << " name = " << mumname << endl; - } - - Bool_t BrickorCES = EmBrick == 1; - - - detID = (NWall+1) *1E7 + (NRow+1) * 1E6 + (NColumn+1)*1E4 + BrickorCES *1E3 + (NPlate+1)*1E1 + EmTop*1 ; - - - fVolumeID = detID; - - if (fELoss == 0. ) { return kFALSE; } - TParticle* p=gMC->GetStack()->GetCurrentTrack(); - //Int_t MotherID =gMC->GetStack()->GetCurrentParentTrackNumber(); - Int_t pdgCode = p->GetPdgCode(); - - TLorentzVector Pos; - gMC->TrackPosition(Pos); - Double_t xmean = (fPos.X()+Pos.X())/2. ; - Double_t ymean = (fPos.Y()+Pos.Y())/2. ; - Double_t zmean = (fPos.Z()+Pos.Z())/2. ; - - - AddHit(fTrackID,fVolumeID, TVector3(xmean, ymean, zmean), - TVector3(fMom.Px(), fMom.Py(), fMom.Pz()), fTime, fLength, - fELoss, pdgCode); - - // Increment number of muon det points in TParticle - ShipStack* stack = (ShipStack*) gMC->GetStack(); - stack->AddPoint(ktauTarget); - } - - return kTRUE; -} - - -void Target::DecodeBrickID(Int_t detID, Int_t &NWall, Int_t &NRow, Int_t &NColumn, Int_t &NPlate, Bool_t &EmCES, Bool_t &EmBrick, Bool_t &EmTop) -{ - Bool_t BrickorCES = false; - - NWall = detID/1E7; - NRow = (detID - NWall*1E7)/1E6; - NColumn = (detID - NWall*1E7 -NRow*1E6)/1E4; - Double_t b = (detID - NWall*1E7 -NRow*1E6 - NColumn*1E4)/1.E3; - if(b < 1) - { - BrickorCES = 0; - NPlate = (detID - NWall*1E7 -NRow*1E6 - NColumn*1E4 - BrickorCES*1E3)/1E1; -// NPlate = detID - NWall*1E7 -NRow*1E6 - NColumn*1E4 - BrickorCES*1E3; + + return kTRUE; +} + +void Target::DecodeBrickID(Int_t detID, + Int_t& NWall, + Int_t& NRow, + Int_t& NColumn, + Int_t& NPlate, + Bool_t& EmCES, + Bool_t& EmBrick, + Bool_t& EmTop) +{ + Bool_t BrickorCES = false; + + NWall = detID / 1E7; + NRow = (detID - NWall * 1E7) / 1E6; + NColumn = (detID - NWall * 1E7 - NRow * 1E6) / 1E4; + Double_t b = (detID - NWall * 1E7 - NRow * 1E6 - NColumn * 1E4) / 1.E3; + if (b < 1) { + BrickorCES = 0; + NPlate = (detID - NWall * 1E7 - NRow * 1E6 - NColumn * 1E4 - BrickorCES * 1E3) / 1E1; + // NPlate = detID - NWall*1E7 -NRow*1E6 - NColumn*1E4 - BrickorCES*1E3; } - if(b >= 1) - { - BrickorCES = 1; - NPlate = (detID - NWall*1E7 -NRow*1E6 - NColumn*1E4 - BrickorCES*1E3)/1E1; -// NPlate = detID - NWall*1E7 -NRow*1E6 - NColumn*1E4 - BrickorCES*1E3; + if (b >= 1) { + BrickorCES = 1; + NPlate = (detID - NWall * 1E7 - NRow * 1E6 - NColumn * 1E4 - BrickorCES * 1E3) / 1E1; + // NPlate = detID - NWall*1E7 -NRow*1E6 - NColumn*1E4 - BrickorCES*1E3; } - EmTop = (detID - NWall*1E7 -NRow*1E6 - NColumn*1E4- BrickorCES*1E3- NPlate*1E1)/1E0; - if(BrickorCES == 0) - { - EmCES = 1; EmBrick =0; + EmTop = (detID - NWall * 1E7 - NRow * 1E6 - NColumn * 1E4 - BrickorCES * 1E3 - NPlate * 1E1) / 1E0; + if (BrickorCES == 0) { + EmCES = 1; + EmBrick = 0; } - if(BrickorCES == 1) - { - EmBrick = 1; EmCES =0; + if (BrickorCES == 1) { + EmBrick = 1; + EmCES = 0; } - // cout << "NPlate = " << NPlate << "; NColumn = " << NColumn << "; NRow = " << NRow << "; NWall = " << NWall << endl; - // cout << "BrickorCES = " << BrickorCES <Register("TargetPoint", "Target", fTargetPointCollection, kTRUE); } TClonesArray* Target::GetCollection(Int_t iColl) const { - if (iColl == 0) { return fTargetPointCollection; } - else { return NULL; } + if (iColl == 0) { + return fTargetPointCollection; + } else { + return NULL; + } } void Target::Reset() { - fTargetPointCollection->Clear(); + fTargetPointCollection->Clear(); } - -TargetPoint* Target::AddHit(Int_t trackID,Int_t detID, - TVector3 pos, TVector3 mom, - Double_t time, Double_t length, - Double_t eLoss, Int_t pdgCode) +TargetPoint* Target::AddHit(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t time, + Double_t length, + Double_t eLoss, + Int_t pdgCode) { - TClonesArray& clref = *fTargetPointCollection; - Int_t size = clref.GetEntriesFast(); - //cout << "brick hit called"<< pos.z()< // for string - -#include "TVector3.h" +#include "FairModule.h" // for FairModule +#include "Rtypes.h" // for ShipMuonShield::Class, Bool_t, etc #include "TLorentzVector.h" +#include "TVector3.h" + +#include // for string class TargetPoint; class FairVolume; @@ -25,14 +23,14 @@ class TClonesArray; class Target : public FairDetector { -public: - Target(const char* name, const Double_t Ydist, Bool_t Active, const char* Title = "NuTauTarget"); + public: + Target(const char* name, const Double_t Ydist, Bool_t Active, const char* Title = "NuTauTarget"); Target(); virtual ~Target(); /** Create the detector geometry */ - //Set options for detector contruction (active/passive, which design) + // Set options for detector contruction (active/passive, which design) void SetDetectorDesign(Int_t Design); void MakeNuTargetPassive(Bool_t a); void MergeTopBot(Bool_t SingleEmFilm); @@ -41,16 +39,28 @@ class Target : public FairDetector void SetTargetWallDimension(Double_t WallXDim, Double_t WallYDim, Double_t WallZDim); void SetDetectorDimension(Double_t xdim, Double_t ydim, Double_t zdim); - void SetEmulsionParam(Double_t EmTh, Double_t EmX, Double_t EmY, Double_t PBTh,Double_t EPlW, Double_t LeadTh, Double_t AllPW); - void SetBrickParam(Double_t BrX, Double_t BrY, Double_t BrZ, Double_t BrPackX, Double_t BrPackY,Double_t BrPackZ, Int_t number_of_plates_); + void SetEmulsionParam(Double_t EmTh, + Double_t EmX, + Double_t EmY, + Double_t PBTh, + Double_t EPlW, + Double_t LeadTh, + Double_t AllPW); + void SetBrickParam(Double_t BrX, + Double_t BrY, + Double_t BrZ, + Double_t BrPackX, + Double_t BrPackY, + Double_t BrPackZ, + Int_t number_of_plates_); void SetCESParam(Double_t RohG, Double_t LayerCESW, Double_t CESW, Double_t CESPack); void SetCellParam(Double_t CellW); void SetNumberBricks(Double_t col, Double_t row, Double_t wall); void SetTTzdimension(Double_t TTZ); void SetNumberTargets(Int_t target); - //Functions to get parameters relative to the magnet in which the detector is placed - void SetMagnetConfiguration(Int_t config);//1=TP, 0=new + // Functions to get parameters relative to the magnet in which the detector is placed + void SetMagnetConfiguration(Int_t config); // 1=TP, 0=new void SetMagnetHeight(Double_t Y); void SetBaseHeight(Double_t Y); void SetColumnHeight(Double_t Y); @@ -59,14 +69,21 @@ class Target : public FairDetector void SetMagneticField(Double_t B); void SetCenterZ(Double_t z); - //Functions to set dimension of both the base and the pillars in no magnet configuration options. The pillars are defined in EmulsionMagnet class in the option with magnet. + // Functions to set dimension of both the base and the pillars in no magnet configuration options. The pillars are + // defined in EmulsionMagnet class in the option with magnet. void SetBaseDimension(Double_t X, Double_t Y, Double_t Z); void SetPillarDimension(Double_t X, Double_t Y, Double_t Z); + void DecodeBrickID(Int_t detID, + Int_t& NWall, + Int_t& NRow, + Int_t& NColumn, + Int_t& NPlate, + Bool_t& EmCES, + Bool_t& EmBrick, + Bool_t& EmTop); - void DecodeBrickID(Int_t detID, Int_t &NWall, Int_t &NRow, Int_t &NColumn, Int_t &NPlate, Bool_t &EmCES, Bool_t &EmBrick, Bool_t &EmTop); - - void SetHpTParam(Int_t n, Double_t dd, Double_t DZ); //other detector's parameters (needed for positioning) + void SetHpTParam(Int_t n, Double_t dd, Double_t DZ); // other detector's parameters (needed for positioning) /** Initialization of the detector is done here */ virtual void Initialize(); @@ -74,105 +91,107 @@ class Target : public FairDetector /** this method is called for each step during simulation * (see FairMCApplication::Stepping()) */ - virtual Bool_t ProcessHits( FairVolume* v=0); + virtual Bool_t ProcessHits(FairVolume* v = 0); /** Registers the produced collections in FAIRRootManager. */ - virtual void Register(); + virtual void Register(); /** Gets the produced collections */ - virtual TClonesArray* GetCollection(Int_t iColl) const ; + virtual TClonesArray* GetCollection(Int_t iColl) const; /** has to be called after each event to reset the containers */ - virtual void Reset(); + virtual void Reset(); /** This method is an example of how to add your own point * of type muonPoint to the clones array */ - TargetPoint* AddHit(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t time, Double_t length, - Double_t eLoss, Int_t pdgCode); + TargetPoint* AddHit(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t time, + Double_t length, + Double_t eLoss, + Int_t pdgCode); /* TargetPoint* AddHit(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t time, Double_t length, - Double_t eLoss, Int_t pdgCode, - Int_t EmTop, Int_t EmBot, Int_t EmCESTop, Int_t EmCESBot, Int_t TT, - Int_t NPlate, Int_t NColumn, Int_t NRow, Int_t NWall); + TVector3 pos, TVector3 mom, + Double_t time, Double_t length, + Double_t eLoss, Int_t pdgCode, + Int_t EmTop, Int_t EmBot, Int_t EmCESTop, Int_t EmCESBot, Int_t TT, + Int_t NPlate, Int_t NColumn, Int_t NRow, Int_t NWall); */ /** The following methods can be implemented if you need to make * any optional action in your detector during the transport. */ - virtual void CopyClones( TClonesArray* cl1, TClonesArray* cl2 , - Int_t offset) {;} - virtual void SetSpecialPhysicsCuts() {;} - virtual void EndOfEvent(); - virtual void FinishPrimary() {;} - virtual void FinishRun() {;} - virtual void BeginPrimary() {;} - virtual void PostTrack() {;} - virtual void PreTrack() {;} - virtual void BeginEvent() {;} - + virtual void CopyClones(TClonesArray* cl1, TClonesArray* cl2, Int_t offset) { ; } + virtual void SetSpecialPhysicsCuts() { ; } + virtual void EndOfEvent(); + virtual void FinishPrimary() { ; } + virtual void FinishRun() { ; } + virtual void BeginPrimary() { ; } + virtual void PostTrack() { ; } + virtual void PreTrack() { ; } + virtual void BeginEvent() { ; } Target(const Target&); Target& operator=(const Target&); - ClassDef(Target,4) + ClassDef(Target, 4) -private: + private + : - /** Track information to be stored until the track leaves the - active volume. - */ - Int_t fTrackID; //! track index - Int_t fVolumeID; //! volume id - TLorentzVector fPos; //! position at entrance - TLorentzVector fMom; //! momentum at entrance - Double32_t fTime; //! time - Double32_t fLength; //! length - Double32_t fELoss; //! energy loss + /** Track information to be stored until the track leaves the + active volume. + */ + Int_t fTrackID; //! track index + Int_t fVolumeID; //! volume id + TLorentzVector fPos; //! position at entrance + TLorentzVector fMom; //! momentum at entrance + Double32_t fTime; //! time + Double32_t fLength; //! length + Double32_t fELoss; //! energy loss /** container for data points */ - TClonesArray* fTargetPointCollection; - - //switch for building the detector with active layers or with passive material only + TClonesArray* fTargetPointCollection; + // switch for building the detector with active layers or with passive material only -protected: + protected: + Bool_t fPassive; // 0 = with Emulsion, 1 = only lead + rohacell + Bool_t fsingleemulsionfilm; // 0 = both top and bottom layers active, separated by plastic base; 1 = only one + // active layer + Int_t fDesign; // 0=TP, 1=NewMagnet (Davide), 2=No Magnet Config - Bool_t fPassive; //0 = with Emulsion, 1 = only lead + rohacell - Bool_t fsingleemulsionfilm; //0 = both top and bottom layers active, separated by plastic base; 1 = only one active layer - Int_t fDesign; //0=TP, 1=NewMagnet (Davide), 2=No Magnet Config - - //Position of the Center of the Detector + // Position of the Center of the Detector Double_t fCenterZ; - //Some Magnet parameters necessary for target positioning + // Some Magnet parameters necessary for target positioning Double_t fMagnetY; Double_t fColumnY; Double_t fMagnetBaseY; Double_t fCoilH1; Double_t fCoilH2; - //Bricks + // Bricks Double_t fField; Int_t fNCol; Int_t fNRow; Int_t fNWall; Int_t fNTarget; - Int_t number_of_plates; //// + Int_t number_of_plates; //// - Double_t XDimension; //dimension of the target box (= 2 x 2 x 1) m^3 + Double_t XDimension; // dimension of the target box (= 2 x 2 x 1) m^3 Double_t YDimension; Double_t ZDimension; - Double_t WallXDim; //dimension of the wall of bricks + Double_t WallXDim; // dimension of the wall of bricks Double_t WallYDim; Double_t WallZDim; @@ -182,45 +201,43 @@ class Target : public FairDetector Double_t PlasticBaseThickness; Double_t LeadThickness; - Double_t EmPlateWidth; // Z dimension of the emulsion plates = 2*EmulsionThickness+PlasticBaseThickness - Double_t AllPlateWidth; //PlateZ + LeadThickness - + Double_t EmPlateWidth; // Z dimension of the emulsion plates = 2*EmulsionThickness+PlasticBaseThickness + Double_t AllPlateWidth; // PlateZ + LeadThickness - Double_t BrickPackageX; //dimension of the brick package along X - Double_t BrickPackageY; //dimension of the brick package along Y - Double_t BrickPackageZ; //dimension of the brick package along Z - Double_t CESPackageZ; //dimension of the CES package along Z + Double_t BrickPackageX; // dimension of the brick package along X + Double_t BrickPackageY; // dimension of the brick package along Y + Double_t BrickPackageZ; // dimension of the brick package along Z + Double_t CESPackageZ; // dimension of the CES package along Z - Double_t Ydistance; //distance in Y between 2 bricks + Double_t Ydistance; // distance in Y between 2 bricks - Double_t BrickZ; //dimension of the brick + package along the Z axis + Double_t BrickZ; // dimension of the brick + package along the Z axis Double_t BrickY; Double_t BrickX; - Double_t RohacellGap; //dimension of the Rohacell Gap in CES along Z axis + Double_t RohacellGap; // dimension of the Rohacell Gap in CES along Z axis Double_t LayerCESWidth; - Double_t CESWidth; //dimension of the CES along Z axis + Double_t CESWidth; // dimension of the CES along Z axis - Double_t CellWidth; //dimension of Brick + CES along Z axis + Double_t CellWidth; // dimension of Brick + CES along Z axis - //TargetTrackers + // TargetTrackers Double_t TTrackerZ; - //Base and Pillars for option without magnetic field - Double_t fBaseX; - Double_t fBaseY; - Double_t fBaseZ; - Double_t fPillarX; - Double_t fPillarY; - Double_t fPillarZ; + // Base and Pillars for option without magnetic field + Double_t fBaseX; + Double_t fBaseY; + Double_t fBaseZ; + Double_t fPillarX; + Double_t fPillarY; + Double_t fPillarZ; - //other detector's parameters (needed for positioning) - Double_t fHpTDistance; - Double_t fHpTDZ; - Int_t fnHpT; + // other detector's parameters (needed for positioning) + Double_t fHpTDistance; + Double_t fHpTDZ; + Int_t fnHpT; Int_t InitMedium(const char* name); - }; #endif diff --git a/nutaudet/TargetPoint.cxx b/nutaudet/TargetPoint.cxx index ee0062df5d..bf512d9290 100644 --- a/nutaudet/TargetPoint.cxx +++ b/nutaudet/TargetPoint.cxx @@ -4,50 +4,51 @@ using std::cout; using std::endl; - // ----- Default constructor ------------------------------------------- TargetPoint::TargetPoint() - : FairMCPoint() -{ -} + : FairMCPoint() +{} // ------------------------------------------------------------------------- // ----- Standard constructor ------------------------------------------ /* TargetPoint::TargetPoint(Int_t trackID, Int_t detID,TVector3 pos, TVector3 mom, Double_t tof, Double_t length, - Double_t eLoss, Int_t pdgcode, - Bool_t emTop, Bool_t emBot,Bool_t emCESTop, Bool_t emCESBot, Bool_t tt, - Int_t nPlate, Int_t nColumn, Int_t nRow, Int_t nWall) + Double_t eLoss, Int_t pdgcode, + Bool_t emTop, Bool_t emBot,Bool_t emCESTop, Bool_t emCESBot, Bool_t tt, + Int_t nPlate, Int_t nColumn, Int_t nRow, Int_t nWall) : FairMCPoint(trackID, detID, pos, mom, tof, length, eLoss),fPdgCode(pdgcode), fEmTop(emTop), fEmBot(emBot), fEmCESTop(emCESTop), fEmCESBot(emCESBot),fTT(tt), fNPlate(nPlate),fNColumn(nColumn), fNRow(nRow),fNWall(nWall) { } */ -TargetPoint::TargetPoint(Int_t trackID, Int_t detID,TVector3 pos, TVector3 mom, - Double_t tof, Double_t length, - Double_t eLoss, Int_t pdgcode) - : FairMCPoint(trackID, detID, pos, mom, tof, length, eLoss),fPdgCode(pdgcode) -{ } +TargetPoint::TargetPoint(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t tof, + Double_t length, + Double_t eLoss, + Int_t pdgcode) + : FairMCPoint(trackID, detID, pos, mom, tof, length, eLoss) + , fPdgCode(pdgcode) +{} // ------------------------------------------------------------------------- //, EmTop, EmBot, EmCESTop,EmCESBot,TT,NPlate,NColumn,NRow,NWall // ----- Destructor ---------------------------------------------------- -TargetPoint::~TargetPoint() { } +TargetPoint::~TargetPoint() {} // ------------------------------------------------------------------------- // ----- Public method Print ------------------------------------------- void TargetPoint::Print(const Option_t* opt) const { - cout << "-I- TargetPoint: ShipRpc point for track " << fTrackID - << " in detector " << fDetectorID << endl; - cout << " Position (" << fX << ", " << fY << ", " << fZ - << ") cm" << endl; - cout << " Momentum (" << fPx << ", " << fPy << ", " << fPz - << ") GeV" << endl; - cout << " Time " << fTime << " ns, Length " << fLength - << " cm, Energy loss " << fELoss*1.0e06 << " keV" << endl; + cout << "-I- TargetPoint: ShipRpc point for track " << fTrackID << " in detector " << fDetectorID << endl; + cout << " Position (" << fX << ", " << fY << ", " << fZ << ") cm" << endl; + cout << " Momentum (" << fPx << ", " << fPy << ", " << fPz << ") GeV" << endl; + cout << " Time " << fTime << " ns, Length " << fLength << " cm, Energy loss " << fELoss * 1.0e06 << " keV" + << endl; } // ------------------------------------------------------------------------- diff --git a/nutaudet/TargetPoint.h b/nutaudet/TargetPoint.h index 08bdfbd0c3..769192560b 100644 --- a/nutaudet/TargetPoint.h +++ b/nutaudet/TargetPoint.h @@ -1,9 +1,7 @@ #ifndef TARGETPOINT_H #define TARGETPOINT_H 1 - #include "FairMCPoint.h" - #include "TObject.h" #include "TVector3.h" @@ -11,11 +9,9 @@ class TargetPoint : public FairMCPoint { public: - /** Default constructor **/ TargetPoint(); - /** Constructor with arguments *@param trackID Index of MCTrack *@param detID Detector ID @@ -28,11 +24,17 @@ class TargetPoint : public FairMCPoint /*TargetPoint(Int_t trackID, Int_t detID, TVector3 pos, TVector3 mom, Double_t tof, Double_t length, Double_t eLoss, Int_t pdgCode, - Bool_t emTop, Bool_t emBot,Bool_t emCESTop, Bool_t emCESBot, Bool_t tt, - Int_t nPlate, Int_t nColumn, Int_t nRow, Int_t nWall);*/ - - TargetPoint(Int_t trackID, Int_t detID, TVector3 pos, TVector3 mom, - Double_t tof, Double_t length, Double_t eLoss, Int_t pdgCode); + Bool_t emTop, Bool_t emBot,Bool_t emCESTop, Bool_t emCESBot, Bool_t tt, + Int_t nPlate, Int_t nColumn, Int_t nRow, Int_t nWall);*/ + + TargetPoint(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t tof, + Double_t length, + Double_t eLoss, + Int_t pdgCode); /** Destructor **/ virtual ~TargetPoint(); @@ -40,22 +42,17 @@ class TargetPoint : public FairMCPoint /** Output to screen **/ virtual void Print(const Option_t* opt) const; - - Int_t PdgCode() const {return fPdgCode;} - + Int_t PdgCode() const { return fPdgCode; } private: - - Int_t fPdgCode; - /** Copy constructor **/ TargetPoint(const TargetPoint& point); TargetPoint operator=(const TargetPoint& point); - ClassDef(TargetPoint,2) + ClassDef(TargetPoint, 2) }; #endif diff --git a/nutaudet/TargetTracker.cxx b/nutaudet/TargetTracker.cxx index b58380ca11..95e3a7b756 100644 --- a/nutaudet/TargetTracker.cxx +++ b/nutaudet/TargetTracker.cxx @@ -8,53 +8,46 @@ #include "TargetTracker.h" -#include "TTPoint.h" - -#include "TGeoManager.h" -#include "FairRun.h" // for FairRun -#include "FairRuntimeDb.h" // for FairRuntimeDb -#include // for ostream -#include "TList.h" // for TListIter, TList (ptr only) -#include "TObjArray.h" // for TObjArray -#include "TString.h" // for TString - +#include "FairGeoBuilder.h" +#include "FairGeoInterface.h" +#include "FairGeoLoader.h" +#include "FairGeoMedia.h" +#include "FairGeoMedium.h" +#include "FairGeoNode.h" +#include "FairGeoTransform.h" +#include "FairGeoVolume.h" +#include "FairRootManager.h" +#include "FairRun.h" // for FairRun +#include "FairRun.h" +#include "FairRuntimeDb.h" // for FairRuntimeDb +#include "FairRuntimeDb.h" +#include "FairVolume.h" +#include "ShipDetectorList.h" +#include "ShipStack.h" +#include "ShipUnit.h" #include "TClonesArray.h" -#include "TVirtualMC.h" - +#include "TGeoArb8.h" #include "TGeoBBox.h" -#include "TGeoTrd1.h" #include "TGeoCompositeShape.h" -#include "TGeoTube.h" +#include "TGeoManager.h" #include "TGeoMaterial.h" #include "TGeoMedium.h" #include "TGeoTrd1.h" -#include "TGeoArb8.h" - +#include "TGeoTube.h" +#include "TGeoUniformMagField.h" +#include "TList.h" // for TListIter, TList (ptr only) +#include "TObjArray.h" // for TObjArray #include "TParticle.h" -#include "TParticlePDG.h" #include "TParticleClassPDG.h" +#include "TParticlePDG.h" +#include "TString.h" // for TString +#include "TTPoint.h" +#include "TVirtualMC.h" #include "TVirtualMCStack.h" -#include "FairVolume.h" -#include "FairGeoVolume.h" -#include "FairGeoNode.h" -#include "FairRootManager.h" -#include "FairGeoLoader.h" -#include "FairGeoInterface.h" -#include "FairGeoTransform.h" -#include "FairGeoMedia.h" -#include "FairGeoMedium.h" -#include "FairGeoBuilder.h" -#include "FairRun.h" -#include "FairRuntimeDb.h" - -#include "ShipDetectorList.h" -#include "ShipUnit.h" -#include "ShipStack.h" - -#include "TGeoUniformMagField.h" -#include // for NULL -#include // for operator<<, basic_ostream,etc +#include // for ostream +#include // for operator<<, basic_ostream,etc +#include // for NULL #include using std::cout; @@ -63,32 +56,36 @@ using std::endl; using namespace ShipUnit; TargetTracker::TargetTracker() -: FairDetector("TargetTracker", "",kTRUE), - fTrackID(-1), -fVolumeID(-1), -fPos(), -fMom(), -fTime(-1.), -fLength(-1.), -fELoss(-1), -fTTPointCollection(new TClonesArray("TTPoint")) -{ -} - -TargetTracker::TargetTracker(const char* name, Double_t TTX, Double_t TTY, Double_t TTZ, Bool_t Active,const char* Title) -: FairDetector(name, true, ktauTT), - fTrackID(-1), -fVolumeID(-1), -fPos(), -fMom(), -fTime(-1.), -fLength(-1.), -fELoss(-1), -fTTPointCollection(new TClonesArray("TTPoint")) + : FairDetector("TargetTracker", "", kTRUE) + , fTrackID(-1) + , fVolumeID(-1) + , fPos() + , fMom() + , fTime(-1.) + , fLength(-1.) + , fELoss(-1) + , fTTPointCollection(new TClonesArray("TTPoint")) +{} + +TargetTracker::TargetTracker(const char* name, + Double_t TTX, + Double_t TTY, + Double_t TTZ, + Bool_t Active, + const char* Title) + : FairDetector(name, true, ktauTT) + , fTrackID(-1) + , fVolumeID(-1) + , fPos() + , fMom() + , fTime(-1.) + , fLength(-1.) + , fELoss(-1) + , fTTPointCollection(new TClonesArray("TTPoint")) { - TTrackerX = TTX; - TTrackerY = TTY; - TTrackerZ = TTZ; + TTrackerX = TTX; + TTrackerY = TTY; + TTrackerZ = TTZ; } TargetTracker::~TargetTracker() @@ -107,39 +104,42 @@ void TargetTracker::Initialize() // ----- Private method InitMedium Int_t TargetTracker::InitMedium(const char* name) { - static FairGeoLoader *geoLoad=FairGeoLoader::Instance(); - static FairGeoInterface *geoFace=geoLoad->getGeoInterface(); - static FairGeoMedia *media=geoFace->getMedia(); - static FairGeoBuilder *geoBuild=geoLoad->getGeoBuilder(); + static FairGeoLoader* geoLoad = FairGeoLoader::Instance(); + static FairGeoInterface* geoFace = geoLoad->getGeoInterface(); + static FairGeoMedia* media = geoFace->getMedia(); + static FairGeoBuilder* geoBuild = geoLoad->getGeoBuilder(); - FairGeoMedium *ShipMedium=media->getMedium(name); + FairGeoMedium* ShipMedium = media->getMedium(name); - if (!ShipMedium) - { - Fatal("InitMedium","Material %s not defined in media file.", name); + if (!ShipMedium) { + Fatal("InitMedium", "Material %s not defined in media file.", name); return -1111; } - TGeoMedium* medium=gGeoManager->GetMedium(name); - if (medium!=NULL) + TGeoMedium* medium = gGeoManager->GetMedium(name); + if (medium != NULL) return ShipMedium->getMediumIndex(); return geoBuild->createMedium(ShipMedium); } -void TargetTracker::SetSciFiParam(Double_t scifimat_width_, Double_t scifimat_hor_, Double_t scifimat_vert_, - Double_t scifimat_z_, Double_t support_z_, Double_t honeycomb_z_) +void TargetTracker::SetSciFiParam(Double_t scifimat_width_, + Double_t scifimat_hor_, + Double_t scifimat_vert_, + Double_t scifimat_z_, + Double_t support_z_, + Double_t honeycomb_z_) { - scifimat_width = scifimat_width_; - scifimat_hor = scifimat_hor_; - scifimat_vert = scifimat_vert_; - scifimat_z = scifimat_z_; - support_z = support_z_; - honeycomb_z = honeycomb_z_; + scifimat_width = scifimat_width_; + scifimat_hor = scifimat_hor_; + scifimat_vert = scifimat_vert_; + scifimat_z = scifimat_z_; + support_z = support_z_; + honeycomb_z = honeycomb_z_; } void TargetTracker::SetNumberSciFi(Int_t n_hor_planes_, Int_t n_vert_planes_) { - n_hor_planes = n_hor_planes_; - n_vert_planes = n_vert_planes_; + n_hor_planes = n_hor_planes_; + n_vert_planes = n_vert_planes_; } void TargetTracker::SetTargetTrackerParam(Double_t TTX, Double_t TTY, Double_t TTZ) @@ -151,173 +151,192 @@ void TargetTracker::SetTargetTrackerParam(Double_t TTX, Double_t TTY, Double_t T void TargetTracker::SetBrickParam(Double_t CellW) { - CellWidth = CellW; + CellWidth = CellW; } void TargetTracker::SetTotZDimension(Double_t Zdim) { - ZDimension = Zdim; + ZDimension = Zdim; } void TargetTracker::SetNumberTT(Int_t n) { - fNTT =n; + fNTT = n; } void TargetTracker::SetDesign(Int_t Design) { - fDesign = Design; + fDesign = Design; } void TargetTracker::ConstructGeometry() { - InitMedium("vacuum"); - TGeoMedium *vacuum = gGeoManager->GetMedium("vacuum"); - - InitMedium("CarbonComposite"); - TGeoMedium *CarbonComposite = gGeoManager->GetMedium("CarbonComposite"); - - InitMedium("SciFiMat"); - TGeoMedium *SciFiMat = gGeoManager->GetMedium("SciFiMat"); - - InitMedium("Airex"); - TGeoMedium *Airex = gGeoManager->GetMedium("Airex"); - - //Target Tracker - TGeoVolume *volTarget = gGeoManager->GetVolume("volTarget"); - - TGeoBBox* TT_box = new TGeoBBox("TT_box", TTrackerX / 2, TTrackerY / 2, TTrackerZ / 2); - TGeoVolume* TT_volume = new TGeoVolume("TT", TT_box, vacuum); - TT_volume->SetLineColor(kBlue - 1); - //TT_volume->SetTransparency(1); - TT_volume->SetVisibility(1); - TT_volume->SetVisDaughters(1); - - //Support Carbon Composite - TGeoBBox* TT_support_box = new TGeoBBox("TT_support_box", TTrackerX / 2, TTrackerY / 2, support_z / 2); - TGeoVolume* TT_support_volume = new TGeoVolume("TT_support", TT_support_box, CarbonComposite); - TT_support_volume->SetLineColor(kGray - 2); - TT_support_volume->SetVisibility(1); - - //Honeycomb Airex (or Nomex) - TGeoBBox* TT_honeycomb_box = new TGeoBBox("TT_honeycomb_box", TTrackerX / 2, TTrackerY / 2, honeycomb_z / 2); - TGeoVolume* TT_honeycomb_volume = new TGeoVolume("TT_honeycomb", TT_honeycomb_box, Airex); - TT_honeycomb_volume->SetLineColor(kYellow); - TT_honeycomb_volume->SetVisibility(1); - - //SciFi planes - TGeoBBox* TT_scifi_plane_hor_box = new TGeoBBox("TT_scifi_plane_hor_box", TTrackerX / 2, TTrackerY / 2, scifimat_z / 2); - TGeoVolume* TT_scifi_plane_hor_volume = new TGeoVolume("TT_scifi_plane_hor", TT_scifi_plane_hor_box, SciFiMat); - TT_scifi_plane_hor_volume->SetVisibility(1); - - TGeoBBox* TT_scifi_plane_vert_box = new TGeoBBox("TT_scifi_plane_vert_box", TTrackerX / 2, TTrackerY / 2, scifimat_z / 2); - TGeoVolume* TT_scifi_plane_vert_volume = new TGeoVolume("TT_scifi_plane_vert", TT_scifi_plane_vert_box, SciFiMat); - TT_scifi_plane_vert_volume->SetVisibility(1); - - //SciFi mats for X and Y - TGeoBBox* TT_scifimat_hor_box = new TGeoBBox("TT_scifimat_hor_box", scifimat_hor / 2, scifimat_width / 2, scifimat_z / 2); - TGeoVolume* TT_scifimat_hor_volume = new TGeoVolume("TT_scifimat_hor", TT_scifimat_hor_box, SciFiMat); - TT_scifimat_hor_volume->SetLineColor(kCyan-9); - - TGeoBBox* TT_scifimat_vert_box = new TGeoBBox("TT_scifimat_vert_box", scifimat_width / 2, scifimat_vert / 2, scifimat_z / 2); - TGeoVolume* TT_scifimat_vert_volume = new TGeoVolume("TT_scifimat_vert", TT_scifimat_vert_box, SciFiMat); - TT_scifimat_vert_volume->SetLineColor(kGreen-7); - - //Add SciFi mat as sensitive unit - AddSensitiveVolume(TT_scifimat_hor_volume); - AddSensitiveVolume(TT_scifimat_vert_volume); - - //Creating physical volumes and multiply - for (int i = 0; i < n_hor_planes; i++){ - TT_scifi_plane_hor_volume->AddNode(TT_scifimat_hor_volume, i+1, new TGeoTranslation(0, (-(n_hor_planes-1)/2.0 + i)*scifimat_width, 0)); - } - for (int i = 0; i < n_vert_planes; i++){ - TT_scifi_plane_vert_volume->AddNode(TT_scifimat_vert_volume, 100+i+1, new TGeoTranslation((-(n_vert_planes-1)/2.0 + i)*scifimat_width, 0, 0)); - } - - TT_volume->AddNode(TT_support_volume, 0, new TGeoTranslation(0, 0, -TTrackerZ/2 + support_z/2)); - TT_volume->AddNode(TT_scifi_plane_hor_volume, 0, new TGeoTranslation(0, 0, -TTrackerZ/2 + support_z + scifimat_z/2)); - TT_volume->AddNode(TT_scifi_plane_vert_volume, 0, new TGeoTranslation(0, 0, -TTrackerZ/2 + support_z + scifimat_z + scifimat_z/2)); - TT_volume->AddNode(TT_honeycomb_volume, 0, new TGeoTranslation(0, 0, -TTrackerZ/2 + support_z + 2*scifimat_z + honeycomb_z/2)); - TT_volume->AddNode(TT_support_volume, 1, new TGeoTranslation(0, 0, -TTrackerZ/2 + support_z + 2*scifimat_z + honeycomb_z + support_z/2)); - - Double_t first_tt_position = -ZDimension / 2 + TTrackerZ / 2; - - //fNTT - number of TT walls - for (int l = 0; l < fNTT; ++l){ - volTarget->AddNode(TT_volume, 1000*(l+1), new TGeoTranslation(0, 0, first_tt_position + l * (TTrackerZ + CellWidth))); - } + InitMedium("vacuum"); + TGeoMedium* vacuum = gGeoManager->GetMedium("vacuum"); + + InitMedium("CarbonComposite"); + TGeoMedium* CarbonComposite = gGeoManager->GetMedium("CarbonComposite"); + + InitMedium("SciFiMat"); + TGeoMedium* SciFiMat = gGeoManager->GetMedium("SciFiMat"); + + InitMedium("Airex"); + TGeoMedium* Airex = gGeoManager->GetMedium("Airex"); + + // Target Tracker + TGeoVolume* volTarget = gGeoManager->GetVolume("volTarget"); + + TGeoBBox* TT_box = new TGeoBBox("TT_box", TTrackerX / 2, TTrackerY / 2, TTrackerZ / 2); + TGeoVolume* TT_volume = new TGeoVolume("TT", TT_box, vacuum); + TT_volume->SetLineColor(kBlue - 1); + // TT_volume->SetTransparency(1); + TT_volume->SetVisibility(1); + TT_volume->SetVisDaughters(1); + + // Support Carbon Composite + TGeoBBox* TT_support_box = new TGeoBBox("TT_support_box", TTrackerX / 2, TTrackerY / 2, support_z / 2); + TGeoVolume* TT_support_volume = new TGeoVolume("TT_support", TT_support_box, CarbonComposite); + TT_support_volume->SetLineColor(kGray - 2); + TT_support_volume->SetVisibility(1); + + // Honeycomb Airex (or Nomex) + TGeoBBox* TT_honeycomb_box = new TGeoBBox("TT_honeycomb_box", TTrackerX / 2, TTrackerY / 2, honeycomb_z / 2); + TGeoVolume* TT_honeycomb_volume = new TGeoVolume("TT_honeycomb", TT_honeycomb_box, Airex); + TT_honeycomb_volume->SetLineColor(kYellow); + TT_honeycomb_volume->SetVisibility(1); + + // SciFi planes + TGeoBBox* TT_scifi_plane_hor_box = + new TGeoBBox("TT_scifi_plane_hor_box", TTrackerX / 2, TTrackerY / 2, scifimat_z / 2); + TGeoVolume* TT_scifi_plane_hor_volume = new TGeoVolume("TT_scifi_plane_hor", TT_scifi_plane_hor_box, SciFiMat); + TT_scifi_plane_hor_volume->SetVisibility(1); + + TGeoBBox* TT_scifi_plane_vert_box = + new TGeoBBox("TT_scifi_plane_vert_box", TTrackerX / 2, TTrackerY / 2, scifimat_z / 2); + TGeoVolume* TT_scifi_plane_vert_volume = new TGeoVolume("TT_scifi_plane_vert", TT_scifi_plane_vert_box, SciFiMat); + TT_scifi_plane_vert_volume->SetVisibility(1); + + // SciFi mats for X and Y + TGeoBBox* TT_scifimat_hor_box = + new TGeoBBox("TT_scifimat_hor_box", scifimat_hor / 2, scifimat_width / 2, scifimat_z / 2); + TGeoVolume* TT_scifimat_hor_volume = new TGeoVolume("TT_scifimat_hor", TT_scifimat_hor_box, SciFiMat); + TT_scifimat_hor_volume->SetLineColor(kCyan - 9); + + TGeoBBox* TT_scifimat_vert_box = + new TGeoBBox("TT_scifimat_vert_box", scifimat_width / 2, scifimat_vert / 2, scifimat_z / 2); + TGeoVolume* TT_scifimat_vert_volume = new TGeoVolume("TT_scifimat_vert", TT_scifimat_vert_box, SciFiMat); + TT_scifimat_vert_volume->SetLineColor(kGreen - 7); + + // Add SciFi mat as sensitive unit + AddSensitiveVolume(TT_scifimat_hor_volume); + AddSensitiveVolume(TT_scifimat_vert_volume); + + // Creating physical volumes and multiply + for (int i = 0; i < n_hor_planes; i++) { + TT_scifi_plane_hor_volume->AddNode( + TT_scifimat_hor_volume, i + 1, new TGeoTranslation(0, (-(n_hor_planes - 1) / 2.0 + i) * scifimat_width, 0)); + } + for (int i = 0; i < n_vert_planes; i++) { + TT_scifi_plane_vert_volume->AddNode( + TT_scifimat_vert_volume, + 100 + i + 1, + new TGeoTranslation((-(n_vert_planes - 1) / 2.0 + i) * scifimat_width, 0, 0)); + } + TT_volume->AddNode(TT_support_volume, 0, new TGeoTranslation(0, 0, -TTrackerZ / 2 + support_z / 2)); + TT_volume->AddNode( + TT_scifi_plane_hor_volume, 0, new TGeoTranslation(0, 0, -TTrackerZ / 2 + support_z + scifimat_z / 2)); + TT_volume->AddNode(TT_scifi_plane_vert_volume, + 0, + new TGeoTranslation(0, 0, -TTrackerZ / 2 + support_z + scifimat_z + scifimat_z / 2)); + TT_volume->AddNode(TT_honeycomb_volume, + 0, + new TGeoTranslation(0, 0, -TTrackerZ / 2 + support_z + 2 * scifimat_z + honeycomb_z / 2)); + TT_volume->AddNode( + TT_support_volume, + 1, + new TGeoTranslation(0, 0, -TTrackerZ / 2 + support_z + 2 * scifimat_z + honeycomb_z + support_z / 2)); + + Double_t first_tt_position = -ZDimension / 2 + TTrackerZ / 2; + + // fNTT - number of TT walls + for (int l = 0; l < fNTT; ++l) { + volTarget->AddNode( + TT_volume, 1000 * (l + 1), new TGeoTranslation(0, 0, first_tt_position + l * (TTrackerZ + CellWidth))); + } } - Bool_t TargetTracker::ProcessHits(FairVolume* vol) { - /** This method is called from the MC stepping */ - //Set parameters at entrance of volume. Reset ELoss. - if ( gMC->IsTrackEntering() ) { - fELoss = 0.; - fTime = gMC->TrackTime() * 1.0e09; - fLength = gMC->TrackLength(); - gMC->TrackPosition(fPos); - gMC->TrackMomentum(fMom); - } - // Sum energy loss for all steps in the active volume - fELoss += gMC->Edep(); - - // Create muonPoint at exit of active volume - if (gMC->IsTrackExiting() || - gMC->IsTrackStop() || - gMC->IsTrackDisappeared() ){ - if (fELoss == 0. ) { return kFALSE; } - TParticle* p=gMC->GetStack()->GetCurrentTrack(); - Int_t pdgCode = p->GetPdgCode(); - fTrackID = gMC->GetStack()->GetCurrentTrackNumber(); - - gMC->CurrentVolID(fVolumeID); - Int_t detID = fVolumeID; - Int_t TTstationID; - gMC->CurrentVolOffID(2, TTstationID); - fVolumeID = TTstationID + detID; - - TLorentzVector Pos; - gMC->TrackPosition(Pos); - Double_t xmean = (fPos.X()+Pos.X())/2. ; - Double_t ymean = (fPos.Y()+Pos.Y())/2. ; - Double_t zmean = (fPos.Z()+Pos.Z())/2. ; - - AddHit(fTrackID, fVolumeID, TVector3(xmean, ymean, zmean), - TVector3(fMom.Px(), fMom.Py(), fMom.Pz()), - fTime, fLength, fELoss, pdgCode); - - // Increment number of muon det points in TParticle - ShipStack* stack = (ShipStack*) gMC->GetStack(); - stack->AddPoint(ktauTT); - } - - return kTRUE; -} + /** This method is called from the MC stepping */ + // Set parameters at entrance of volume. Reset ELoss. + if (gMC->IsTrackEntering()) { + fELoss = 0.; + fTime = gMC->TrackTime() * 1.0e09; + fLength = gMC->TrackLength(); + gMC->TrackPosition(fPos); + gMC->TrackMomentum(fMom); + } + // Sum energy loss for all steps in the active volume + fELoss += gMC->Edep(); + + // Create muonPoint at exit of active volume + if (gMC->IsTrackExiting() || gMC->IsTrackStop() || gMC->IsTrackDisappeared()) { + if (fELoss == 0.) { + return kFALSE; + } + TParticle* p = gMC->GetStack()->GetCurrentTrack(); + Int_t pdgCode = p->GetPdgCode(); + fTrackID = gMC->GetStack()->GetCurrentTrackNumber(); + + gMC->CurrentVolID(fVolumeID); + Int_t detID = fVolumeID; + Int_t TTstationID; + gMC->CurrentVolOffID(2, TTstationID); + fVolumeID = TTstationID + detID; + + TLorentzVector Pos; + gMC->TrackPosition(Pos); + Double_t xmean = (fPos.X() + Pos.X()) / 2.; + Double_t ymean = (fPos.Y() + Pos.Y()) / 2.; + Double_t zmean = (fPos.Z() + Pos.Z()) / 2.; + + AddHit(fTrackID, + fVolumeID, + TVector3(xmean, ymean, zmean), + TVector3(fMom.Px(), fMom.Py(), fMom.Pz()), + fTime, + fLength, + fELoss, + pdgCode); + + // Increment number of muon det points in TParticle + ShipStack* stack = (ShipStack*)gMC->GetStack(); + stack->AddPoint(ktauTT); + } + return kTRUE; +} -void TargetTracker::DecodeTTID(Int_t detID, Int_t &NTT, int &nplane, Bool_t &ishor) +void TargetTracker::DecodeTTID(Int_t detID, Int_t& NTT, int& nplane, Bool_t& ishor) { - NTT = detID/1000; - int idir = (detID - NTT*1000)/100; + NTT = detID / 1000; + int idir = (detID - NTT * 1000) / 100; - if (idir == 1) ishor = kFALSE; - else if (idir == 0) ishor = kTRUE; + if (idir == 1) + ishor = kFALSE; + else if (idir == 0) + ishor = kTRUE; - nplane = (detID - NTT*1000 - idir*100); + nplane = (detID - NTT * 1000 - idir * 100); } - void TargetTracker::EndOfEvent() { fTTPointCollection->Clear(); } - void TargetTracker::Register() { @@ -327,14 +346,16 @@ void TargetTracker::Register() only during the simulation. */ - FairRootManager::Instance()->Register("TTPoint", "TargetTracker", - fTTPointCollection, kTRUE); + FairRootManager::Instance()->Register("TTPoint", "TargetTracker", fTTPointCollection, kTRUE); } TClonesArray* TargetTracker::GetCollection(Int_t iColl) const { - if (iColl == 0) { return fTTPointCollection; } - else { return NULL; } + if (iColl == 0) { + return fTTPointCollection; + } else { + return NULL; + } } void TargetTracker::Reset() @@ -342,15 +363,17 @@ void TargetTracker::Reset() fTTPointCollection->Clear(); } - -TTPoint* TargetTracker::AddHit(Int_t trackID,Int_t detID, - TVector3 pos, TVector3 mom, - Double_t time, Double_t length, - Double_t eLoss, Int_t pdgCode) +TTPoint* TargetTracker::AddHit(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t time, + Double_t length, + Double_t eLoss, + Int_t pdgCode) { TClonesArray& clref = *fTTPointCollection; Int_t size = clref.GetEntriesFast(); - //cout << "brick hit called"<< pos.z()< // for string - -#include "TVector3.h" +#include "FairModule.h" // for FairModule +#include "Rtypes.h" // for ShipMuonShield::Class, Bool_t, etc #include "TLorentzVector.h" +#include "TVector3.h" + +#include // for string class TTPoint; class FairVolume; @@ -25,89 +23,97 @@ class TClonesArray; class TargetTracker : public FairDetector { -public: - TargetTracker(const char* name, Double_t TTX, Double_t TTY, Double_t TTZ, Bool_t Active, const char* Title = "TargetTrackers"); + public: + TargetTracker(const char* name, + Double_t TTX, + Double_t TTY, + Double_t TTZ, + Bool_t Active, + const char* Title = "TargetTrackers"); TargetTracker(); virtual ~TargetTracker(); void ConstructGeometry(); - void SetSciFiParam(Double_t scifimat_width_, Double_t scifimat_hor_, Double_t scifimat_vert_, - Double_t scifimat_z_, Double_t support_z_, Double_t honeycomb_z_); + void SetSciFiParam(Double_t scifimat_width_, + Double_t scifimat_hor_, + Double_t scifimat_vert_, + Double_t scifimat_z_, + Double_t support_z_, + Double_t honeycomb_z_); void SetNumberSciFi(Int_t n_hor_planes_, Int_t n_vert_planes_); void SetTargetTrackerParam(Double_t TTX, Double_t TTY, Double_t TTZ); void SetBrickParam(Double_t CellW); void SetTotZDimension(Double_t Zdim); - void DecodeTTID(Int_t detID, Int_t &NTT, int &nplane, Bool_t &ishor); + void DecodeTTID(Int_t detID, Int_t& NTT, int& nplane, Bool_t& ishor); void SetNumberTT(Int_t n); void SetDesign(Int_t Design); - /** Initialization of the detector is done here */ virtual void Initialize(); /** this method is called for each step during simulation * (see FairMCApplication::Stepping()) */ - virtual Bool_t ProcessHits( FairVolume* v=0); + virtual Bool_t ProcessHits(FairVolume* v = 0); /** Registers the produced collections in FAIRRootManager. */ - virtual void Register(); + virtual void Register(); /** Gets the produced collections */ - virtual TClonesArray* GetCollection(Int_t iColl) const ; + virtual TClonesArray* GetCollection(Int_t iColl) const; /** has to be called after each event to reset the containers */ - virtual void Reset(); + virtual void Reset(); /** This method is an example of how to add your own point * of type muonPoint to the clones array */ - TTPoint* AddHit(Int_t trackID, Int_t detID, - TVector3 pos, TVector3 mom, - Double_t time, Double_t length, - Double_t eLoss, Int_t pdgCode); + TTPoint* AddHit(Int_t trackID, + Int_t detID, + TVector3 pos, + TVector3 mom, + Double_t time, + Double_t length, + Double_t eLoss, + Int_t pdgCode); /** The following methods can be implemented if you need to make * any optional action in your detector during the transport. */ - virtual void CopyClones( TClonesArray* cl1, TClonesArray* cl2 , - Int_t offset) {;} - virtual void SetSpecialPhysicsCuts() {;} - virtual void EndOfEvent(); - virtual void FinishPrimary() {;} - virtual void FinishRun() {;} - virtual void BeginPrimary() {;} - virtual void PostTrack() {;} - virtual void PreTrack() {;} - virtual void BeginEvent() {;} - + virtual void CopyClones(TClonesArray* cl1, TClonesArray* cl2, Int_t offset) { ; } + virtual void SetSpecialPhysicsCuts() { ; } + virtual void EndOfEvent(); + virtual void FinishPrimary() { ; } + virtual void FinishRun() { ; } + virtual void BeginPrimary() { ; } + virtual void PostTrack() { ; } + virtual void PreTrack() { ; } + virtual void BeginEvent() { ; } TargetTracker(const TargetTracker&); TargetTracker& operator=(const TargetTracker&); - ClassDef(TargetTracker,4); - - private: + ClassDef(TargetTracker, 4); + private: /** Track information to be stored until the track leaves the active volume. */ - Int_t fTrackID; //! track index - Int_t fVolumeID; //! volume id - TLorentzVector fPos; //! position at entrance - TLorentzVector fMom; //! momentum at entrance - Double32_t fTime; //! time - Double32_t fLength; //! length - Double32_t fELoss; //! energy loss + Int_t fTrackID; //! track index + Int_t fVolumeID; //! volume id + TLorentzVector fPos; //! position at entrance + TLorentzVector fMom; //! momentum at entrance + Double32_t fTime; //! time + Double32_t fLength; //! length + Double32_t fELoss; //! energy loss /** container for data points */ - TClonesArray* fTTPointCollection; - -protected: + TClonesArray* fTTPointCollection; + protected: Double_t TTrackerX; Double_t TTrackerY; Double_t TTrackerZ; @@ -121,16 +127,14 @@ class TargetTracker : public FairDetector Int_t n_hor_planes; Int_t n_vert_planes; - Double_t CellWidth; //dimension of the cell containing brick and CES - Double_t ZDimension; //Dimension of the TTs+bricks total volume + Double_t CellWidth; // dimension of the cell containing brick and CES + Double_t ZDimension; // Dimension of the TTs+bricks total volume - Int_t fNTT; //number of TT + Int_t fNTT; // number of TT Int_t fDesign; - Int_t InitMedium(const char* name); - }; #endif diff --git a/passive/CMakeLists.txt b/passive/CMakeLists.txt index 025f58df26..9b325a3737 100644 --- a/passive/CMakeLists.txt +++ b/passive/CMakeLists.txt @@ -1,37 +1,31 @@ # Create a library called "libPassive" which includes the source files given in -# the array . -# The extension is already found. Any number of sources could be listed here. +# the array . The extension is already found. Any number of sources could be +# listed here. -set(INCLUDE_DIRECTORIES -${CMAKE_SOURCE_DIR}/passive -${VMC_INCLUDE_DIRS} -) +set(INCLUDE_DIRECTORIES ${CMAKE_SOURCE_DIR}/passive ${VMC_INCLUDE_DIRS}) -include_directories(${INCLUDE_DIRECTORIES} ${GEANT4_INCLUDE_DIR} ${FAIRROOT_INCLUDE_DIR}) +include_directories(${INCLUDE_DIRECTORIES} ${GEANT4_INCLUDE_DIR} + ${FAIRROOT_INCLUDE_DIR}) include_directories(SYSTEM ${SYSTEM_INCLUDE_DIRECTORIES}) -Message(STATUS "include directories ${GEANT4_INCLUDE_DIR}") -set(LINK_DIRECTORIES -${ROOT_LIBRARY_DIR} -${FAIRROOT_LIBRARY_DIR} -) +message(STATUS "include directories ${GEANT4_INCLUDE_DIR}") +set(LINK_DIRECTORIES ${ROOT_LIBRARY_DIR} ${FAIRROOT_LIBRARY_DIR}) -link_directories( ${LINK_DIRECTORIES}) +link_directories(${LINK_DIRECTORIES}) set(SRCS -ShipCave.cxx -ShipGeoCave.cxx -ShipMagnet.cxx -ShipChamber.cxx -ShipTargetStation.cxx -ShipMuonShield.cxx -ShipPassiveContFact.cxx -ShipTAUMagneticSpectrometer.cxx -ShipGoliath.cxx -) + ShipCave.cxx + ShipGeoCave.cxx + ShipMagnet.cxx + ShipChamber.cxx + ShipTargetStation.cxx + ShipMuonShield.cxx + ShipPassiveContFact.cxx + ShipTAUMagneticSpectrometer.cxx + ShipGoliath.cxx) -Set(HEADERS ) -Set(LINKDEF PassiveLinkDef.h) -Set(LIBRARY_NAME ShipPassive) +set(HEADERS) +set(LINKDEF PassiveLinkDef.h) +set(LIBRARY_NAME ShipPassive) set(DEPENDENCIES Base GeoBase ParBase Geom Core FairLogger::FairLogger) -GENERATE_LIBRARY() +generate_library() diff --git a/passive/ShipCave.h b/passive/ShipCave.h index e508076afc..2a781b84bd 100644 --- a/passive/ShipCave.h +++ b/passive/ShipCave.h @@ -1,22 +1,20 @@ #ifndef Cave_H #define Cave_H -#include "FairModule.h" // for FairModule - -#include "Rtypes.h" // for ShipCave::Class, ClassDef, etc +#include "FairModule.h" // for FairModule +#include "Rtypes.h" // for ShipCave::Class, ClassDef, etc class ShipCave : public FairModule { public: - ShipCave(const char* name, const char* Title="Exp Cave"); + ShipCave(const char* name, const char* Title = "Exp Cave"); ShipCave(); virtual ~ShipCave(); virtual void ConstructGeometry(); - private: Double_t world[3]; - ClassDef(ShipCave,1) //PNDCaveSD + ClassDef(ShipCave, 1) // PNDCaveSD }; -#endif //Cave_H +#endif // Cave_H diff --git a/passive/ShipChamber.cxx b/passive/ShipChamber.cxx index 484c4a98ab..3d59b789a4 100644 --- a/passive/ShipChamber.cxx +++ b/passive/ShipChamber.cxx @@ -1,94 +1,83 @@ #include "ShipChamber.h" -#include "TGeoManager.h" -#include "FairRun.h" // for FairRun -#include "FairRuntimeDb.h" // for FairRuntimeDb -#include // for ostream -#include "TList.h" // for TListIter, TList (ptr only) -#include "TObjArray.h" // for TObjArray -#include "TString.h" // for TString +#include "FairGeoBuilder.h" +#include "FairGeoMedia.h" +#include "FairRun.h" // for FairRun +#include "FairRuntimeDb.h" // for FairRuntimeDb #include "TGeoBBox.h" #include "TGeoCompositeShape.h" -#include "FairGeoMedia.h" -#include "FairGeoBuilder.h" -#include "TGeoTube.h" +#include "TGeoManager.h" #include "TGeoMaterial.h" #include "TGeoMedium.h" -#include // for NULL -#include // for operator<<, basic_ostream, etc - +#include "TGeoTube.h" +#include "TList.h" // for TListIter, TList (ptr only) +#include "TObjArray.h" // for TObjArray +#include "TString.h" // for TString +#include // for ostream +#include // for operator<<, basic_ostream, etc +#include // for NULL -ShipChamber::~ShipChamber() -{ -} +ShipChamber::~ShipChamber() {} ShipChamber::ShipChamber() - : FairModule("ShipChamber", "") -{ -} + : FairModule("ShipChamber", "") +{} ShipChamber::ShipChamber(const char* name, const char* Title) - : FairModule(name ,Title) -{ -} + : FairModule(name, Title) +{} // ----- Private method InitMedium Int_t ShipChamber::InitMedium(const char* name) { - static FairGeoLoader *geoLoad=FairGeoLoader::Instance(); - static FairGeoInterface *geoFace=geoLoad->getGeoInterface(); - static FairGeoMedia *media=geoFace->getMedia(); - static FairGeoBuilder *geoBuild=geoLoad->getGeoBuilder(); - - FairGeoMedium *ShipMedium=media->getMedium(name); - - if (!ShipMedium) - { - Fatal("InitMedium","Material %s not defined in media file.", name); - return -1111; - } - TGeoMedium* medium=gGeoManager->GetMedium(name); - if (medium!=NULL) - return ShipMedium->getMediumIndex(); - return geoBuild->createMedium(ShipMedium); + static FairGeoLoader* geoLoad = FairGeoLoader::Instance(); + static FairGeoInterface* geoFace = geoLoad->getGeoInterface(); + static FairGeoMedia* media = geoFace->getMedia(); + static FairGeoBuilder* geoBuild = geoLoad->getGeoBuilder(); + + FairGeoMedium* ShipMedium = media->getMedium(name); + + if (!ShipMedium) { + Fatal("InitMedium", "Material %s not defined in media file.", name); + return -1111; + } + TGeoMedium* medium = gGeoManager->GetMedium(name); + if (medium != NULL) + return ShipMedium->getMediumIndex(); + return geoBuild->createMedium(ShipMedium); } void ShipChamber::ConstructGeometry() { - TGeoVolume *top=gGeoManager->GetTopVolume(); + TGeoVolume* top = gGeoManager->GetTopVolume(); InitMedium("Aluminum"); - TGeoMedium *Al =gGeoManager->GetMedium("Aluminum"); + TGeoMedium* Al = gGeoManager->GetMedium("Aluminum"); // first part of vacuum chamber up to veto station - TGeoVolume *tub1 = gGeoManager->MakeTube("tub1", Al, 245, 250, 50); - tub1->SetLineColor(18); // silver/gray + TGeoVolume* tub1 = gGeoManager->MakeTube("tub1", Al, 245, 250, 50); + tub1->SetLineColor(18); // silver/gray top->AddNode(tub1, 1, new TGeoTranslation(0, 0, -2450)); - // second part of vacuum chamber up to first tracking station - TGeoVolume *tub2 = gGeoManager->MakeTube("tub2", Al, 245, 250, 3880/2); // 1890 + TGeoVolume* tub2 = gGeoManager->MakeTube("tub2", Al, 245, 250, 3880 / 2); // 1890 tub2->SetLineColor(18); top->AddNode(tub2, 1, new TGeoTranslation(0, 0, -440)); - // third part of vacuum chamber up to second tracking station - TGeoVolume *tub3 = gGeoManager->MakeTube("tub3", Al, 245, 250, 80); + TGeoVolume* tub3 = gGeoManager->MakeTube("tub3", Al, 245, 250, 80); tub3->SetLineColor(18); top->AddNode(tub3, 1, new TGeoTranslation(0, 0, 1620)); // fourth part of vacuum chamber up to third tracking station and being covered by magnet - TGeoVolume *tub4 = gGeoManager->MakeTube("tub4", Al, 245, 250, 200); + TGeoVolume* tub4 = gGeoManager->MakeTube("tub4", Al, 245, 250, 200); tub4->SetLineColor(18); top->AddNode(tub4, 1, new TGeoTranslation(0, 0, 1940)); // fifth part of vacuum chamber up to fourth tracking station - TGeoVolume *tub5 = gGeoManager->MakeTube("tub5", Al, 245, 250, 90); + TGeoVolume* tub5 = gGeoManager->MakeTube("tub5", Al, 245, 250, 90); tub5->SetLineColor(18); top->AddNode(tub5, 1, new TGeoTranslation(0, 0, 2270)); // sixth part of vacuum chamber up to muon detector - TGeoVolume *tub6 = gGeoManager->MakeTube("tub6", Al, 245, 250, 20); + TGeoVolume* tub6 = gGeoManager->MakeTube("tub6", Al, 245, 250, 20); tub6->SetLineColor(18); top->AddNode(tub6, 1, new TGeoTranslation(0, 0, 2540)); - - - } diff --git a/passive/ShipChamber.h b/passive/ShipChamber.h index 4f95d5a5fa..9331f1d78f 100644 --- a/passive/ShipChamber.h +++ b/passive/ShipChamber.h @@ -1,22 +1,19 @@ #ifndef Chamber_H #define Chamber_H -#include "FairModule.h" // for FairModule +#include "FairModule.h" // for FairModule +#include "Rtypes.h" // for ShipChamber::Class, Bool_t, etc -#include "Rtypes.h" // for ShipChamber::Class, Bool_t, etc - -#include // for string +#include // for string class ShipChamber : public FairModule { public: - ShipChamber(const char* name, const char* Title="ShipChamber"); + ShipChamber(const char* name, const char* Title = "ShipChamber"); ShipChamber(); virtual ~ShipChamber(); void ConstructGeometry(); - ClassDef(ShipChamber,1) - Int_t InitMedium(const char* name); - + ClassDef(ShipChamber, 1) Int_t InitMedium(const char* name); }; -#endif //Chamber_H +#endif // Chamber_H diff --git a/passive/ShipGeoCave.cxx b/passive/ShipGeoCave.cxx index 46473eba14..7bb330f8b3 100644 --- a/passive/ShipGeoCave.cxx +++ b/passive/ShipGeoCave.cxx @@ -7,107 +7,119 @@ #include "ShipGeoCave.h" -#include "FairGeoBasicShape.h" // for FairGeoBasicShape -#include "FairGeoMedia.h" // for FairGeoMedia -#include "FairGeoMedium.h" // for FairGeoMedium -#include "FairGeoNode.h" // for FairGeoNode, etc -#include "FairGeoShapes.h" // for FairGeoShapes +#include "FairGeoBasicShape.h" // for FairGeoBasicShape +#include "FairGeoMedia.h" // for FairGeoMedia +#include "FairGeoMedium.h" // for FairGeoMedium +#include "FairGeoNode.h" // for FairGeoNode, etc +#include "FairGeoShapes.h" // for FairGeoShapes +#include "TList.h" // for TList -#include "TList.h" // for TList - -#include // for strcmp -#include // for cout +#include // for cout +#include // for strcmp using namespace std; ShipGeoCave::ShipGeoCave() - : FairGeoSet(), - name("cave") + : FairGeoSet() + , name("cave") { - // Constructor - fName="cave"; - name="cave"; - maxModules=1; + // Constructor + fName = "cave"; + name = "cave"; + maxModules = 1; } -Bool_t ShipGeoCave::read(fstream& fin,FairGeoMedia* media) +Bool_t ShipGeoCave::read(fstream& fin, FairGeoMedia* media) { - // Reads the geometry from file - if (!media) { return kFALSE; } - const Int_t maxbuf=256; - char buf[maxbuf]; - FairGeoNode* volu=0; - FairGeoMedium* medium; - Bool_t rc=kTRUE; - do { - fin.getline(buf,maxbuf); - if (buf[0]!='\0' && buf[0]!='/' && !fin.eof()) { - if (strcmp(buf,name)==0) { - volu=new FairGeoNode; - volu->SetName(buf); - volu->setVolumeType(kFairGeoTopNode); - volu->setActive(); - fin.getline(buf,maxbuf); - TString shape(buf); - FairGeoBasicShape* sh=pShapes->selectShape(shape); - if (sh) { volu->setShape(sh); } - else { rc=kFALSE; } - fin.getline(buf,maxbuf); - medium=media->getMedium(buf); - if (!medium) { - medium=new FairGeoMedium(); - media->addMedium(medium); + // Reads the geometry from file + if (!media) { + return kFALSE; + } + const Int_t maxbuf = 256; + char buf[maxbuf]; + FairGeoNode* volu = 0; + FairGeoMedium* medium; + Bool_t rc = kTRUE; + do { + fin.getline(buf, maxbuf); + if (buf[0] != '\0' && buf[0] != '/' && !fin.eof()) { + if (strcmp(buf, name) == 0) { + volu = new FairGeoNode; + volu->SetName(buf); + volu->setVolumeType(kFairGeoTopNode); + volu->setActive(); + fin.getline(buf, maxbuf); + TString shape(buf); + FairGeoBasicShape* sh = pShapes->selectShape(shape); + if (sh) { + volu->setShape(sh); + } else { + rc = kFALSE; + } + fin.getline(buf, maxbuf); + medium = media->getMedium(buf); + if (!medium) { + medium = new FairGeoMedium(); + media->addMedium(medium); + } + volu->setMedium(medium); + Int_t n = 0; + if (sh) { + n = sh->readPoints(&fin, volu); + } + if (n <= 0) { + rc = kFALSE; + } + } else { + rc = kFALSE; + } } - volu->setMedium(medium); - Int_t n=0; - if (sh) { n=sh->readPoints(&fin,volu); } - if (n<=0) { rc=kFALSE; } - } else { rc=kFALSE; } + } while (rc && !volu && !fin.eof()); + if (volu && rc) { + volumes->Add(volu); + masterNodes->Add(new FairGeoNode(*volu)); + } else { + delete volu; + volu = 0; + rc = kFALSE; } - } while (rc && !volu && !fin.eof()); - if (volu && rc) { - volumes->Add(volu); - masterNodes->Add(new FairGeoNode(*volu)); - } else { - delete volu; - volu=0; - rc=kFALSE; - } - return rc; + return rc; } void ShipGeoCave::addRefNodes() { - // Adds the reference node - FairGeoNode* volu=getVolume(name); - if (volu) { masterNodes->Add(new FairGeoNode(*volu)); } + // Adds the reference node + FairGeoNode* volu = getVolume(name); + if (volu) { + masterNodes->Add(new FairGeoNode(*volu)); + } } void ShipGeoCave::write(fstream& fout) { - // Writes the geometry to file - fout.setf(ios::fixed,ios::floatfield); - FairGeoNode* volu=getVolume(name); - if (volu) { - FairGeoBasicShape* sh=volu->getShapePointer(); - FairGeoMedium* med=volu->getMedium(); - if (sh&&med) { - fout<GetName()<<'\n'<GetName()<<'\n'<GetName()<<'\n'; - sh->writePoints(&fout,volu); + // Writes the geometry to file + fout.setf(ios::fixed, ios::floatfield); + FairGeoNode* volu = getVolume(name); + if (volu) { + FairGeoBasicShape* sh = volu->getShapePointer(); + FairGeoMedium* med = volu->getMedium(); + if (sh && med) { + fout << volu->GetName() << '\n' << sh->GetName() << '\n' << med->GetName() << '\n'; + sh->writePoints(&fout, volu); + } } - } } void ShipGeoCave::print() { - // Prints the geometry - FairGeoNode* volu=getVolume(name); - if (volu) { - FairGeoBasicShape* sh=volu->getShapePointer(); - FairGeoMedium* med=volu->getMedium(); - if (sh&&med) { - cout<GetName()<<'\n'<GetName()<<'\n'<GetName()<<'\n'; - sh->printPoints(volu); + // Prints the geometry + FairGeoNode* volu = getVolume(name); + if (volu) { + FairGeoBasicShape* sh = volu->getShapePointer(); + FairGeoMedium* med = volu->getMedium(); + if (sh && med) { + cout << volu->GetName() << '\n' << sh->GetName() << '\n' << med->GetName() << '\n'; + sh->printPoints(volu); + } } - } } diff --git a/passive/ShipGeoCave.h b/passive/ShipGeoCave.h index 18331078f5..951079b2c4 100644 --- a/passive/ShipGeoCave.h +++ b/passive/ShipGeoCave.h @@ -1,29 +1,29 @@ #ifndef SNOOPYGEOCAVE_H #define SNOOPYGEOCAVE_H -#include "FairGeoSet.h" // for FairGeoSet +#include "FairGeoSet.h" // for FairGeoSet +#include "Rtypes.h" // for ShipGeoCave::Class, Bool_t, etc +#include "TString.h" // for TString -#include // for fstream -#include "Rtypes.h" // for ShipGeoCave::Class, Bool_t, etc -#include "TString.h" // for TString - -#include // for fstream +#include // for fstream +#include // for fstream class FairGeoMedia; -class ShipGeoCave : public FairGeoSet +class ShipGeoCave : public FairGeoSet { protected: TString name; + public: ShipGeoCave(); ~ShipGeoCave() {} - const char* getModuleName(Int_t) {return name.Data();} - Bool_t read(std::fstream&,FairGeoMedia*); + const char* getModuleName(Int_t) { return name.Data(); } + Bool_t read(std::fstream&, FairGeoMedia*); void addRefNodes(); void write(std::fstream&); void print(); - ClassDef(ShipGeoCave,0) // Class for the geometry of CAVE + ClassDef(ShipGeoCave, 0) // Class for the geometry of CAVE }; -#endif /* !PNDGEOCAVE_H */ +#endif /* !PNDGEOCAVE_H */ diff --git a/passive/ShipGoliath.cxx b/passive/ShipGoliath.cxx index d88249e72d..d8bf64e720 100644 --- a/passive/ShipGoliath.cxx +++ b/passive/ShipGoliath.cxx @@ -1,39 +1,42 @@ #include "ShipGoliath.h" +#include "FairRun.h" // for FairRun +#include "FairRuntimeDb.h" // for FairRuntimeDb #include "TGeoManager.h" -#include "FairRun.h" // for FairRun -#include "FairRuntimeDb.h" // for FairRuntimeDb -//#include "FairGeoMedia.h" -//#include "FairGeoBuilder.h" - -#include // for ostream -#include "TList.h" // for TListIter, TList (ptr only) -#include "TObjArray.h" // for TObjArray -#include "TString.h" // for TString -#include "TGeoBBox.h" -#include "TGeoTrd1.h" +// #include "FairGeoMedia.h" +// #include "FairGeoBuilder.h" + #include "TGeoArb8.h" +#include "TGeoBBox.h" #include "TGeoCompositeShape.h" -#include "TGeoTube.h" -#include "TGeoMaterial.h" #include "TGeoElement.h" +#include "TGeoMaterial.h" #include "TGeoMedium.h" -#include // for NULL -#include // for operator<<, basic_ostream, etc +#include "TGeoTrd1.h" +#include "TGeoTube.h" +#include "TList.h" // for TListIter, TList (ptr only) +#include "TObjArray.h" // for TObjArray +#include "TString.h" // for TString + +#include // for ostream +#include // for operator<<, basic_ostream, etc +#include // for NULL using namespace std; -ShipGoliath::~ShipGoliath() -{ -} +ShipGoliath::~ShipGoliath() {} ShipGoliath::ShipGoliath() - : FairModule("ShipGoliath", "") -{ -} - -ShipGoliath::ShipGoliath(const char* name, const Double_t zC, const Double_t LS, const Double_t TS, const Double_t GapTS, const char* Title) - : FairModule(name ,Title) + : FairModule("ShipGoliath", "") +{} + +ShipGoliath::ShipGoliath(const char* name, + const Double_t zC, + const Double_t LS, + const Double_t TS, + const Double_t GapTS, + const char* Title) + : FairModule(name, Title) { zCenter = zC; LongitudinalSize = LS; @@ -43,76 +46,68 @@ ShipGoliath::ShipGoliath(const char* name, const Double_t zC, const Double_t LS, void ShipGoliath::ConstructGeometry() { - Double_t side1 = TransversalSize, side2 = LongitudinalSize; //side1 = short side, side2 = long side of the top part - Double_t base1 = 135, base2 = 78; //basis of the trapezoid - Double_t side3 = 33, side4 = 90, side5 = 125; //Sides of the columns - Double_t height = 180; //Distane between the lower and upper surface + Double_t side1 = TransversalSize, + side2 = LongitudinalSize; // side1 = short side, side2 = long side of the top part + Double_t base1 = 135, base2 = 78; // basis of the trapezoid + Double_t side3 = 33, side4 = 90, side5 = 125; // Sides of the columns + Double_t height = 180; // Distane between the lower and upper surface cout << zCenter << endl; - TGeoVolume *top=gGeoManager->GetTopVolume(); - TGeoMedium *Fe = gGeoManager->GetMedium("iron"); + TGeoVolume* top = gGeoManager->GetTopVolume(); + TGeoMedium* Fe = gGeoManager->GetMedium("iron"); // //******* UPPER AND LOWER BASE ******* // - TGeoBBox *TopS = new TGeoBBox(180,57/2,225); - TGeoVolume *volTopS = new TGeoVolume("volTopS",TopS,Fe); + TGeoBBox* TopS = new TGeoBBox(180, 57 / 2, 225); + TGeoVolume* volTopS = new TGeoVolume("volTopS", TopS, Fe); volTopS->SetLineColor(kRed); - //volTopS->SetTransparency(7); - - top->AddNode(volTopS,1,new TGeoTranslation(0, 126, zCenter)); //upper part - top->AddNode(volTopS,2,new TGeoTranslation(0, -111, zCenter)); //lower part + // volTopS->SetTransparency(7); + top->AddNode(volTopS, 1, new TGeoTranslation(0, 126, zCenter)); // upper part + top->AddNode(volTopS, 2, new TGeoTranslation(0, -111, zCenter)); // lower part //******************************************************************* //**************************** MAGNETS ****************************** //******************************************************************* - - - TGeoRotation *r1 = new TGeoRotation(); - r1->SetAngles(0,90,0); - TGeoCombiTrans t(0, 75, zCenter,r1); + TGeoRotation* r1 = new TGeoRotation(); + r1->SetAngles(0, 90, 0); + TGeoCombiTrans t(0, 75, zCenter, r1); t.Print(); - TGeoHMatrix *m = new TGeoHMatrix(t); - - + TGeoHMatrix* m = new TGeoHMatrix(t); - TGeoTube *magnetUp = new TGeoTube(side4,160,22.5); - TGeoVolume *volmagnetUp = new TGeoVolume("volmagnetUp",magnetUp,Fe); + TGeoTube* magnetUp = new TGeoTube(side4, 160, 22.5); + TGeoVolume* volmagnetUp = new TGeoVolume("volmagnetUp", magnetUp, Fe); volmagnetUp->SetLineColor(kGreen); - top->AddNode(volmagnetUp,1,m); //upper part + top->AddNode(volmagnetUp, 1, m); // upper part + TGeoCombiTrans t1(0, -67.5, zCenter, r1); + TGeoHMatrix* m1 = new TGeoHMatrix(t1); - TGeoCombiTrans t1(0, -67.5, zCenter,r1); - TGeoHMatrix *m1 = new TGeoHMatrix(t1); - - - TGeoTube *magnetDown = new TGeoTube(side4,160,15); - TGeoVolume *volmagnetDown = new TGeoVolume("volmagnetDown",magnetDown,Fe); + TGeoTube* magnetDown = new TGeoTube(side4, 160, 15); + TGeoVolume* volmagnetDown = new TGeoVolume("volmagnetDown", magnetDown, Fe); volmagnetDown->SetLineColor(kGreen); - top->AddNode(volmagnetDown,1,m1); //lower part - + top->AddNode(volmagnetDown, 1, m1); // lower part //******************************************************************* //********************* LATERAL SURFACES **************************** //******************************************************************* - //***** SIDE Left Front **** - //LONGER RECTANGLE - TGeoBBox *LateralS1 = new TGeoBBox("LateralS1",16.5,45/2,67.5); - TGeoTranslation *tr1 = new TGeoTranslation(-side1/2 +side3/2, 75, zCenter- side2/2 +base1/2); - TGeoVolume *volLateralS1 = new TGeoVolume("volLateralS1",LateralS1,Fe); + // LONGER RECTANGLE + TGeoBBox* LateralS1 = new TGeoBBox("LateralS1", 16.5, 45 / 2, 67.5); + TGeoTranslation* tr1 = new TGeoTranslation(-side1 / 2 + side3 / 2, 75, zCenter - side2 / 2 + base1 / 2); + TGeoVolume* volLateralS1 = new TGeoVolume("volLateralS1", LateralS1, Fe); volLateralS1->SetLineColor(kRed); top->AddNode(volLateralS1, 1, tr1); - //TRAPEZOID + // TRAPEZOID - TGeoArb8 *LateralS2 = new TGeoArb8("LateralS2",45/2); + TGeoArb8* LateralS2 = new TGeoArb8("LateralS2", 45 / 2); LateralS2->SetVertex(0, side4, 0); LateralS2->SetVertex(1, side3, 0); LateralS2->SetVertex(2, side3, base1); @@ -122,102 +117,103 @@ void ShipGoliath::ConstructGeometry() LateralS2->SetVertex(6, side3, base1); LateralS2->SetVertex(7, side4, base2); - TGeoVolume *volLateralS2 = new TGeoVolume("volLateralS2",LateralS2,Fe); + TGeoVolume* volLateralS2 = new TGeoVolume("volLateralS2", LateralS2, Fe); volLateralS2->SetLineColor(kRed); - TGeoRotation *r2 = new TGeoRotation(); - r2->SetAngles(0,90,0); - TGeoCombiTrans tr2(-side1/2, 75, zCenter-side2/2,r2); - TGeoHMatrix *m2 = new TGeoHMatrix(tr2); + TGeoRotation* r2 = new TGeoRotation(); + r2->SetAngles(0, 90, 0); + TGeoCombiTrans tr2(-side1 / 2, 75, zCenter - side2 / 2, r2); + TGeoHMatrix* m2 = new TGeoHMatrix(tr2); top->AddNode(volLateralS2, 1, m2); - //LOWER LATERAL SURFACE + // LOWER LATERAL SURFACE - //LONGER RECTANGLE - TGeoBBox *LateralSurface1low = new TGeoBBox("LateralSurface1low",side3/2,135/2,side5/2); - TGeoTranslation *tr1low = new TGeoTranslation(-side1/2 +side3/2, -15, zCenter- side2/2 +side5/2); + // LONGER RECTANGLE + TGeoBBox* LateralSurface1low = new TGeoBBox("LateralSurface1low", side3 / 2, 135 / 2, side5 / 2); + TGeoTranslation* tr1low = new TGeoTranslation(-side1 / 2 + side3 / 2, -15, zCenter - side2 / 2 + side5 / 2); tr1low->SetName("tr1low"); tr1low->RegisterYourself(); - //SHORTER RECTANGLE - TGeoBBox *LateralSurface2low = new TGeoBBox("LateralSurface2low",28.5,135/2,base2/2); - TGeoTranslation *tr2low = new TGeoTranslation(-side1/2 + (side4-side3)/2 + side3, -15, zCenter-side2/2 +base2/2); + // SHORTER RECTANGLE + TGeoBBox* LateralSurface2low = new TGeoBBox("LateralSurface2low", 28.5, 135 / 2, base2 / 2); + TGeoTranslation* tr2low = + new TGeoTranslation(-side1 / 2 + (side4 - side3) / 2 + side3, -15, zCenter - side2 / 2 + base2 / 2); tr2low->SetName("tr2low"); tr2low->RegisterYourself(); - TGeoCompositeShape *LateralSurfacelow = new TGeoCompositeShape("LateralSurfacelow", "LateralSurface1low:tr1low+LateralSurface2low:tr2low"); - TGeoVolume *volLateralSurfacelow = new TGeoVolume("volLateralSurfacelow",LateralSurfacelow,Fe); + TGeoCompositeShape* LateralSurfacelow = + new TGeoCompositeShape("LateralSurfacelow", "LateralSurface1low:tr1low+LateralSurface2low:tr2low"); + TGeoVolume* volLateralSurfacelow = new TGeoVolume("volLateralSurfacelow", LateralSurfacelow, Fe); volLateralSurfacelow->SetLineColor(kRed); - top->AddNode(volLateralSurfacelow, 1, new TGeoTranslation(0,0,0)); - - + top->AddNode(volLateralSurfacelow, 1, new TGeoTranslation(0, 0, 0)); //***** SIDE Right Front **** - //LONGER RECTANGLE - TGeoBBox *LateralS1_b = new TGeoBBox("LateralS1_b",16.5,45/2,67.5); - TGeoTranslation *tr1_b = new TGeoTranslation(-side1/2 +side3/2, 75, zCenter+ side2/2 - base1/2); - TGeoVolume *volLateralS1_b = new TGeoVolume("volLateralS1_b",LateralS1_b,Fe); + // LONGER RECTANGLE + TGeoBBox* LateralS1_b = new TGeoBBox("LateralS1_b", 16.5, 45 / 2, 67.5); + TGeoTranslation* tr1_b = new TGeoTranslation(-side1 / 2 + side3 / 2, 75, zCenter + side2 / 2 - base1 / 2); + TGeoVolume* volLateralS1_b = new TGeoVolume("volLateralS1_b", LateralS1_b, Fe); volLateralS1_b->SetLineColor(kRed); top->AddNode(volLateralS1_b, 1, tr1_b); - //TRAPEZOID - TGeoArb8 *LateralS2_b = new TGeoArb8("LateralS2_b",45/2); - LateralS2_b ->SetVertex(0, side4, 0); - LateralS2_b ->SetVertex(1, side3, 0); - LateralS2_b ->SetVertex(2, side3, base1); - LateralS2_b ->SetVertex(3, side4, base2); - LateralS2_b ->SetVertex(4, side4, 0); - LateralS2_b ->SetVertex(5, side3, 0); - LateralS2_b ->SetVertex(6, side3, base1); - LateralS2_b ->SetVertex(7, side4, base2); - - TGeoVolume *volLateralS2_b = new TGeoVolume("volLateralS2_b",LateralS2_b,Fe); + // TRAPEZOID + TGeoArb8* LateralS2_b = new TGeoArb8("LateralS2_b", 45 / 2); + LateralS2_b->SetVertex(0, side4, 0); + LateralS2_b->SetVertex(1, side3, 0); + LateralS2_b->SetVertex(2, side3, base1); + LateralS2_b->SetVertex(3, side4, base2); + LateralS2_b->SetVertex(4, side4, 0); + LateralS2_b->SetVertex(5, side3, 0); + LateralS2_b->SetVertex(6, side3, base1); + LateralS2_b->SetVertex(7, side4, base2); + + TGeoVolume* volLateralS2_b = new TGeoVolume("volLateralS2_b", LateralS2_b, Fe); volLateralS2_b->SetLineColor(kRed); - TGeoRotation *r2_b = new TGeoRotation(); - r2_b->SetAngles(0,270,0); - TGeoCombiTrans tr2_b(-side1/2, 75, zCenter + side2/2,r2_b); - TGeoHMatrix *m2_b = new TGeoHMatrix(tr2_b); + TGeoRotation* r2_b = new TGeoRotation(); + r2_b->SetAngles(0, 270, 0); + TGeoCombiTrans tr2_b(-side1 / 2, 75, zCenter + side2 / 2, r2_b); + TGeoHMatrix* m2_b = new TGeoHMatrix(tr2_b); top->AddNode(volLateralS2_b, 1, m2_b); - //LOWER LATERAL SURFACE + // LOWER LATERAL SURFACE - //LONGER RECTANGLE - TGeoBBox *LateralSurface1dlow = new TGeoBBox("LateralSurface1dlow",side3/2,135/2,side5/2); - TGeoTranslation *tr1dlow = new TGeoTranslation(-side1/2 +side3/2, -15, zCenter+ side2/2 -side5/2); + // LONGER RECTANGLE + TGeoBBox* LateralSurface1dlow = new TGeoBBox("LateralSurface1dlow", side3 / 2, 135 / 2, side5 / 2); + TGeoTranslation* tr1dlow = new TGeoTranslation(-side1 / 2 + side3 / 2, -15, zCenter + side2 / 2 - side5 / 2); tr1dlow->SetName("tr1dlow"); tr1dlow->RegisterYourself(); - //SHORTER RECTANGLE - TGeoBBox *LateralSurface2dlow = new TGeoBBox("LateralSurface2dlow",28.5,135/2,base2/2); - TGeoTranslation *tr2dlow = new TGeoTranslation(-side1/2 + (side4-side3)/2 + side3, -15, zCenter+side2/2 -base2/2); + // SHORTER RECTANGLE + TGeoBBox* LateralSurface2dlow = new TGeoBBox("LateralSurface2dlow", 28.5, 135 / 2, base2 / 2); + TGeoTranslation* tr2dlow = + new TGeoTranslation(-side1 / 2 + (side4 - side3) / 2 + side3, -15, zCenter + side2 / 2 - base2 / 2); tr2dlow->SetName("tr2dlow"); tr2dlow->RegisterYourself(); - TGeoCompositeShape *LateralSurfacedlow = new TGeoCompositeShape("LateralSurfacedlow", "LateralSurface1dlow:tr1dlow+LateralSurface2dlow:tr2dlow"); - TGeoVolume *volLateralSurfacedlow = new TGeoVolume("volLateralSurfacedlow",LateralSurfacedlow,Fe); + TGeoCompositeShape* LateralSurfacedlow = + new TGeoCompositeShape("LateralSurfacedlow", "LateralSurface1dlow:tr1dlow+LateralSurface2dlow:tr2dlow"); + TGeoVolume* volLateralSurfacedlow = new TGeoVolume("volLateralSurfacedlow", LateralSurfacedlow, Fe); volLateralSurfacedlow->SetLineColor(kRed); - top->AddNode(volLateralSurfacedlow, 1, new TGeoTranslation(0,0,0)); - + top->AddNode(volLateralSurfacedlow, 1, new TGeoTranslation(0, 0, 0)); //***** SIDE left Back **** - //UPPER LATERAL SURFACE = LOWER ONE + // UPPER LATERAL SURFACE = LOWER ONE - //LONGER RECTANGLE + // LONGER RECTANGLE - TGeoBBox *LateralS1_d = new TGeoBBox("LateralS1_d",16.5,height/2,67.5); - TGeoTranslation *tr1_d = new TGeoTranslation(side1/2 - side3/2, 7.5, zCenter- side2/2 +base1/2); - TGeoVolume *volLateralS1_d = new TGeoVolume("volLateralS1_d",LateralS1_d,Fe); + TGeoBBox* LateralS1_d = new TGeoBBox("LateralS1_d", 16.5, height / 2, 67.5); + TGeoTranslation* tr1_d = new TGeoTranslation(side1 / 2 - side3 / 2, 7.5, zCenter - side2 / 2 + base1 / 2); + TGeoVolume* volLateralS1_d = new TGeoVolume("volLateralS1_d", LateralS1_d, Fe); volLateralS1_d->SetLineColor(kRed); top->AddNode(volLateralS1_d, 1, tr1_d); - //TRAPEZOID + // TRAPEZOID - TGeoArb8 *LateralS2_d = new TGeoArb8("LateralS2_d",height/2); + TGeoArb8* LateralS2_d = new TGeoArb8("LateralS2_d", height / 2); LateralS2_d->SetVertex(0, side4, 0); LateralS2_d->SetVertex(1, side3, 0); LateralS2_d->SetVertex(2, side3, base1); @@ -227,50 +223,45 @@ void ShipGoliath::ConstructGeometry() LateralS2_d->SetVertex(6, side3, base1); LateralS2_d->SetVertex(7, side4, base2); - - TGeoVolume *volLateralS2_d = new TGeoVolume("volLateralS2_d",LateralS2_d,Fe); + TGeoVolume* volLateralS2_d = new TGeoVolume("volLateralS2_d", LateralS2_d, Fe); volLateralS2_d->SetLineColor(kRed); - TGeoRotation *r2_d = new TGeoRotation(); - r2_d->SetAngles(0,270,180); - TGeoCombiTrans tr2_d(side1/2, 7.5, zCenter -side2/2,r2_d); - TGeoHMatrix *m2_d = new TGeoHMatrix(tr2_d); + TGeoRotation* r2_d = new TGeoRotation(); + r2_d->SetAngles(0, 270, 180); + TGeoCombiTrans tr2_d(side1 / 2, 7.5, zCenter - side2 / 2, r2_d); + TGeoHMatrix* m2_d = new TGeoHMatrix(tr2_d); top->AddNode(volLateralS2_d, 1, m2_d); - - //***** SIDE right Back **** + // UPPER LATERAL SURFACE = LOWER ONE - //UPPER LATERAL SURFACE = LOWER ONE + // LONGER RECTANGLE - //LONGER RECTANGLE - - TGeoBBox *LateralS1_c = new TGeoBBox("LateralS1_c",16.5,height/2,67.5); - TGeoTranslation *tr1_c = new TGeoTranslation(side1/2 - side3/2, 7.5, zCenter+ side2/2 -base1/2); - TGeoVolume *volLateralS1_c = new TGeoVolume("volLateralS1_c",LateralS1_c,Fe); + TGeoBBox* LateralS1_c = new TGeoBBox("LateralS1_c", 16.5, height / 2, 67.5); + TGeoTranslation* tr1_c = new TGeoTranslation(side1 / 2 - side3 / 2, 7.5, zCenter + side2 / 2 - base1 / 2); + TGeoVolume* volLateralS1_c = new TGeoVolume("volLateralS1_c", LateralS1_c, Fe); volLateralS1_c->SetLineColor(kRed); top->AddNode(volLateralS1_c, 1, tr1_c); + // TRAPEZOID - //TRAPEZOID - - TGeoArb8 *LateralS2_c = new TGeoArb8("LateralS2_c",height/2); - LateralS2_c ->SetVertex(0, side4, 0); - LateralS2_c ->SetVertex(1, side3, 0); - LateralS2_c ->SetVertex(2, side3, base1); - LateralS2_c ->SetVertex(3, side4, base2); - LateralS2_c ->SetVertex(4, side4, 0); - LateralS2_c ->SetVertex(5, side3, 0); - LateralS2_c ->SetVertex(6, side3, base1); - LateralS2_c ->SetVertex(7, side4, base2); + TGeoArb8* LateralS2_c = new TGeoArb8("LateralS2_c", height / 2); + LateralS2_c->SetVertex(0, side4, 0); + LateralS2_c->SetVertex(1, side3, 0); + LateralS2_c->SetVertex(2, side3, base1); + LateralS2_c->SetVertex(3, side4, base2); + LateralS2_c->SetVertex(4, side4, 0); + LateralS2_c->SetVertex(5, side3, 0); + LateralS2_c->SetVertex(6, side3, base1); + LateralS2_c->SetVertex(7, side4, base2); - TGeoVolume *volLateralS2_c = new TGeoVolume("volLateralS2_c",LateralS2_c,Fe); + TGeoVolume* volLateralS2_c = new TGeoVolume("volLateralS2_c", LateralS2_c, Fe); volLateralS2_c->SetLineColor(kRed); - TGeoRotation *r2_c = new TGeoRotation(); - r2_c->SetAngles(0,90,180); - TGeoCombiTrans tr2_c(side1/2, 7.5, zCenter + side2/2,r2_c); - TGeoHMatrix *m2_c = new TGeoHMatrix(tr2_c); + TGeoRotation* r2_c = new TGeoRotation(); + r2_c->SetAngles(0, 90, 180); + TGeoCombiTrans tr2_c(side1 / 2, 7.5, zCenter + side2 / 2, r2_c); + TGeoHMatrix* m2_c = new TGeoHMatrix(tr2_c); top->AddNode(volLateralS2_c, 1, m2_c); } diff --git a/passive/ShipGoliath.h b/passive/ShipGoliath.h index 16462e231d..7d8d4094a6 100644 --- a/passive/ShipGoliath.h +++ b/passive/ShipGoliath.h @@ -1,26 +1,29 @@ #ifndef GOLIATH_H #define GOLIATH_H -#include "FairModule.h" // for FairModule +#include "FairModule.h" // for FairModule +#include "Rtypes.h" // for ShipMagnet::Class, Bool_t, etc -#include "Rtypes.h" // for ShipMagnet::Class, Bool_t, etc - -#include // for string +#include // for string class ShipGoliath : public FairModule { public: - ShipGoliath(const char* name, const Double_t zC, const Double_t LS, const Double_t TS, const Double_t GapTS, const char* Title="Goliath"); + ShipGoliath(const char* name, + const Double_t zC, + const Double_t LS, + const Double_t TS, + const Double_t GapTS, + const char* Title = "Goliath"); ShipGoliath(); virtual ~ShipGoliath(); void ConstructGeometry(); - ClassDef(ShipGoliath,1) + ClassDef(ShipGoliath, 1) -protected: - Double_t zCenter; + protected : Double_t zCenter; Double_t LongitudinalSize; Double_t TransversalSize; Double_t GapFromTSpectro; }; -#endif //GOLIATH_H +#endif // GOLIATH_H diff --git a/passive/ShipMagnet.cxx b/passive/ShipMagnet.cxx index bc97dbef39..8e8f9affe8 100644 --- a/passive/ShipMagnet.cxx +++ b/passive/ShipMagnet.cxx @@ -1,242 +1,260 @@ #include "ShipMagnet.h" +#include "FairRun.h" // for FairRun +#include "FairRuntimeDb.h" // for FairRuntimeDb #include "TGeoManager.h" -#include "FairRun.h" // for FairRun -#include "FairRuntimeDb.h" // for FairRuntimeDb -//#include "FairGeoMedia.h" -//#include "FairGeoBuilder.h" - -#include // for ostream -#include "TList.h" // for TListIter, TList (ptr only) -#include "TObjArray.h" // for TObjArray -#include "TString.h" // for TString -#include "TGeoBBox.h" -#include "TGeoCompositeShape.h" +// #include "FairGeoMedia.h" +// #include "FairGeoBuilder.h" + +#include "FairGeoBuilder.h" #include "FairGeoInterface.h" #include "FairGeoMedia.h" -#include "FairGeoBuilder.h" -#include "TGeoTube.h" -#include "TGeoMaterial.h" +#include "TGeoBBox.h" +#include "TGeoCompositeShape.h" #include "TGeoElement.h" #include "TGeoEltu.h" +#include "TGeoMaterial.h" #include "TGeoMedium.h" -#include // for NULL -#include // for operator<<, basic_ostream, etc - +#include "TGeoTube.h" +#include "TList.h" // for TListIter, TList (ptr only) +#include "TObjArray.h" // for TObjArray +#include "TString.h" // for TString +#include // for ostream +#include // for operator<<, basic_ostream, etc +#include // for NULL -ShipMagnet::~ShipMagnet() -{ -} +ShipMagnet::~ShipMagnet() {} ShipMagnet::ShipMagnet() - : FairModule("ShipMagnet", "") -{ -} + : FairModule("ShipMagnet", "") +{} -ShipMagnet::ShipMagnet(const char* name, const char* Title, Double_t z, Int_t c, Double_t dx, Double_t dy, Double_t fl, Double_t YW, Double_t YD, Double_t CT) - : FairModule(name ,Title) +ShipMagnet::ShipMagnet(const char* name, + const char* Title, + Double_t z, + Int_t c, + Double_t dx, + Double_t dy, + Double_t fl, + Double_t YW, + Double_t YD, + Double_t CT) + : FairModule(name, Title) { - fDesign = c; - fSpecMagz = z; - fDy = dy; - fDx = dx; - floorheight = fl; - YokeWidth = YW; - YokeDepth = YD; - CoilThick = CT; + fDesign = c; + fSpecMagz = z; + fDy = dy; + fDx = dx; + floorheight = fl; + YokeWidth = YW; + YokeDepth = YD; + CoilThick = CT; } // ----- Private method InitMedium Int_t ShipMagnet::InitMedium(const char* name) { - static FairGeoLoader *geoLoad=FairGeoLoader::Instance(); - static FairGeoInterface *geoFace=geoLoad->getGeoInterface(); - static FairGeoMedia *media=geoFace->getMedia(); - static FairGeoBuilder *geoBuild=geoLoad->getGeoBuilder(); - - FairGeoMedium *ShipMedium=media->getMedium(name); - - if (!ShipMedium) - { - Fatal("InitMedium","Material %s not defined in media file.", name); - return -1111; - } - TGeoMedium* medium=gGeoManager->GetMedium(name); - if (medium!=NULL) - return ShipMedium->getMediumIndex(); - - return geoBuild->createMedium(ShipMedium); + static FairGeoLoader* geoLoad = FairGeoLoader::Instance(); + static FairGeoInterface* geoFace = geoLoad->getGeoInterface(); + static FairGeoMedia* media = geoFace->getMedia(); + static FairGeoBuilder* geoBuild = geoLoad->getGeoBuilder(); + + FairGeoMedium* ShipMedium = media->getMedium(name); + + if (!ShipMedium) { + Fatal("InitMedium", "Material %s not defined in media file.", name); + return -1111; + } + TGeoMedium* medium = gGeoManager->GetMedium(name); + if (medium != NULL) + return ShipMedium->getMediumIndex(); + + return geoBuild->createMedium(ShipMedium); } // private method make support of magnet -TGeoVolume* ShipMagnet::MagnetSupport(Double_t hwidth,Double_t hheight,Double_t dz,Int_t colour,TGeoMedium *material) +TGeoVolume* ShipMagnet::MagnetSupport(Double_t hwidth, + Double_t hheight, + Double_t dz, + Int_t colour, + TGeoMedium* material) { - TGeoBBox *ms = new TGeoBBox("ms", hwidth,hheight-1.,dz); - //try to make SHiP like logo in support - Double_t swidth=30.; // - //6 cutouts from the front - Double_t r25=hheight-swidth/2.; - Double_t r1346=hwidth-swidth/2; - Double_t alpha=atan(hheight/hwidth)*180./TMath::Pi(); - TGeoTubeSeg *FL1 = new TGeoTubeSeg("FL1",swidth,r1346,dz+1.,5.,alpha-5.); - TGeoTubeSeg *FL3 = new TGeoTubeSeg("FL3",swidth,r1346,dz+1.,180-alpha+5.,175.); - TGeoTubeSeg *FL4 = new TGeoTubeSeg("FL4",swidth,r1346,dz+1.,185.,180.+alpha-5.); - TGeoTubeSeg *FL6 = new TGeoTubeSeg("FL6",swidth,r1346,dz+1.,360.-alpha+5.,355.); - TGeoTubeSeg *FL2 = new TGeoTubeSeg("FL2",swidth,r25,dz+1.,alpha+5.,180-alpha-5.); - TGeoTubeSeg *FL5 = new TGeoTubeSeg("FL5",swidth,r25,dz+1.,180.+alpha+5.,360.-alpha-5.); - - //6 cutouts from the side - r1346=dz-swidth/2; - alpha=atan(hheight/dz)*180./TMath::Pi(); - //cout << "magsupport: "<< swidth<<", "<RotateY(90.); r->RegisterYourself(); - - TGeoCompositeShape *TS = new TGeoCompositeShape("TS",\ - "ms-FL1-FL2-FL3-FL4-FL5-FL6-SL1:r-SL2:r-SL3:r-SL4:r-SL5:r-SL6:r"); - - TGeoVolume *T = new TGeoVolume("TSUP", TS, material); - T->SetLineColor(colour); - return T; + TGeoBBox* ms = new TGeoBBox("ms", hwidth, hheight - 1., dz); + // try to make SHiP like logo in support + Double_t swidth = 30.; // + // 6 cutouts from the front + Double_t r25 = hheight - swidth / 2.; + Double_t r1346 = hwidth - swidth / 2; + Double_t alpha = atan(hheight / hwidth) * 180. / TMath::Pi(); + TGeoTubeSeg* FL1 = new TGeoTubeSeg("FL1", swidth, r1346, dz + 1., 5., alpha - 5.); + TGeoTubeSeg* FL3 = new TGeoTubeSeg("FL3", swidth, r1346, dz + 1., 180 - alpha + 5., 175.); + TGeoTubeSeg* FL4 = new TGeoTubeSeg("FL4", swidth, r1346, dz + 1., 185., 180. + alpha - 5.); + TGeoTubeSeg* FL6 = new TGeoTubeSeg("FL6", swidth, r1346, dz + 1., 360. - alpha + 5., 355.); + TGeoTubeSeg* FL2 = new TGeoTubeSeg("FL2", swidth, r25, dz + 1., alpha + 5., 180 - alpha - 5.); + TGeoTubeSeg* FL5 = new TGeoTubeSeg("FL5", swidth, r25, dz + 1., 180. + alpha + 5., 360. - alpha - 5.); + + // 6 cutouts from the side + r1346 = dz - swidth / 2; + alpha = atan(hheight / dz) * 180. / TMath::Pi(); + // cout << "magsupport: "<< swidth<<", "<RotateY(90.); + r->RegisterYourself(); + + TGeoCompositeShape* TS = + new TGeoCompositeShape("TS", "ms-FL1-FL2-FL3-FL4-FL5-FL6-SL1:r-SL2:r-SL3:r-SL4:r-SL5:r-SL6:r"); + + TGeoVolume* T = new TGeoVolume("TSUP", TS, material); + T->SetLineColor(colour); + return T; } void ShipMagnet::ConstructGeometry() { - TGeoVolume *top=gGeoManager->GetTopVolume(); + TGeoVolume* top = gGeoManager->GetTopVolume(); InitMedium("iron"); - TGeoMedium *Fe =gGeoManager->GetMedium("iron"); + TGeoMedium* Fe = gGeoManager->GetMedium("iron"); InitMedium("Aluminum"); - TGeoMedium *Al =gGeoManager->GetMedium("Aluminum"); - TGeoVolumeAssembly *tMagnet = new TGeoVolumeAssembly("SHiPMagnet"); + TGeoMedium* Al = gGeoManager->GetMedium("Aluminum"); + TGeoVolumeAssembly* tMagnet = new TGeoVolumeAssembly("SHiPMagnet"); top->AddNode(tMagnet, 1, new TGeoTranslation(0, 0, 0)); - Double_t cm = 1; - Double_t m = 100*cm; - if (fDesign==1){ - // magnet yoke - TGeoBBox *magyoke1 = new TGeoBBox("magyoke1", 350, 350, 125); - TGeoBBox *magyoke2 = new TGeoBBox("magyoke2", 250, 250, 126); - - TGeoCompositeShape *magyokec = new TGeoCompositeShape("magyokec", "magyoke1-magyoke2"); - TGeoVolume *magyoke = new TGeoVolume("magyoke", magyokec, Fe); - magyoke->SetLineColor(kBlue); - //magyoke->SetTransparency(50); - tMagnet->AddNode(magyoke, 1, new TGeoTranslation(0, 0, 1940)); - - // magnet - TGeoTubeSeg *magnet1a = new TGeoTubeSeg("magnet1a", 250, 300, 35, 45, 135); - TGeoTubeSeg *magnet1b = new TGeoTubeSeg("magnet1b", 250, 300, 35, 45, 135); - TGeoTubeSeg *magnet1c = new TGeoTubeSeg("magnet1c", 250, 270, 125, 45, 60); - TGeoTubeSeg *magnet1d = new TGeoTubeSeg("magnet1d", 250, 270, 125, 120, 135); - - // magnet composite shape matrices - TGeoTranslation *m1 = new TGeoTranslation(0, 0, 160); - m1->SetName("m1"); - m1->RegisterYourself(); - TGeoTranslation *m2 = new TGeoTranslation(0, 0, -160); - m2->SetName("m2"); - m2->RegisterYourself(); - - TGeoCompositeShape *magcomp1 = new TGeoCompositeShape("magcomp1", "magnet1a:m1+magnet1b:m2+magnet1c+magnet1d"); - TGeoVolume *magnet1 = new TGeoVolume("magnet1", magcomp1, Fe); - magnet1->SetLineColor(kYellow); - tMagnet->AddNode(magnet1, 1, new TGeoTranslation(0, 0, fSpecMagz)); // was 1940 - - TGeoRotation m3; - m3.SetAngles(180, 0, 0); - TGeoTranslation m4(0, 0, fSpecMagz); // was 1940 - TGeoCombiTrans m5(m4, m3); - TGeoHMatrix *m6 = new TGeoHMatrix(m5); - tMagnet->AddNode(magnet1, 2, m6); - } - else if(fDesign==2 || fDesign==3) { // fDesign==2 TP version, fDesign==3, rectangular version - Double_t Yokel = 1.25*m; - Double_t magnetIncrease = 100.*cm; - // magnet yoke - Double_t bradius = fDy/2.; - TGeoBBox *magyoke1 = new TGeoBBox("magyoke1", fDx+0.7*m, bradius+1.2*m, Yokel); - TGeoBBox *magyoke2 = new TGeoBBox("magyoke2", fDx-0.3*m, bradius+0.2*m, Yokel+0.01*cm); - - TGeoCompositeShape *magyokec = new TGeoCompositeShape("magyokec", "magyoke1-magyoke2"); - TGeoVolume *magyoke = new TGeoVolume("magyoke", magyokec, Fe); - magyoke->SetLineColor(kBlue); - tMagnet->AddNode(magyoke, 1, new TGeoTranslation(0, 0, fSpecMagz)); - - Double_t hsupport=(10.*m-(bradius+1.2*m)-floorheight)/2.; - TGeoVolume* SMS =MagnetSupport(fDx+0.7*m, hsupport, Yokel,15,Fe); - tMagnet->AddNode(SMS, 1, new TGeoTranslation(0, -bradius-1.2*m-hsupport, fSpecMagz)); - - //Attempt to make Al coils... - TGeoCompositeShape *MCoilc; - if(fDesign==2){ - TGeoEltu *C2 = new TGeoEltu("C2",fDx,bradius+0.5*m,Yokel+0.6*m+magnetIncrease/2.); - TGeoEltu *C1 = new TGeoEltu("C1",fDx-0.3*m,bradius+0.2*m,Yokel+0.601*m+magnetIncrease/2.); - TGeoBBox *Box1 = new TGeoBBox("Box1", 1.*m, bradius+0.51*m, Yokel+0.61*m+magnetIncrease/2.); - TGeoBBox *Box2 = new TGeoBBox("Box2", fDx+0.01*m, bradius-0.5*m, Yokel+0.01*m+magnetIncrease/2.); - MCoilc = new TGeoCompositeShape("MCoilc", "C2-C1-magyokec-Box1-Box2"); - }else{ - TGeoBBox *C2 = new TGeoBBox("C2", fDx, bradius+0.5*m, Yokel+0.6*m+magnetIncrease/2.); - TGeoBBox *C1 = new TGeoBBox("C1", fDx-0.3*m, bradius+0.2*m, Yokel+0.601*m+magnetIncrease/2.); - MCoilc = new TGeoCompositeShape("MCoilc", "C2-C1-magyokec"); - } - TGeoVolume *MCoil = new TGeoVolume("MCoil", MCoilc, Al); - MCoil->SetLineColor(kYellow); - - tMagnet->AddNode(MCoil, 1, new TGeoTranslation(0, 0, fSpecMagz)); - - }else if(fDesign==4) { // rectangular a la MISIS, full opening for vessel - //define dimensions - Double_t xaperture=fDx; //half apertures - Double_t yaperture=fDy; - //built the yoke - TGeoBBox *magyoke1 = new TGeoBBox("magyoke1", xaperture+YokeWidth,yaperture+YokeWidth,YokeDepth); - TGeoBBox *magyoke2 = new TGeoBBox("magyoke2", xaperture,yaperture,YokeDepth+1.); - TGeoCompositeShape *magyokec = new TGeoCompositeShape("magyokec", "magyoke1-magyoke2"); - //and a epsilon larger yoke to subtract while making the coils - TGeoBBox *my1 = new TGeoBBox("my1", xaperture+YokeWidth,yaperture+YokeWidth,YokeDepth+0.1*cm); - TGeoBBox *my2 = new TGeoBBox("my2", xaperture-0.1*cm,yaperture-0.1*cm,YokeDepth+1.); - TGeoCompositeShape *myc = new TGeoCompositeShape("myc", "my1-my2"); - TGeoVolume *magyoke = new TGeoVolume("magyoke", magyokec, Fe); - magyoke->SetLineColor(kBlue); - tMagnet->AddNode(magyoke, 1, new TGeoTranslation(0, 0, fSpecMagz)); - //and the coils: top - TGeoTubeSeg *CTop = new TGeoTubeSeg("CTop",1.*cm,YokeWidth,YokeDepth+CoilThick+1.*cm,0.,180.); - TGeoTranslation *t1 = new TGeoTranslation("t1",xaperture,yaperture-CoilThick,0.); t1->RegisterYourself(); - TGeoTranslation *t2 = new TGeoTranslation("t2",-xaperture,yaperture-CoilThick,0.); t2->RegisterYourself(); - TGeoCompositeShape *CTop1 = new TGeoCompositeShape("CTop1", "CTop:t1-myc"); - TGeoCompositeShape *CTop2 = new TGeoCompositeShape("CTop2", "CTop:t2-myc"); - TGeoVolume *MCoil1 = new TGeoVolume("MCoil1", CTop1, Al); - TGeoVolume *MCoil2 = new TGeoVolume("MCoil2", CTop2, Al); - MCoil1->SetLineColor(kYellow); - tMagnet->AddNode(MCoil1, 1, new TGeoTranslation(0, 0, fSpecMagz)); - MCoil2->SetLineColor(kYellow); - tMagnet->AddNode(MCoil2, 1, new TGeoTranslation(0, 0, fSpecMagz)); - //coils bottom - TGeoTubeSeg *CBot = new TGeoTubeSeg("CBot",1.*cm,YokeWidth,YokeDepth+CoilThick+1.*cm,180.,360.); - TGeoTranslation *b1 = new TGeoTranslation("b1",xaperture,-yaperture+CoilThick,0.); b1->RegisterYourself(); - TGeoTranslation *b2 = new TGeoTranslation("b2",-xaperture,-yaperture+CoilThick,0.); b2->RegisterYourself(); - TGeoCompositeShape *CBot1 = new TGeoCompositeShape("CBot1", "CBot:b1-myc"); - TGeoCompositeShape *CBot2 = new TGeoCompositeShape("CBot2", "CBot:b2-myc"); - TGeoVolume *MCoil3 = new TGeoVolume("MCoil3", CBot1, Al); - TGeoVolume *MCoil4 = new TGeoVolume("MCoil4", CBot2, Al); - MCoil3->SetLineColor(kYellow); - tMagnet->AddNode(MCoil3, 1, new TGeoTranslation(0, 0, fSpecMagz)); - MCoil4->SetLineColor(kYellow); - tMagnet->AddNode(MCoil4, 1, new TGeoTranslation(0, 0, fSpecMagz)); - //add vertical coils - TGeoBBox *CVert = new TGeoBBox("CVert",YokeWidth/2.,yaperture-CoilThick,CoilThick/2.); - TGeoVolume *CV = new TGeoVolume("CV", CVert, Al); - CV->SetLineColor(kYellow); - tMagnet->AddNode(CV, 1, new TGeoTranslation(xaperture+YokeWidth/2., 0, fSpecMagz-YokeDepth-CoilThick/2.)); - tMagnet->AddNode(CV, 2, new TGeoTranslation(-xaperture-YokeWidth/2., 0, fSpecMagz-YokeDepth-CoilThick/2.)); - tMagnet->AddNode(CV, 3, new TGeoTranslation(xaperture+YokeWidth/2., 0, fSpecMagz+YokeDepth+CoilThick/2.)); - tMagnet->AddNode(CV, 4, new TGeoTranslation(-xaperture-YokeWidth/2., 0, fSpecMagz+YokeDepth+CoilThick/2.)); + Double_t cm = 1; + Double_t m = 100 * cm; + if (fDesign == 1) { + // magnet yoke + TGeoBBox* magyoke1 = new TGeoBBox("magyoke1", 350, 350, 125); + TGeoBBox* magyoke2 = new TGeoBBox("magyoke2", 250, 250, 126); + + TGeoCompositeShape* magyokec = new TGeoCompositeShape("magyokec", "magyoke1-magyoke2"); + TGeoVolume* magyoke = new TGeoVolume("magyoke", magyokec, Fe); + magyoke->SetLineColor(kBlue); + // magyoke->SetTransparency(50); + tMagnet->AddNode(magyoke, 1, new TGeoTranslation(0, 0, 1940)); + + // magnet + TGeoTubeSeg* magnet1a = new TGeoTubeSeg("magnet1a", 250, 300, 35, 45, 135); + TGeoTubeSeg* magnet1b = new TGeoTubeSeg("magnet1b", 250, 300, 35, 45, 135); + TGeoTubeSeg* magnet1c = new TGeoTubeSeg("magnet1c", 250, 270, 125, 45, 60); + TGeoTubeSeg* magnet1d = new TGeoTubeSeg("magnet1d", 250, 270, 125, 120, 135); + + // magnet composite shape matrices + TGeoTranslation* m1 = new TGeoTranslation(0, 0, 160); + m1->SetName("m1"); + m1->RegisterYourself(); + TGeoTranslation* m2 = new TGeoTranslation(0, 0, -160); + m2->SetName("m2"); + m2->RegisterYourself(); + + TGeoCompositeShape* magcomp1 = new TGeoCompositeShape("magcomp1", "magnet1a:m1+magnet1b:m2+magnet1c+magnet1d"); + TGeoVolume* magnet1 = new TGeoVolume("magnet1", magcomp1, Fe); + magnet1->SetLineColor(kYellow); + tMagnet->AddNode(magnet1, 1, new TGeoTranslation(0, 0, fSpecMagz)); // was 1940 + + TGeoRotation m3; + m3.SetAngles(180, 0, 0); + TGeoTranslation m4(0, 0, fSpecMagz); // was 1940 + TGeoCombiTrans m5(m4, m3); + TGeoHMatrix* m6 = new TGeoHMatrix(m5); + tMagnet->AddNode(magnet1, 2, m6); + } else if (fDesign == 2 || fDesign == 3) { // fDesign==2 TP version, fDesign==3, rectangular version + Double_t Yokel = 1.25 * m; + Double_t magnetIncrease = 100. * cm; + // magnet yoke + Double_t bradius = fDy / 2.; + TGeoBBox* magyoke1 = new TGeoBBox("magyoke1", fDx + 0.7 * m, bradius + 1.2 * m, Yokel); + TGeoBBox* magyoke2 = new TGeoBBox("magyoke2", fDx - 0.3 * m, bradius + 0.2 * m, Yokel + 0.01 * cm); + + TGeoCompositeShape* magyokec = new TGeoCompositeShape("magyokec", "magyoke1-magyoke2"); + TGeoVolume* magyoke = new TGeoVolume("magyoke", magyokec, Fe); + magyoke->SetLineColor(kBlue); + tMagnet->AddNode(magyoke, 1, new TGeoTranslation(0, 0, fSpecMagz)); + + Double_t hsupport = (10. * m - (bradius + 1.2 * m) - floorheight) / 2.; + TGeoVolume* SMS = MagnetSupport(fDx + 0.7 * m, hsupport, Yokel, 15, Fe); + tMagnet->AddNode(SMS, 1, new TGeoTranslation(0, -bradius - 1.2 * m - hsupport, fSpecMagz)); + + // Attempt to make Al coils... + TGeoCompositeShape* MCoilc; + if (fDesign == 2) { + TGeoEltu* C2 = new TGeoEltu("C2", fDx, bradius + 0.5 * m, Yokel + 0.6 * m + magnetIncrease / 2.); + TGeoEltu* C1 = + new TGeoEltu("C1", fDx - 0.3 * m, bradius + 0.2 * m, Yokel + 0.601 * m + magnetIncrease / 2.); + TGeoBBox* Box1 = new TGeoBBox("Box1", 1. * m, bradius + 0.51 * m, Yokel + 0.61 * m + magnetIncrease / 2.); + TGeoBBox* Box2 = + new TGeoBBox("Box2", fDx + 0.01 * m, bradius - 0.5 * m, Yokel + 0.01 * m + magnetIncrease / 2.); + MCoilc = new TGeoCompositeShape("MCoilc", "C2-C1-magyokec-Box1-Box2"); + } else { + TGeoBBox* C2 = new TGeoBBox("C2", fDx, bradius + 0.5 * m, Yokel + 0.6 * m + magnetIncrease / 2.); + TGeoBBox* C1 = + new TGeoBBox("C1", fDx - 0.3 * m, bradius + 0.2 * m, Yokel + 0.601 * m + magnetIncrease / 2.); + MCoilc = new TGeoCompositeShape("MCoilc", "C2-C1-magyokec"); + } + TGeoVolume* MCoil = new TGeoVolume("MCoil", MCoilc, Al); + MCoil->SetLineColor(kYellow); + tMagnet->AddNode(MCoil, 1, new TGeoTranslation(0, 0, fSpecMagz)); + } else if (fDesign == 4) { // rectangular a la MISIS, full opening for vessel + // define dimensions + Double_t xaperture = fDx; // half apertures + Double_t yaperture = fDy; + // built the yoke + TGeoBBox* magyoke1 = new TGeoBBox("magyoke1", xaperture + YokeWidth, yaperture + YokeWidth, YokeDepth); + TGeoBBox* magyoke2 = new TGeoBBox("magyoke2", xaperture, yaperture, YokeDepth + 1.); + TGeoCompositeShape* magyokec = new TGeoCompositeShape("magyokec", "magyoke1-magyoke2"); + // and a epsilon larger yoke to subtract while making the coils + TGeoBBox* my1 = new TGeoBBox("my1", xaperture + YokeWidth, yaperture + YokeWidth, YokeDepth + 0.1 * cm); + TGeoBBox* my2 = new TGeoBBox("my2", xaperture - 0.1 * cm, yaperture - 0.1 * cm, YokeDepth + 1.); + TGeoCompositeShape* myc = new TGeoCompositeShape("myc", "my1-my2"); + TGeoVolume* magyoke = new TGeoVolume("magyoke", magyokec, Fe); + magyoke->SetLineColor(kBlue); + tMagnet->AddNode(magyoke, 1, new TGeoTranslation(0, 0, fSpecMagz)); + // and the coils: top + TGeoTubeSeg* CTop = new TGeoTubeSeg("CTop", 1. * cm, YokeWidth, YokeDepth + CoilThick + 1. * cm, 0., 180.); + TGeoTranslation* t1 = new TGeoTranslation("t1", xaperture, yaperture - CoilThick, 0.); + t1->RegisterYourself(); + TGeoTranslation* t2 = new TGeoTranslation("t2", -xaperture, yaperture - CoilThick, 0.); + t2->RegisterYourself(); + TGeoCompositeShape* CTop1 = new TGeoCompositeShape("CTop1", "CTop:t1-myc"); + TGeoCompositeShape* CTop2 = new TGeoCompositeShape("CTop2", "CTop:t2-myc"); + TGeoVolume* MCoil1 = new TGeoVolume("MCoil1", CTop1, Al); + TGeoVolume* MCoil2 = new TGeoVolume("MCoil2", CTop2, Al); + MCoil1->SetLineColor(kYellow); + tMagnet->AddNode(MCoil1, 1, new TGeoTranslation(0, 0, fSpecMagz)); + MCoil2->SetLineColor(kYellow); + tMagnet->AddNode(MCoil2, 1, new TGeoTranslation(0, 0, fSpecMagz)); + // coils bottom + TGeoTubeSeg* CBot = new TGeoTubeSeg("CBot", 1. * cm, YokeWidth, YokeDepth + CoilThick + 1. * cm, 180., 360.); + TGeoTranslation* b1 = new TGeoTranslation("b1", xaperture, -yaperture + CoilThick, 0.); + b1->RegisterYourself(); + TGeoTranslation* b2 = new TGeoTranslation("b2", -xaperture, -yaperture + CoilThick, 0.); + b2->RegisterYourself(); + TGeoCompositeShape* CBot1 = new TGeoCompositeShape("CBot1", "CBot:b1-myc"); + TGeoCompositeShape* CBot2 = new TGeoCompositeShape("CBot2", "CBot:b2-myc"); + TGeoVolume* MCoil3 = new TGeoVolume("MCoil3", CBot1, Al); + TGeoVolume* MCoil4 = new TGeoVolume("MCoil4", CBot2, Al); + MCoil3->SetLineColor(kYellow); + tMagnet->AddNode(MCoil3, 1, new TGeoTranslation(0, 0, fSpecMagz)); + MCoil4->SetLineColor(kYellow); + tMagnet->AddNode(MCoil4, 1, new TGeoTranslation(0, 0, fSpecMagz)); + // add vertical coils + TGeoBBox* CVert = new TGeoBBox("CVert", YokeWidth / 2., yaperture - CoilThick, CoilThick / 2.); + TGeoVolume* CV = new TGeoVolume("CV", CVert, Al); + CV->SetLineColor(kYellow); + tMagnet->AddNode( + CV, 1, new TGeoTranslation(xaperture + YokeWidth / 2., 0, fSpecMagz - YokeDepth - CoilThick / 2.)); + tMagnet->AddNode( + CV, 2, new TGeoTranslation(-xaperture - YokeWidth / 2., 0, fSpecMagz - YokeDepth - CoilThick / 2.)); + tMagnet->AddNode( + CV, 3, new TGeoTranslation(xaperture + YokeWidth / 2., 0, fSpecMagz + YokeDepth + CoilThick / 2.)); + tMagnet->AddNode( + CV, 4, new TGeoTranslation(-xaperture - YokeWidth / 2., 0, fSpecMagz + YokeDepth + CoilThick / 2.)); } } diff --git a/passive/ShipMagnet.h b/passive/ShipMagnet.h index da4baa3517..f183146031 100644 --- a/passive/ShipMagnet.h +++ b/passive/ShipMagnet.h @@ -1,31 +1,39 @@ #ifndef MAGNET_H #define MAGNET_H -#include "FairModule.h" // for FairModule +#include "FairModule.h" // for FairModule +#include "Rtypes.h" // for ShipMagnet::Class, Bool_t, etc #include "TGeoMedium.h" -#include "Rtypes.h" // for ShipMagnet::Class, Bool_t, etc - -#include // for string +#include // for string class ShipMagnet : public FairModule { public: - ShipMagnet(const char* name, const char* Title="SHiP Magnet", Double_t z=2018., Int_t c=2, Double_t dx=3, Double_t dy=5, Double_t fl=2, Double_t YW=1., Double_t YD=1., Double_t CT=1.); + ShipMagnet(const char* name, + const char* Title = "SHiP Magnet", + Double_t z = 2018., + Int_t c = 2, + Double_t dx = 3, + Double_t dy = 5, + Double_t fl = 2, + Double_t YW = 1., + Double_t YD = 1., + Double_t CT = 1.); ShipMagnet(); virtual ~ShipMagnet(); void ConstructGeometry(); - ClassDef(ShipMagnet,5) - protected: + ClassDef(ShipMagnet, 5) protected + : - Int_t fDesign; // design, 1=circular 5m, 2 = ellipse 5x10, 3 = rectangular - Int_t fSpecMagz; // z position - Double_t fDy; // y diameter of ellipse - Double_t fDx; // x diameter of ellipse - Double_t YokeWidth, YokeDepth, CoilThick; - Double_t floorheight; - TGeoVolume* MagnetSupport(Double_t hwidth,Double_t hheight,Double_t dz,Int_t colour,TGeoMedium *material); - Int_t InitMedium(const char* name); + Int_t fDesign; // design, 1=circular 5m, 2 = ellipse 5x10, 3 = rectangular + Int_t fSpecMagz; // z position + Double_t fDy; // y diameter of ellipse + Double_t fDx; // x diameter of ellipse + Double_t YokeWidth, YokeDepth, CoilThick; + Double_t floorheight; + TGeoVolume* MagnetSupport(Double_t hwidth, Double_t hheight, Double_t dz, Int_t colour, TGeoMedium* material); + Int_t InitMedium(const char* name); }; -#endif //MAGNET_H +#endif // MAGNET_H diff --git a/passive/ShipMuonShield.cxx b/passive/ShipMuonShield.cxx index c0e8aae2b5..d457c40ab4 100644 --- a/passive/ShipMuonShield.cxx +++ b/passive/ShipMuonShield.cxx @@ -1,20 +1,21 @@ #include "ShipMuonShield.h" -#include "TGeoManager.h" -#include "TObjArray.h" // for TObjArray -#include "TString.h" // for TString -#include "TGeoBBox.h" -#include "TGeoTrd1.h" -#include "TGeoCompositeShape.h" -#include "TGeoBoolNode.h" -#include "TGeoTube.h" -#include "TGeoMaterial.h" +#include "FairGeoBuilder.h" #include "FairGeoInterface.h" #include "FairGeoMedia.h" -#include "FairGeoBuilder.h" -#include "FairRuntimeDb.h" // for FairRuntimeDb +#include "FairRuntimeDb.h" // for FairRuntimeDb #include "TFile.h" -#include // for operator<<, basic_ostream, etc +#include "TGeoBBox.h" +#include "TGeoBoolNode.h" +#include "TGeoCompositeShape.h" +#include "TGeoManager.h" +#include "TGeoMaterial.h" +#include "TGeoTrd1.h" +#include "TGeoTube.h" +#include "TObjArray.h" // for TObjArray +#include "TString.h" // for TString + +#include // for operator<<, basic_ostream, etc Double_t cm = 1; Double_t m = 100 * cm; @@ -23,274 +24,324 @@ Double_t kilogauss = 1.; Double_t tesla = 10 * kilogauss; ShipMuonShield::~ShipMuonShield() {} -ShipMuonShield::ShipMuonShield() : FairModule("ShipMuonShield", "") {} +ShipMuonShield::ShipMuonShield() + : FairModule("ShipMuonShield", "") +{} ShipMuonShield::ShipMuonShield(TString geofile, Double_t floor, - const Int_t withCoMagnet, const Bool_t StepGeo, - const Bool_t WithConstAbsorberField, const Bool_t WithConstShieldField) - : FairModule("MuonShield", "ShipMuonShield") + const Int_t withCoMagnet, + const Bool_t StepGeo, + const Bool_t WithConstAbsorberField, + const Bool_t WithConstShieldField) + : FairModule("MuonShield", "ShipMuonShield") { - fWithConstAbsorberField = WithConstAbsorberField; - fWithConstShieldField = WithConstShieldField; - fStepGeo = StepGeo; - fWithCoMagnet = withCoMagnet; - fGeofile = geofile; - auto f = TFile::Open(geofile, "read"); - TVectorT params; - params.Read("params"); - Double_t LE = 7 * m; - fDesign = 8; - fSC_mag = false; - fField = 1.7; - dZ0 = 1 * m; - dZ1 = 0.4 * m; - dZ2 = 2.31 * m; - dZ3 = params[2]; - dZ4 = params[3]; - dZ5 = params[4]; - dZ6 = params[5]; - dZ7 = params[6]; - dZ8 = params[7]; - fMuonShieldLength = 2 * (dZ1 + dZ2 + dZ3 + dZ4 + dZ5 + dZ6 + dZ7 + dZ8) + LE; - - fFloor = floor; - fSupport = false; - - Double_t Z = -25 * m - fMuonShieldLength / 2.; - - zEndOfAbsorb = Z + - fMuonShieldLength / 2.; + fWithConstAbsorberField = WithConstAbsorberField; + fWithConstShieldField = WithConstShieldField; + fStepGeo = StepGeo; + fWithCoMagnet = withCoMagnet; + fGeofile = geofile; + auto f = TFile::Open(geofile, "read"); + TVectorT params; + params.Read("params"); + Double_t LE = 7 * m; + fDesign = 8; + fSC_mag = false; + fField = 1.7; + dZ0 = 1 * m; + dZ1 = 0.4 * m; + dZ2 = 2.31 * m; + dZ3 = params[2]; + dZ4 = params[3]; + dZ5 = params[4]; + dZ6 = params[5]; + dZ7 = params[6]; + dZ8 = params[7]; + fMuonShieldLength = 2 * (dZ1 + dZ2 + dZ3 + dZ4 + dZ5 + dZ6 + dZ7 + dZ8) + LE; + + fFloor = floor; + fSupport = false; + + Double_t Z = -25 * m - fMuonShieldLength / 2.; + + zEndOfAbsorb = Z + -fMuonShieldLength / 2.; } ShipMuonShield::ShipMuonShield(TVectorT in_params, -Double_t floor, const Int_t withCoMagnet, const Bool_t StepGeo, const Bool_t WithConstAbsorberField, const Bool_t WithConstShieldField) - : FairModule("MuonShield", "ShipMuonShield") + Double_t floor, + const Int_t withCoMagnet, + const Bool_t StepGeo, + const Bool_t WithConstAbsorberField, + const Bool_t WithConstShieldField) + : FairModule("MuonShield", "ShipMuonShield") { - for(int i = 0; i < 56; i++){ - shield_params.push_back(in_params[i]); - } - fWithConstAbsorberField = WithConstAbsorberField; - fWithConstShieldField = WithConstShieldField; - fStepGeo = StepGeo; - fWithCoMagnet = withCoMagnet; - Double_t LE = 7 * m; - fDesign = 8; - fSC_mag = true; - fField = 1.7; - dZ0 = 1 * m; - dZ1 = 0.4 * m; - dZ2 = 2.31 * m; - dZ3 = in_params[2]; - dZ4 = in_params[3]; - dZ5 = in_params[4]; - dZ6 = in_params[5]; - dZ7 = in_params[6]; - dZ8 = in_params[7]; - fMuonShieldLength = 2 * (dZ1 + dZ2 + dZ3 + dZ4 + dZ5 + dZ6 + dZ7 + dZ8) + LE; - - fFloor = floor; - fSupport = false; - - Double_t Z = -25 * m - fMuonShieldLength / 2.; - - zEndOfAbsorb = Z + - fMuonShieldLength / 2.; + for (int i = 0; i < 56; i++) { + shield_params.push_back(in_params[i]); + } + fWithConstAbsorberField = WithConstAbsorberField; + fWithConstShieldField = WithConstShieldField; + fStepGeo = StepGeo; + fWithCoMagnet = withCoMagnet; + Double_t LE = 7 * m; + fDesign = 8; + fSC_mag = true; + fField = 1.7; + dZ0 = 1 * m; + dZ1 = 0.4 * m; + dZ2 = 2.31 * m; + dZ3 = in_params[2]; + dZ4 = in_params[3]; + dZ5 = in_params[4]; + dZ6 = in_params[5]; + dZ7 = in_params[6]; + dZ8 = in_params[7]; + fMuonShieldLength = 2 * (dZ1 + dZ2 + dZ3 + dZ4 + dZ5 + dZ6 + dZ7 + dZ8) + LE; + + fFloor = floor; + fSupport = false; + + Double_t Z = -25 * m - fMuonShieldLength / 2.; + + zEndOfAbsorb = Z + -fMuonShieldLength / 2.; } -ShipMuonShield::ShipMuonShield(const char* name, const Int_t Design, const char* Title, - Double_t Z, Double_t L0, Double_t L1, Double_t L2, Double_t L3, Double_t L4, Double_t L5, Double_t L6, - Double_t L7, Double_t L8, Double_t gap, Double_t LE, Double_t, Double_t floor, Double_t field, - const Int_t withCoMagnet, const Bool_t StepGeo, - const Bool_t WithConstAbsorberField, const Bool_t WithConstShieldField) - : FairModule(name ,Title) +ShipMuonShield::ShipMuonShield(const char* name, + const Int_t Design, + const char* Title, + Double_t Z, + Double_t L0, + Double_t L1, + Double_t L2, + Double_t L3, + Double_t L4, + Double_t L5, + Double_t L6, + Double_t L7, + Double_t L8, + Double_t gap, + Double_t LE, + Double_t, + Double_t floor, + Double_t field, + const Int_t withCoMagnet, + const Bool_t StepGeo, + const Bool_t WithConstAbsorberField, + const Bool_t WithConstShieldField) + : FairModule(name, Title) { - fDesign = Design; - fField = field; - fSC_mag = false; - fGeofile = ""; - fWithConstAbsorberField = WithConstAbsorberField; - fWithConstShieldField = WithConstShieldField; - fStepGeo = StepGeo; - fWithCoMagnet = withCoMagnet; - if (fDesign < 7){ - Fatal("ShipMuonShield","Design %i not anymore supported",fDesign); - } else if (fDesign >= 7){ - dZ1 = L1; - dZ2 = L2; - dZ3 = L3; - dZ4 = L4; - dZ5 = L5; - dZ6 = L6; - dZ7 = L7; - dZ8 = L8; - fMuonShieldLength = - 2 * (dZ1 + dZ2 + dZ3 + dZ4 + dZ5 + dZ6 + dZ7 + dZ8) + LE; - } - - fFloor = floor; - - zEndOfAbsorb = Z - fMuonShieldLength/2.; - - fSupport = false; + fDesign = Design; + fField = field; + fSC_mag = false; + fGeofile = ""; + fWithConstAbsorberField = WithConstAbsorberField; + fWithConstShieldField = WithConstShieldField; + fStepGeo = StepGeo; + fWithCoMagnet = withCoMagnet; + if (fDesign < 7) { + Fatal("ShipMuonShield", "Design %i not anymore supported", fDesign); + } else if (fDesign >= 7) { + dZ1 = L1; + dZ2 = L2; + dZ3 = L3; + dZ4 = L4; + dZ5 = L5; + dZ6 = L6; + dZ7 = L7; + dZ8 = L8; + fMuonShieldLength = 2 * (dZ1 + dZ2 + dZ3 + dZ4 + dZ5 + dZ6 + dZ7 + dZ8) + LE; + } + + fFloor = floor; + + zEndOfAbsorb = Z - fMuonShieldLength / 2.; + + fSupport = false; } // ----- Private method InitMedium Int_t ShipMuonShield::InitMedium(TString name) { - static FairGeoLoader *geoLoad=FairGeoLoader::Instance(); - static FairGeoInterface *geoFace=geoLoad->getGeoInterface(); - static FairGeoMedia *media=geoFace->getMedia(); - static FairGeoBuilder *geoBuild=geoLoad->getGeoBuilder(); - - FairGeoMedium *ShipMedium=media->getMedium(name); - - if (!ShipMedium) - Fatal("InitMedium","Material %s not defined in media file.", name.Data()); - TGeoMedium* medium=gGeoManager->GetMedium(name); - if (medium) - return ShipMedium->getMediumIndex(); - return geoBuild->createMedium(ShipMedium); + static FairGeoLoader* geoLoad = FairGeoLoader::Instance(); + static FairGeoInterface* geoFace = geoLoad->getGeoInterface(); + static FairGeoMedia* media = geoFace->getMedia(); + static FairGeoBuilder* geoBuild = geoLoad->getGeoBuilder(); + + FairGeoMedium* ShipMedium = media->getMedium(name); + + if (!ShipMedium) + Fatal("InitMedium", "Material %s not defined in media file.", name.Data()); + TGeoMedium* medium = gGeoManager->GetMedium(name); + if (medium) + return ShipMedium->getMediumIndex(); + return geoBuild->createMedium(ShipMedium); } -void ShipMuonShield::CreateTube(TString tubeName, TGeoMedium *medium, - Double_t dX, Double_t dY, Double_t dZ, - Int_t color, TGeoVolume *tShield, - Double_t x_translation, Double_t y_translation, - Double_t z_translation) { - TGeoVolume *absorber = gGeoManager->MakeTube(tubeName, medium, dX, dY, dZ); - absorber->SetLineColor(color); - tShield->AddNode( - absorber, 1, - new TGeoTranslation(x_translation, y_translation, z_translation)); +void ShipMuonShield::CreateTube(TString tubeName, + TGeoMedium* medium, + Double_t dX, + Double_t dY, + Double_t dZ, + Int_t color, + TGeoVolume* tShield, + Double_t x_translation, + Double_t y_translation, + Double_t z_translation) +{ + TGeoVolume* absorber = gGeoManager->MakeTube(tubeName, medium, dX, dY, dZ); + absorber->SetLineColor(color); + tShield->AddNode(absorber, 1, new TGeoTranslation(x_translation, y_translation, z_translation)); } -void ShipMuonShield::CreateArb8(TString arbName, TGeoMedium *medium, - Double_t dZ, std::array corners, - Int_t color, TGeoUniformMagField *magField, - TGeoVolume *tShield, Double_t x_translation, - Double_t y_translation, - Double_t z_translation) { - TGeoVolume *magF = - gGeoManager->MakeArb8(arbName, medium, dZ, corners.data()); - magF->SetLineColor(color); - if (arbName.Contains("Absorb")) { - if (fWithConstAbsorberField) { - magF->SetField(magField); - } - } else if (fWithConstShieldField) { - magF->SetField(magField); - } - tShield->AddNode(magF, 1, new TGeoTranslation(x_translation, y_translation, - z_translation)); +void ShipMuonShield::CreateArb8(TString arbName, + TGeoMedium* medium, + Double_t dZ, + std::array corners, + Int_t color, + TGeoUniformMagField* magField, + TGeoVolume* tShield, + Double_t x_translation, + Double_t y_translation, + Double_t z_translation) +{ + TGeoVolume* magF = gGeoManager->MakeArb8(arbName, medium, dZ, corners.data()); + magF->SetLineColor(color); + if (arbName.Contains("Absorb")) { + if (fWithConstAbsorberField) { + magF->SetField(magField); + } + } else if (fWithConstShieldField) { + magF->SetField(magField); + } + tShield->AddNode(magF, 1, new TGeoTranslation(x_translation, y_translation, z_translation)); } -void ShipMuonShield::CreateArb8(TString arbName, TGeoMedium *medium, - Double_t dZ, std::array corners, - Int_t color, TGeoUniformMagField *magField, - TGeoVolume *tShield, Double_t x_translation, - Double_t y_translation, - Double_t z_translation, - Bool_t stepGeo) { - if (!stepGeo) - { - CreateArb8 (arbName, medium, dZ, corners, color, magField, tShield, x_translation, y_translation, z_translation); - return; - } - Double_t partLength = 0.5; - Int_t zParts = std::ceil(2.0*dZ/m/partLength); - Double_t finalCorners[zParts][16]; - Double_t dxdy[4][2]; - Double_t dZp = dZ/Double_t(zParts); - - for (int i = 0; i < 4; ++i) - { - dxdy[i][0] = (corners[8+2*i] - corners[0+2*i])/Double_t(zParts); - dxdy[i][1] = (corners[9+2*i] - corners[1+2*i])/Double_t(zParts); - } - - std::copy(corners.data() + 0, corners.data() + 8, finalCorners[0]); - - for (int i = 0; i < zParts; ++i) - { - for (int k = 0; k < 4; ++k) - { - finalCorners[i][8+2*k] = finalCorners[i][0+2*k] + dxdy[k][0]; - finalCorners[i][9+2*k] = finalCorners[i][1+2*k] + dxdy[k][1]; +void ShipMuonShield::CreateArb8(TString arbName, + TGeoMedium* medium, + Double_t dZ, + std::array corners, + Int_t color, + TGeoUniformMagField* magField, + TGeoVolume* tShield, + Double_t x_translation, + Double_t y_translation, + Double_t z_translation, + Bool_t stepGeo) +{ + if (!stepGeo) { + CreateArb8(arbName, medium, dZ, corners, color, magField, tShield, x_translation, y_translation, z_translation); + return; } - if (i != zParts-1) - { - std::copy(finalCorners[i] + 8, finalCorners[i] + 16, finalCorners[i+1]); + Double_t partLength = 0.5; + Int_t zParts = std::ceil(2.0 * dZ / m / partLength); + Double_t finalCorners[zParts][16]; + Double_t dxdy[4][2]; + Double_t dZp = dZ / Double_t(zParts); + + for (int i = 0; i < 4; ++i) { + dxdy[i][0] = (corners[8 + 2 * i] - corners[0 + 2 * i]) / Double_t(zParts); + dxdy[i][1] = (corners[9 + 2 * i] - corners[1 + 2 * i]) / Double_t(zParts); + } + + std::copy(corners.data() + 0, corners.data() + 8, finalCorners[0]); + + for (int i = 0; i < zParts; ++i) { + for (int k = 0; k < 4; ++k) { + finalCorners[i][8 + 2 * k] = finalCorners[i][0 + 2 * k] + dxdy[k][0]; + finalCorners[i][9 + 2 * k] = finalCorners[i][1 + 2 * k] + dxdy[k][1]; + } + if (i != zParts - 1) { + std::copy(finalCorners[i] + 8, finalCorners[i] + 16, finalCorners[i + 1]); + } } - } - - for (int i = 0; i < zParts; ++i) - { - for (int k = 0; k < 4; ++k) - { - finalCorners[i][8+2*k] = finalCorners[i][0+2*k] = (finalCorners[i][0+2*k] + finalCorners[i][8+2*k]) / 2.0; - finalCorners[i][9+2*k] = finalCorners[i][1+2*k] = (finalCorners[i][9+2*k] + finalCorners[i][1+2*k]) / 2.0; + + for (int i = 0; i < zParts; ++i) { + for (int k = 0; k < 4; ++k) { + finalCorners[i][8 + 2 * k] = finalCorners[i][0 + 2 * k] = + (finalCorners[i][0 + 2 * k] + finalCorners[i][8 + 2 * k]) / 2.0; + finalCorners[i][9 + 2 * k] = finalCorners[i][1 + 2 * k] = + (finalCorners[i][9 + 2 * k] + finalCorners[i][1 + 2 * k]) / 2.0; + } } - } - std::vector magF; + std::vector magF; - for (int i = 0; i < zParts; ++i) - { - magF.push_back(gGeoManager->MakeArb8(arbName + '_' + std::to_string(i), medium, dZp - 0.00001*m, finalCorners[i])); - magF[i]->SetLineColor(color); - if (fWithConstShieldField) { - magF[i]->SetField(magField); + for (int i = 0; i < zParts; ++i) { + magF.push_back( + gGeoManager->MakeArb8(arbName + '_' + std::to_string(i), medium, dZp - 0.00001 * m, finalCorners[i])); + magF[i]->SetLineColor(color); + if (fWithConstShieldField) { + magF[i]->SetField(magField); + } } - } - for (int i = 0; i < zParts; ++i) - { - Double_t true_z_translation = z_translation + 2.0 * Double_t(i) * dZp - dZ + dZp; - tShield->AddNode(magF[i], 1, new TGeoTranslation(x_translation, y_translation, true_z_translation)); - } + for (int i = 0; i < zParts; ++i) { + Double_t true_z_translation = z_translation + 2.0 * Double_t(i) * dZp - dZ + dZp; + tShield->AddNode(magF[i], 1, new TGeoTranslation(x_translation, y_translation, true_z_translation)); + } } -void ShipMuonShield::CreateMagnet(TString magnetName,TGeoMedium* medium,TGeoVolume *tShield,TGeoUniformMagField *fields[4],FieldDirection fieldDirection, - Double_t dX, Double_t dY, Double_t dX2, Double_t dY2, Double_t dZ, - Double_t middleGap,Double_t middleGap2, - Double_t HmainSideMag, Double_t HmainSideMag2, - Double_t gap,Double_t gap2, Double_t Z, Bool_t NotMagnet, - Bool_t stepGeo, Bool_t SC_key = false) - { - Double_t coil_gap,coil_gap2; - Int_t color[4] = {45,31,30,38}; +void ShipMuonShield::CreateMagnet(TString magnetName, + TGeoMedium* medium, + TGeoVolume* tShield, + TGeoUniformMagField* fields[4], + FieldDirection fieldDirection, + Double_t dX, + Double_t dY, + Double_t dX2, + Double_t dY2, + Double_t dZ, + Double_t middleGap, + Double_t middleGap2, + Double_t HmainSideMag, + Double_t HmainSideMag2, + Double_t gap, + Double_t gap2, + Double_t Z, + Bool_t NotMagnet, + Bool_t stepGeo, + Bool_t SC_key = false) +{ + Double_t coil_gap, coil_gap2; + Int_t color[4] = {45, 31, 30, 38}; if (NotMagnet) { - coil_gap = gap; - coil_gap2 = gap2; + coil_gap = gap; + coil_gap2 = gap2; } else if (fDesign > 7) { - // Assuming 0.5A/mm^2 and 10000At needed, about 200cm^2 gaps are necessary - // Current design safely above this. Will consult with MISiS to get a better minimum. - gap = std::ceil(std::max(100. / dY, gap)); - gap2 = std::ceil(std::max(100. / dY2, gap2)); - coil_gap = gap; - coil_gap2 = gap2; + // Assuming 0.5A/mm^2 and 10000At needed, about 200cm^2 gaps are necessary + // Current design safely above this. Will consult with MISiS to get a better minimum. + gap = std::ceil(std::max(100. / dY, gap)); + gap2 = std::ceil(std::max(100. / dY2, gap2)); + coil_gap = gap; + coil_gap2 = gap2; } else { - coil_gap = std::max(20., gap); - coil_gap2 = std::max(20., gap2); - gap = std::max(2., gap); - gap2 = std::max(2., gap2); + coil_gap = std::max(20., gap); + coil_gap2 = std::max(20., gap2); + gap = std::max(2., gap); + gap2 = std::max(2., gap2); } - Double_t anti_overlap = 0.1; // gap between fields in the - // corners for mitred joints - // (Geant goes crazy when - // they touch each other) - - std::array cornersMainL = { - middleGap, -(dY + dX - anti_overlap), - middleGap, dY + dX - anti_overlap, - dX + middleGap, dY - anti_overlap, - dX + middleGap, -(dY - anti_overlap), - middleGap2, -(dY2 + dX2 - anti_overlap), - middleGap2, dY2 + dX2 - anti_overlap, - dX2 + middleGap2, dY2 - anti_overlap, - dX2 + middleGap2, -(dY2 - anti_overlap) - }; + Double_t anti_overlap = 0.1; // gap between fields in the + // corners for mitred joints + // (Geant goes crazy when + // they touch each other) + + std::array cornersMainL = {middleGap, + -(dY + dX - anti_overlap), + middleGap, + dY + dX - anti_overlap, + dX + middleGap, + dY - anti_overlap, + dX + middleGap, + -(dY - anti_overlap), + middleGap2, + -(dY2 + dX2 - anti_overlap), + middleGap2, + dY2 + dX2 - anti_overlap, + dX2 + middleGap2, + dY2 - anti_overlap, + dX2 + middleGap2, + -(dY2 - anti_overlap)}; std::array cornersTL = {middleGap + dX, dY, @@ -309,124 +360,149 @@ void ShipMuonShield::CreateMagnet(TString magnetName,TGeoMedium* medium,TGeoVolu dX2 + middleGap2 + coil_gap2, dY2}; - std::array cornersMainSideL = - fDesign == 7 ? - std::array{ - dX + middleGap + gap, -HmainSideMag, - dX + middleGap + gap, HmainSideMag, - 2 * dX + middleGap + gap, HmainSideMag, - 2 * dX + middleGap + gap, -HmainSideMag, - dX2 + middleGap2 + gap2, -HmainSideMag2, - dX2 + middleGap2 + gap2, HmainSideMag2, - 2 * dX2 + middleGap2 + gap2, HmainSideMag2, - 2 * dX2 + middleGap2 + gap2, -HmainSideMag2 - } : - std::array{ - dX + middleGap + gap, -(dY - anti_overlap), - dX + middleGap + gap, dY - anti_overlap, - 2 * dX + middleGap + gap, dY + dX - anti_overlap, - 2 * dX + middleGap + gap, -(dY + dX - anti_overlap), - dX2 + middleGap2 + gap2, -(dY2 - anti_overlap), - dX2 + middleGap2 + gap2, dY2 - anti_overlap, - 2 * dX2 + middleGap2 + gap2, dY2 + dX2 - anti_overlap, - 2 * dX2 + middleGap2 + gap2, -(dY2 + dX2 - anti_overlap) - }; + std::array cornersMainSideL = fDesign == 7 ? std::array{dX + middleGap + gap, + -HmainSideMag, + dX + middleGap + gap, + HmainSideMag, + 2 * dX + middleGap + gap, + HmainSideMag, + 2 * dX + middleGap + gap, + -HmainSideMag, + dX2 + middleGap2 + gap2, + -HmainSideMag2, + dX2 + middleGap2 + gap2, + HmainSideMag2, + 2 * dX2 + middleGap2 + gap2, + HmainSideMag2, + 2 * dX2 + middleGap2 + gap2, + -HmainSideMag2} + : std::array{dX + middleGap + gap, + -(dY - anti_overlap), + dX + middleGap + gap, + dY - anti_overlap, + 2 * dX + middleGap + gap, + dY + dX - anti_overlap, + 2 * dX + middleGap + gap, + -(dY + dX - anti_overlap), + dX2 + middleGap2 + gap2, + -(dY2 - anti_overlap), + dX2 + middleGap2 + gap2, + dY2 - anti_overlap, + 2 * dX2 + middleGap2 + gap2, + dY2 + dX2 - anti_overlap, + 2 * dX2 + middleGap2 + gap2, + -(dY2 + dX2 - anti_overlap)}; // SC part - if(SC_key){ - - cornersMainL = { - middleGap, -(dY + 3*dX - anti_overlap), - middleGap, dY + 3*dX - anti_overlap, - dX + middleGap, dY - anti_overlap, - dX + middleGap, -(dY - anti_overlap), - middleGap2, -(dY2 + 3*dX2 - anti_overlap), - middleGap2, dY2 + 3*dX2 - anti_overlap, - dX2 + middleGap2, dY2 - anti_overlap, - dX2 + middleGap2, -(dY2 - anti_overlap) - }; - - cornersTL = {middleGap + dX, - dY, - middleGap, - dY + 3*dX, - 4 * dX + middleGap + coil_gap, - dY + 3*dX, - dX + middleGap + coil_gap, - dY, - middleGap2 + dX2, - dY2, - middleGap2, - dY2 + 3*dX2, - 4 * dX2 + middleGap2 + coil_gap2, - dY2 + 3*dX2, - dX2 + middleGap2 + coil_gap2, - dY2}; - - cornersMainSideL = - fDesign == 7 ? - std::array{ - dX + middleGap + gap, -HmainSideMag, - dX + middleGap + gap, HmainSideMag, - 4 * dX + middleGap + gap, HmainSideMag, - 4 * dX + middleGap + gap, -HmainSideMag, - dX2 + middleGap2 + gap2, -HmainSideMag2, - dX2 + middleGap2 + gap2, HmainSideMag2, - 4 * dX2 + middleGap2 + gap2, HmainSideMag2, - 4 * dX2 + middleGap2 + gap2, -HmainSideMag2 - } : - std::array{ - dX + middleGap + gap, -(dY - anti_overlap), - dX + middleGap + gap, dY - anti_overlap, - 4 * dX + middleGap + gap, dY + 3*dX - anti_overlap, - 4 * dX + middleGap + gap, -(dY + 3*dX - anti_overlap), - dX2 + middleGap2 + gap2, -(dY2 - anti_overlap), - dX2 + middleGap2 + gap2, dY2 - anti_overlap, - 4 * dX2 + middleGap2 + gap2, dY2 + 3*dX2 - anti_overlap, - 4 * dX2 + middleGap2 + gap2, -(dY2 + 3*dX2 - anti_overlap) - }; - } - // END of SC part - std::array cornersMainR, cornersCLBA, - cornersMainSideR, cornersCLTA, cornersCRBA, - cornersCRTA, cornersTR, cornersBL, cornersBR; + if (SC_key) { + + cornersMainL = {middleGap, + -(dY + 3 * dX - anti_overlap), + middleGap, + dY + 3 * dX - anti_overlap, + dX + middleGap, + dY - anti_overlap, + dX + middleGap, + -(dY - anti_overlap), + middleGap2, + -(dY2 + 3 * dX2 - anti_overlap), + middleGap2, + dY2 + 3 * dX2 - anti_overlap, + dX2 + middleGap2, + dY2 - anti_overlap, + dX2 + middleGap2, + -(dY2 - anti_overlap)}; + + cornersTL = {middleGap + dX, + dY, + middleGap, + dY + 3 * dX, + 4 * dX + middleGap + coil_gap, + dY + 3 * dX, + dX + middleGap + coil_gap, + dY, + middleGap2 + dX2, + dY2, + middleGap2, + dY2 + 3 * dX2, + 4 * dX2 + middleGap2 + coil_gap2, + dY2 + 3 * dX2, + dX2 + middleGap2 + coil_gap2, + dY2}; + + cornersMainSideL = fDesign == 7 ? std::array{dX + middleGap + gap, + -HmainSideMag, + dX + middleGap + gap, + HmainSideMag, + 4 * dX + middleGap + gap, + HmainSideMag, + 4 * dX + middleGap + gap, + -HmainSideMag, + dX2 + middleGap2 + gap2, + -HmainSideMag2, + dX2 + middleGap2 + gap2, + HmainSideMag2, + 4 * dX2 + middleGap2 + gap2, + HmainSideMag2, + 4 * dX2 + middleGap2 + gap2, + -HmainSideMag2} + : std::array{dX + middleGap + gap, + -(dY - anti_overlap), + dX + middleGap + gap, + dY - anti_overlap, + 4 * dX + middleGap + gap, + dY + 3 * dX - anti_overlap, + 4 * dX + middleGap + gap, + -(dY + 3 * dX - anti_overlap), + dX2 + middleGap2 + gap2, + -(dY2 - anti_overlap), + dX2 + middleGap2 + gap2, + dY2 - anti_overlap, + 4 * dX2 + middleGap2 + gap2, + dY2 + 3 * dX2 - anti_overlap, + 4 * dX2 + middleGap2 + gap2, + -(dY2 + 3 * dX2 - anti_overlap)}; + } + // END of SC part + std::array cornersMainR, cornersCLBA, cornersMainSideR, cornersCLTA, cornersCRBA, cornersCRTA, + cornersTR, cornersBL, cornersBR; if (fDesign == 7) { - cornersCLBA = {dX + middleGap + gap, - -HmainSideMag, - 2 * dX + middleGap + gap, - -HmainSideMag, - 2 * dX + middleGap + coil_gap, - -(dY + dX - anti_overlap), - dX + middleGap + coil_gap, - -(dY - anti_overlap), - dX2 + middleGap2 + gap2, - -HmainSideMag2, - 2 * dX2 + middleGap2 + gap2, - -HmainSideMag2, - 2 * dX2 + middleGap2 + coil_gap2, - -(dY2 + dX2 - anti_overlap), - dX2 + middleGap2 + coil_gap2, - -(dY2 - anti_overlap)}; + cornersCLBA = {dX + middleGap + gap, + -HmainSideMag, + 2 * dX + middleGap + gap, + -HmainSideMag, + 2 * dX + middleGap + coil_gap, + -(dY + dX - anti_overlap), + dX + middleGap + coil_gap, + -(dY - anti_overlap), + dX2 + middleGap2 + gap2, + -HmainSideMag2, + 2 * dX2 + middleGap2 + gap2, + -HmainSideMag2, + 2 * dX2 + middleGap2 + coil_gap2, + -(dY2 + dX2 - anti_overlap), + dX2 + middleGap2 + coil_gap2, + -(dY2 - anti_overlap)}; } // Use symmetries to define remaining magnets for (int i = 0; i < 16; ++i) { - cornersMainR[i] = -cornersMainL[i]; - cornersMainSideR[i] = -cornersMainSideL[i]; - cornersCRTA[i] = -cornersCLBA[i]; - cornersBR[i] = -cornersTL[i]; + cornersMainR[i] = -cornersMainL[i]; + cornersMainSideR[i] = -cornersMainSideL[i]; + cornersCRTA[i] = -cornersCLBA[i]; + cornersBR[i] = -cornersTL[i]; } // Need to change order as corners need to be defined clockwise for (int i = 0, j = 4; i < 8; ++i) { - j = (11 - i) % 8; - cornersCLTA[2 * j] = cornersCLBA[2 * i]; - cornersCLTA[2 * j + 1] = -cornersCLBA[2 * i + 1]; - cornersTR[2 * j] = -cornersTL[2 * i]; - cornersTR[2 * j + 1] = cornersTL[2 * i + 1]; + j = (11 - i) % 8; + cornersCLTA[2 * j] = cornersCLBA[2 * i]; + cornersCLTA[2 * j + 1] = -cornersCLBA[2 * i + 1]; + cornersTR[2 * j] = -cornersTL[2 * i]; + cornersTR[2 * j + 1] = cornersTL[2 * i + 1]; } for (int i = 0; i < 16; ++i) { - cornersCRBA[i] = -cornersCLTA[i]; - cornersBL[i] = -cornersTR[i]; + cornersCRBA[i] = -cornersCLTA[i]; + cornersBL[i] = -cornersTR[i]; } TString str1L = "_MiddleMagL"; @@ -442,458 +518,583 @@ void ShipMuonShield::CreateMagnet(TString magnetName,TGeoMedium* medium,TGeoVolu TString str10 = "_MagBotLeft"; TString str11 = "_MagBotRight"; - switch (fieldDirection){ - - case FieldDirection::up: - CreateArb8(magnetName + str1L, medium, dZ, cornersMainL, color[0], fields[0], tShield, 0, 0, Z, stepGeo); - CreateArb8(magnetName + str1R, medium, dZ, cornersMainR, color[0], fields[0], tShield, 0, 0, Z, stepGeo); - CreateArb8(magnetName + str2, medium, dZ, cornersMainSideL, color[1], fields[1], tShield, 0, 0, Z, stepGeo); - CreateArb8(magnetName + str3, medium, dZ, cornersMainSideR, color[1], fields[1], tShield, 0, 0, Z, stepGeo); - if (fDesign == 7) { - CreateArb8(magnetName + str4, medium, dZ, cornersCLBA, color[1], fields[1], tShield, 0, 0, Z, stepGeo); - CreateArb8(magnetName + str5, medium, dZ, cornersCLTA, color[1], fields[1], tShield, 0, 0, Z, stepGeo); - CreateArb8(magnetName + str6, medium, dZ, cornersCRTA, color[1], fields[1], tShield, 0, 0, Z, stepGeo); - CreateArb8(magnetName + str7, medium, dZ, cornersCRBA, color[1], fields[1], tShield, 0, 0, Z, stepGeo); - } - CreateArb8(magnetName + str8, medium, dZ, cornersTL, color[3], fields[3], tShield, 0, 0, Z, stepGeo); - CreateArb8(magnetName + str9, medium, dZ, cornersTR, color[2], fields[2], tShield, 0, 0, Z, stepGeo); - CreateArb8(magnetName + str10, medium, dZ, cornersBL, color[2], fields[2], tShield, 0, 0, Z, stepGeo); - CreateArb8(magnetName + str11, medium, dZ, cornersBR, color[3], fields[3], tShield, 0, 0, Z, stepGeo); - break; - case FieldDirection::down: - CreateArb8(magnetName + str1L, medium, dZ, cornersMainL, color[1], fields[1], tShield, 0, 0, Z, stepGeo); - CreateArb8(magnetName + str1R, medium, dZ, cornersMainR, color[1], fields[1], tShield, 0, 0, Z, stepGeo); - CreateArb8(magnetName + str2, medium, dZ, cornersMainSideL, color[0], fields[0], tShield, 0, 0, Z, stepGeo); - CreateArb8(magnetName + str3, medium, dZ, cornersMainSideR, color[0], fields[0], tShield, 0, 0, Z, stepGeo); - if (fDesign == 7) { - CreateArb8(magnetName + str4, medium, dZ, cornersCLBA, color[0], fields[0], tShield, 0, 0, Z, stepGeo); - CreateArb8(magnetName + str5, medium, dZ, cornersCLTA, color[0], fields[0], tShield, 0, 0, Z, stepGeo); - CreateArb8(magnetName + str6, medium, dZ, cornersCRTA, color[0], fields[0], tShield, 0, 0, Z, stepGeo); - CreateArb8(magnetName + str7, medium, dZ, cornersCRBA, color[0], fields[0], tShield, 0, 0, Z, stepGeo); - } - CreateArb8(magnetName + str8, medium, dZ, cornersTL, color[2], fields[2], tShield, 0, 0, Z, stepGeo); - CreateArb8(magnetName + str9, medium, dZ, cornersTR, color[3], fields[3], tShield, 0, 0, Z, stepGeo); - CreateArb8(magnetName + str10, medium, dZ, cornersBL, color[3], fields[3], tShield, 0, 0, Z, stepGeo); - CreateArb8(magnetName + str11, medium, dZ, cornersBR, color[2], fields[2], tShield, 0, 0, Z, stepGeo); - break; - } - } - -Int_t ShipMuonShield::Initialize(std::vector &magnetName, - std::vector &fieldDirection, - std::vector &dXIn, std::vector &dYIn, - std::vector &dXOut, std::vector &dYOut, - std::vector &dZ, std::vector &midGapIn, - std::vector &midGapOut, - std::vector &HmainSideMagIn, - std::vector &HmainSideMagOut, - std::vector &gapIn, std::vector &gapOut, - std::vector &Z) { - - const Int_t nMagnets = 9; - magnetName.reserve(nMagnets); - fieldDirection.reserve(nMagnets); - for (auto i : - {&dXIn, &dXOut, &dYIn, &dYOut, &dZ, &midGapIn, &midGapOut, - &HmainSideMagIn, &HmainSideMagOut, &gapIn, &gapOut, &Z}) { - i->reserve(nMagnets); - } - - Double_t zgap = 10 * cm; // fixed distance between magnets in Z-axis - - if (fDesign == 8) { - - magnetName = {"MagnAbsorb1", "MagnAbsorb2", "Magn1", "Magn2", "Magn3", - "Magn4", "Magn5", "Magn6", "Magn7"}; - - fieldDirection = { - FieldDirection::up, FieldDirection::up, FieldDirection::up, - FieldDirection::up, FieldDirection::up, FieldDirection::down, - FieldDirection::down, FieldDirection::down, FieldDirection::down, - }; - - std::vector params; - if (!fSC_mag) - { - TVectorT paramsR; - auto f = TFile::Open(fGeofile, "read"); - paramsR.Read("params"); - for (int i = 0; i < 56; i++){params.push_back(paramsR[i]);} - }else{ - params = shield_params; + switch (fieldDirection) { + + case FieldDirection::up: + CreateArb8(magnetName + str1L, medium, dZ, cornersMainL, color[0], fields[0], tShield, 0, 0, Z, stepGeo); + CreateArb8(magnetName + str1R, medium, dZ, cornersMainR, color[0], fields[0], tShield, 0, 0, Z, stepGeo); + CreateArb8(magnetName + str2, medium, dZ, cornersMainSideL, color[1], fields[1], tShield, 0, 0, Z, stepGeo); + CreateArb8(magnetName + str3, medium, dZ, cornersMainSideR, color[1], fields[1], tShield, 0, 0, Z, stepGeo); + if (fDesign == 7) { + CreateArb8(magnetName + str4, medium, dZ, cornersCLBA, color[1], fields[1], tShield, 0, 0, Z, stepGeo); + CreateArb8(magnetName + str5, medium, dZ, cornersCLTA, color[1], fields[1], tShield, 0, 0, Z, stepGeo); + CreateArb8(magnetName + str6, medium, dZ, cornersCRTA, color[1], fields[1], tShield, 0, 0, Z, stepGeo); + CreateArb8(magnetName + str7, medium, dZ, cornersCRBA, color[1], fields[1], tShield, 0, 0, Z, stepGeo); + } + CreateArb8(magnetName + str8, medium, dZ, cornersTL, color[3], fields[3], tShield, 0, 0, Z, stepGeo); + CreateArb8(magnetName + str9, medium, dZ, cornersTR, color[2], fields[2], tShield, 0, 0, Z, stepGeo); + CreateArb8(magnetName + str10, medium, dZ, cornersBL, color[2], fields[2], tShield, 0, 0, Z, stepGeo); + CreateArb8(magnetName + str11, medium, dZ, cornersBR, color[3], fields[3], tShield, 0, 0, Z, stepGeo); + break; + case FieldDirection::down: + CreateArb8(magnetName + str1L, medium, dZ, cornersMainL, color[1], fields[1], tShield, 0, 0, Z, stepGeo); + CreateArb8(magnetName + str1R, medium, dZ, cornersMainR, color[1], fields[1], tShield, 0, 0, Z, stepGeo); + CreateArb8(magnetName + str2, medium, dZ, cornersMainSideL, color[0], fields[0], tShield, 0, 0, Z, stepGeo); + CreateArb8(magnetName + str3, medium, dZ, cornersMainSideR, color[0], fields[0], tShield, 0, 0, Z, stepGeo); + if (fDesign == 7) { + CreateArb8(magnetName + str4, medium, dZ, cornersCLBA, color[0], fields[0], tShield, 0, 0, Z, stepGeo); + CreateArb8(magnetName + str5, medium, dZ, cornersCLTA, color[0], fields[0], tShield, 0, 0, Z, stepGeo); + CreateArb8(magnetName + str6, medium, dZ, cornersCRTA, color[0], fields[0], tShield, 0, 0, Z, stepGeo); + CreateArb8(magnetName + str7, medium, dZ, cornersCRBA, color[0], fields[0], tShield, 0, 0, Z, stepGeo); + } + CreateArb8(magnetName + str8, medium, dZ, cornersTL, color[2], fields[2], tShield, 0, 0, Z, stepGeo); + CreateArb8(magnetName + str9, medium, dZ, cornersTR, color[3], fields[3], tShield, 0, 0, Z, stepGeo); + CreateArb8(magnetName + str10, medium, dZ, cornersBL, color[3], fields[3], tShield, 0, 0, Z, stepGeo); + CreateArb8(magnetName + str11, medium, dZ, cornersBR, color[2], fields[2], tShield, 0, 0, Z, stepGeo); + break; } +} - const int offset = 7; - - dXIn[0] = 0.4 * m; - dXOut[0] = 0.40 * m; - gapIn[0] = 0.1 * mm; - dYIn[0] = 1.5 * m; - dYOut[0] = 1.5 * m; - gapOut[0] = 0.1 * mm; - dXIn[1] = 0.5 * m; - dXOut[1] = 0.5 * m; - gapIn[1] = 0.02 * m; - dYIn[1] = 1.3 * m; - dYOut[1] = 1.3 * m; - gapOut[1] = 0.02 * m; - - for (Int_t i = 2; i < nMagnets - 1; ++i) { - dXIn[i] = params[offset + i * 6 + 1]; - dXOut[i] = params[offset + i * 6 + 2]; - dYIn[i] = params[offset + i * 6 + 3]; - dYOut[i] = params[offset + i * 6 + 4]; - gapIn[i] = params[offset + i * 6 + 5]; - gapOut[i] = params[offset + i * 6 + 6]; - } +Int_t ShipMuonShield::Initialize(std::vector& magnetName, + std::vector& fieldDirection, + std::vector& dXIn, + std::vector& dYIn, + std::vector& dXOut, + std::vector& dYOut, + std::vector& dZ, + std::vector& midGapIn, + std::vector& midGapOut, + std::vector& HmainSideMagIn, + std::vector& HmainSideMagOut, + std::vector& gapIn, + std::vector& gapOut, + std::vector& Z) +{ - dZ[0] = dZ1 - zgap / 2; - Z[0] = zEndOfAbsorb + dZ[0] + zgap; - dZ[1] = dZ2 - zgap / 2; - Z[1] = Z[0] + dZ[0] + dZ[1] + zgap; - dZ[2] = dZ3 - zgap / 2; - Z[2] = Z[1] + dZ[1] + dZ[2] + 2 * zgap; - dZ[3] = dZ4 - zgap / 2; - Z[3] = Z[2] + dZ[2] + dZ[3] + zgap; - dZ[4] = dZ5 - zgap / 2; - Z[4] = Z[3] + dZ[3] + dZ[4] + zgap; - dZ[5] = dZ6 - zgap / 2; - Z[5] = Z[4] + dZ[4] + dZ[5] + zgap; - dZ[6] = dZ7 - zgap / 2; - Z[6] = Z[5] + dZ[5] + dZ[6] + zgap; - dZ[7] = dZ8 - zgap / 2; - Z[7] = Z[6] + dZ[6] + dZ[7] + zgap; - - dXIn[8] = dXOut[7]; - dYIn[8] = dYOut[7]; - dXOut[8] = dXIn[8]; - dYOut[8] = dYIn[8]; - gapIn[8] = gapOut[7]; - gapOut[8] = gapIn[8]; - dZ[8] = 0.1 * m; - Z[8] = Z[7] + dZ[7] + dZ[8]; - - for (int i = 0; i < nMagnets; ++i) { - midGapIn[i] = 0.; - midGapOut[i] = 0.; - HmainSideMagIn[i] = dYIn[i] / 2; - HmainSideMagOut[i] = dYOut[i] / 2; + const Int_t nMagnets = 9; + magnetName.reserve(nMagnets); + fieldDirection.reserve(nMagnets); + for (auto i : {&dXIn, + &dXOut, + &dYIn, + &dYOut, + &dZ, + &midGapIn, + &midGapOut, + &HmainSideMagIn, + &HmainSideMagOut, + &gapIn, + &gapOut, + &Z}) { + i->reserve(nMagnets); } - } else if (fDesign == 9) { - magnetName = {"MagnAbsorb1", "MagnAbsorb2", "Magn1", "Magn2", "Magn3", - "Magn4", "Magn5", "Magn6", "Magn7" - }; - - fieldDirection = { - FieldDirection::up, FieldDirection::up, FieldDirection::up, - FieldDirection::up, FieldDirection::up, FieldDirection::down, - FieldDirection::down, FieldDirection::down, FieldDirection::down, - }; - - dXIn[0] = 0.4 * m; - dXOut[0] = 0.40 * m; - dYIn[0] = 1.5 * m; - dYOut[0] = 1.5 * m; - gapIn[0] = 0.1 * mm; - gapOut[0] = 0.1 * mm; - dZ[0] = dZ1 - zgap / 2; - Z[0] = zEndOfAbsorb + dZ[0] + zgap; - - dXIn[1] = 0.5 * m; - dXOut[1] = 0.5 * m; - dYIn[1] = 1.3 * m; - dYOut[1] = 1.3 * m; - gapIn[1] = 0.02 * m; - gapOut[1] = 0.02 * m; - dZ[1] = dZ2 - zgap / 2; - Z[1] = Z[0] + dZ[0] + dZ[1] + zgap; - - dXIn[2] = 0.72 * m; - dXOut[2] = 0.51 * m; - dYIn[2] = 0.29 * m; - dYOut[2] = 0.46 * m; - gapIn[2] = 0.10 * m; - gapOut[2] = 0.07 * m; - dZ[2] = dZ3 - zgap / 2; - Z[2] = Z[1] + dZ[1] + dZ[2] + 2 * zgap; - - dXIn[3] = 0.54 * m; - dXOut[3] = 0.38 * m; - dYIn[3] = 0.46 * m; - dYOut[3] = 1.92 * m; - gapIn[3] = 0.14 * m; - gapOut[3] = 0.09 * m; - dZ[3] = dZ4 - zgap / 2; - Z[3] = Z[2] + dZ[2] + dZ[3] + zgap; - - dXIn[4] = 0.10 * m; - dXOut[4] = 0.31 * m; - dYIn[4] = 0.35 * m; - dYOut[4] = 0.31 * m; - gapIn[4] = 0.51 * m; - gapOut[4] = 0.11 * m; - dZ[4] = dZ5 - zgap / 2; - Z[4] = Z[3] + dZ[3] + dZ[4] + zgap; - - dXIn[5] = 0.03 * m; - dXOut[5] = 0.32 * m; - dYIn[5] = 0.54 * m; - dYOut[5] = 0.24 * m; - gapIn[5] = 0.08 * m; - gapOut[5] = 0.08 * m; - dZ[5] = dZ6 - zgap / 2; - Z[5] = Z[4] + dZ[4] + dZ[5] + zgap; - - dXIn[6] = 0.22 * m; - dXOut[6] = 0.32 * m; - dYIn[6] = 2.09 * m; - dYOut[6] = 0.35 * m; - gapIn[6] = 0.08 * m; - gapOut[6] = 0.13 * m; - dZ[6] = dZ7 - zgap / 2; - Z[6] = Z[5] + dZ[5] + dZ[6] + zgap; - - dXIn[7] = 0.33 * m; - dXOut[7] = 0.77 * m; - dYIn[7] = 0.85 * m; - dYOut[7] = 2.41 * m; - gapIn[7] = 0.09 * m; - gapOut[7] = 0.26 * m; - dZ[7] = dZ8 - zgap / 2; - Z[7] = Z[6] + dZ[6] + dZ[7] + zgap; - - dXIn[8] = dXOut[7]; - dYIn[8] = dYOut[7]; - dXOut[8] = dXIn[8]; - dYOut[8] = dYIn[8]; - gapIn[8] = gapOut[7]; - gapOut[8] = gapIn[8]; - dZ[8] = 0.1 * m; - Z[8] = Z[7] + dZ[7] + dZ[8]; - - for (int i = 0; i < nMagnets; ++i) { - midGapIn[i] = 0.; - midGapOut[i] = 0.; - HmainSideMagIn[i] = dYIn[i] / 2; - HmainSideMagOut[i] = dYOut[i] / 2; - } - - } else if (fDesign == 7) { - magnetName = {"MagnAbsorb1", "MagnAbsorb2", "Magn1", "Magn2", "Magn3", - "Magn4", "Magn5", "Magn6", "Magn7"}; - - fieldDirection[0] = FieldDirection::up; - dXIn[0] = 0.4*m; dYIn[0] = 1.5*m; - dXOut[0] = 0.40*m; dYOut[0]= 1.5*m; - gapIn[0] = 0.02 * m; gapOut[0] = 0.02 * m; - dZ[0] = dZ1-zgap/2; Z[0] = zEndOfAbsorb + dZ[0]+zgap; - - fieldDirection[1] = FieldDirection::up; - dXIn[1] = 0.8*m; dYIn[1] = 1.5*m; - dXOut[1] = 0.8*m; dYOut[1]= 1.5*m; - gapIn[1] = 0.02*m; gapOut[1] = 0.02*m; - dZ[1] = dZ2-zgap/2; Z[1] = Z[0] + dZ[0] + dZ[1]+zgap; - - fieldDirection[2] = FieldDirection::up; - dXIn[2] = 0.87*m; dYIn[2] = 0.35*m; - dXOut[2] = 0.65*m; dYOut[2]= 1.21*m; - gapIn[2] = 0.11 * m; gapOut[2] = 0.065 * m; - dZ[2] = dZ3-zgap/2; Z[2] = Z[1] + dZ[1] + dZ[2] + zgap; - - fieldDirection[3] = FieldDirection::up; - dXIn[3] = 0.65*m; dYIn[3] = 1.21*m; - dXOut[3] = 0.43*m; dYOut[3]= 2.07*m; - gapIn[3] = 0.065 * m; gapOut[3] = 0.02 * m; - dZ[3] = dZ4-zgap/2; Z[3] = Z[2] + dZ[2] + dZ[3]+zgap; - - fieldDirection[4] = FieldDirection::up; - dXIn[4] = 0.06*m; dYIn[4] = 0.32*m; - dXOut[4] = 0.33*m; dYOut[4]= 0.13*m; - gapIn[4] = 0.7*m; gapOut[4] = 0.11*m; - dZ[4] = dZ5-zgap/2; Z[4] = Z[3] + dZ[3] + dZ[4]+zgap; - - fieldDirection[5] = FieldDirection::down; - dXIn[5] = 0.05*m; dYIn[5] = 1.12*m; - dXOut[5] =0.16*m; dYOut[5]= 0.05*m; - gapIn[5] = 0.04*m; gapOut[5] = 0.02*m; - dZ[5] = dZ6-zgap/2; Z[5] = Z[4] + dZ[4] + dZ[5]+zgap; - - fieldDirection[6] = FieldDirection::down; - dXIn[6] = 0.15*m; dYIn[6] = 2.35*m; - dXOut[6] = 0.34*m; dYOut[6]= 0.32*m; - gapIn[6] = 0.05*m; gapOut[6] = 0.08*m; - dZ[6] = dZ7-zgap/2; Z[6] = Z[5] + dZ[5] + dZ[6]+zgap; - - Double_t clip_width = 0.1*m; // clip field width by this width - fieldDirection[7] = FieldDirection::down; - dXIn[7] = 0.31*m; dYIn[7] = 1.86*m; - dXOut[7] = 0.9*m - clip_width; dYOut[7]= 3.1*m; - Double_t clip_len = - (dZ8-zgap/2) * (1 - (dXOut[7] - dXIn[7]) / (dXOut[7] + clip_width - dXIn[7])); - gapIn[7] = 0.02*m; gapOut[7] = 0.55*m; - dZ[7] = dZ8 - clip_len - zgap / 2; Z[7] = Z[6] + dZ[6] + dZ[7] + zgap; - - fieldDirection[8] = FieldDirection::down; - dXIn[8] = dXOut[7]; dYIn[8] = dYOut[7]; - dXOut[8] = dXOut[7]; dYOut[8]= dYOut[7]; - gapIn[8] = 0.55*m; gapOut[8] = 0.55*m; - dZ[8] = clip_len; Z[8] = Z[7] + dZ[7] + dZ[8]; - - for (int i = 0; i < nMagnets; ++i) { - midGapIn[i] = 0.; - midGapOut[i] = 0.; - HmainSideMagIn[i] = dYIn[i] / 2; - HmainSideMagOut[i] = dYOut[i] / 2; - } - - } else { - - magnetName = {"1", "2", "3", "4", "5", "6", "7"}; - - fieldDirection[0] = FieldDirection::up; - dXIn[0] = 0.7*m; dYIn[0] = 1.*m; - dXOut[0] = 0.7*m; dYOut[0]= 0.8158*m; - midGapIn[0] = 0; midGapOut[0] = 0; - HmainSideMagIn[0] = dYIn[0]; HmainSideMagOut[0] = dYOut[0]; - gapIn[0] = 20; gapOut[0] = 20; - dZ[0] = dZ1-zgap; Z[0] = zEndOfAbsorb + dZ[0]+zgap; - - fieldDirection[1] = FieldDirection::up; - dXIn[1] = 0.36*m; dYIn[1] = 0.8158*m; - dXOut[1] = 0.19*m; dYOut[1]= 0.499*m; - midGapIn[1] = 0; midGapOut[1] = 0; - HmainSideMagIn[1] = dYIn[1]/2; HmainSideMagOut[1] = dYOut[1]/2; - gapIn[1] = 88; gapOut[1] = 122; - dZ[1] = dZ2-zgap/2; Z[1] = Z[0] + dZ[0] + dZ[1]+zgap; - - fieldDirection[2] = FieldDirection::down; - dXIn[2] = 0.075*m; dYIn[2] = 0.499*m; - dXOut[2] = 0.25*m; dYOut[2]= 1.10162*m; - midGapIn[2] = 0; midGapOut[2] = 0; - HmainSideMagIn[2] = dYIn[2]/2; HmainSideMagOut[2] = dYOut[2]/2; - gapIn[2] = 0; gapOut[2] = 0; - dZ[2] = dZ3-zgap/2; Z[2] = Z[1] + dZ[1] + dZ[2]+zgap; - - fieldDirection[3] = FieldDirection::down; - dXIn[3] = 0.25*m; dYIn[3] = 1.10262*m; - dXOut[3] = 0.3*m; dYOut[3]= 1.82697*m; - midGapIn[3] = 0; midGapOut[3] = 0; - HmainSideMagIn[3] = dXIn[3]; HmainSideMagOut[3] = dXOut[3]; - gapIn[3] = 0; gapOut[3] = 25; - dZ[3] = dZ4-zgap/2; Z[3] = Z[2] + dZ[2] + dZ[3]+zgap; - - fieldDirection[4] = FieldDirection::down; - dXIn[4] = 0.3*m; dYIn[4] = 1.82697*m; - dXOut[4] = 0.4*m; dYOut[4]= 2.55131*m; - midGapIn[4] = 5; midGapOut[4] = 25; - HmainSideMagIn[4] = dXIn[4]; HmainSideMagOut[4] = dXOut[4]; - gapIn[4] = 20; gapOut[4] = 20; - dZ[4] = dZ6-zgap/2; Z[4] = Z[3] + dZ[3] + dZ[4]+zgap; - - fieldDirection[5] = FieldDirection::down; - dXIn[5] = 0.4*m; dYIn[5] = 2.55131*m; - dXOut[5] =0.4*m; dYOut[5]= 3.27566*m; - midGapIn[5] = 25; midGapOut[5] = 65; - HmainSideMagIn[5] = dXIn[5]; HmainSideMagOut[5] = dXOut[5]; - gapIn[5] = 20; gapOut[5] = 20; - dZ[5] = dZ7-zgap/2; Z[5] = Z[4] + dZ[4] + dZ[5]+zgap; - - fieldDirection[6] = FieldDirection::down; - dXIn[6] = 0.4*m; dYIn[6] = 3.27566*m; - dXOut[6] = 0.75*m; dYOut[6]= 4*m; - midGapIn[6] = 65; midGapOut[6] = 75; - HmainSideMagIn[6] = dXIn[6]; HmainSideMagOut[6] = dXOut[6]; - gapIn[6] = 20; gapOut[6] = 20; - dZ[6] = dZ8-zgap/2; Z[6] = Z[5] + dZ[5] + dZ[6]+zgap; - } - return nMagnets; + Double_t zgap = 10 * cm; // fixed distance between magnets in Z-axis + + if (fDesign == 8) { + + magnetName = {"MagnAbsorb1", "MagnAbsorb2", "Magn1", "Magn2", "Magn3", "Magn4", "Magn5", "Magn6", "Magn7"}; + + fieldDirection = { + FieldDirection::up, + FieldDirection::up, + FieldDirection::up, + FieldDirection::up, + FieldDirection::up, + FieldDirection::down, + FieldDirection::down, + FieldDirection::down, + FieldDirection::down, + }; + + std::vector params; + if (!fSC_mag) { + TVectorT paramsR; + auto f = TFile::Open(fGeofile, "read"); + paramsR.Read("params"); + for (int i = 0; i < 56; i++) { + params.push_back(paramsR[i]); + } + } else { + params = shield_params; + } + + const int offset = 7; + + dXIn[0] = 0.4 * m; + dXOut[0] = 0.40 * m; + gapIn[0] = 0.1 * mm; + dYIn[0] = 1.5 * m; + dYOut[0] = 1.5 * m; + gapOut[0] = 0.1 * mm; + dXIn[1] = 0.5 * m; + dXOut[1] = 0.5 * m; + gapIn[1] = 0.02 * m; + dYIn[1] = 1.3 * m; + dYOut[1] = 1.3 * m; + gapOut[1] = 0.02 * m; + + for (Int_t i = 2; i < nMagnets - 1; ++i) { + dXIn[i] = params[offset + i * 6 + 1]; + dXOut[i] = params[offset + i * 6 + 2]; + dYIn[i] = params[offset + i * 6 + 3]; + dYOut[i] = params[offset + i * 6 + 4]; + gapIn[i] = params[offset + i * 6 + 5]; + gapOut[i] = params[offset + i * 6 + 6]; + } + + dZ[0] = dZ1 - zgap / 2; + Z[0] = zEndOfAbsorb + dZ[0] + zgap; + dZ[1] = dZ2 - zgap / 2; + Z[1] = Z[0] + dZ[0] + dZ[1] + zgap; + dZ[2] = dZ3 - zgap / 2; + Z[2] = Z[1] + dZ[1] + dZ[2] + 2 * zgap; + dZ[3] = dZ4 - zgap / 2; + Z[3] = Z[2] + dZ[2] + dZ[3] + zgap; + dZ[4] = dZ5 - zgap / 2; + Z[4] = Z[3] + dZ[3] + dZ[4] + zgap; + dZ[5] = dZ6 - zgap / 2; + Z[5] = Z[4] + dZ[4] + dZ[5] + zgap; + dZ[6] = dZ7 - zgap / 2; + Z[6] = Z[5] + dZ[5] + dZ[6] + zgap; + dZ[7] = dZ8 - zgap / 2; + Z[7] = Z[6] + dZ[6] + dZ[7] + zgap; + + dXIn[8] = dXOut[7]; + dYIn[8] = dYOut[7]; + dXOut[8] = dXIn[8]; + dYOut[8] = dYIn[8]; + gapIn[8] = gapOut[7]; + gapOut[8] = gapIn[8]; + dZ[8] = 0.1 * m; + Z[8] = Z[7] + dZ[7] + dZ[8]; + + for (int i = 0; i < nMagnets; ++i) { + midGapIn[i] = 0.; + midGapOut[i] = 0.; + HmainSideMagIn[i] = dYIn[i] / 2; + HmainSideMagOut[i] = dYOut[i] / 2; + } + + } else if (fDesign == 9) { + magnetName = {"MagnAbsorb1", "MagnAbsorb2", "Magn1", "Magn2", "Magn3", "Magn4", "Magn5", "Magn6", "Magn7"}; + + fieldDirection = { + FieldDirection::up, + FieldDirection::up, + FieldDirection::up, + FieldDirection::up, + FieldDirection::up, + FieldDirection::down, + FieldDirection::down, + FieldDirection::down, + FieldDirection::down, + }; + + dXIn[0] = 0.4 * m; + dXOut[0] = 0.40 * m; + dYIn[0] = 1.5 * m; + dYOut[0] = 1.5 * m; + gapIn[0] = 0.1 * mm; + gapOut[0] = 0.1 * mm; + dZ[0] = dZ1 - zgap / 2; + Z[0] = zEndOfAbsorb + dZ[0] + zgap; + + dXIn[1] = 0.5 * m; + dXOut[1] = 0.5 * m; + dYIn[1] = 1.3 * m; + dYOut[1] = 1.3 * m; + gapIn[1] = 0.02 * m; + gapOut[1] = 0.02 * m; + dZ[1] = dZ2 - zgap / 2; + Z[1] = Z[0] + dZ[0] + dZ[1] + zgap; + + dXIn[2] = 0.72 * m; + dXOut[2] = 0.51 * m; + dYIn[2] = 0.29 * m; + dYOut[2] = 0.46 * m; + gapIn[2] = 0.10 * m; + gapOut[2] = 0.07 * m; + dZ[2] = dZ3 - zgap / 2; + Z[2] = Z[1] + dZ[1] + dZ[2] + 2 * zgap; + + dXIn[3] = 0.54 * m; + dXOut[3] = 0.38 * m; + dYIn[3] = 0.46 * m; + dYOut[3] = 1.92 * m; + gapIn[3] = 0.14 * m; + gapOut[3] = 0.09 * m; + dZ[3] = dZ4 - zgap / 2; + Z[3] = Z[2] + dZ[2] + dZ[3] + zgap; + + dXIn[4] = 0.10 * m; + dXOut[4] = 0.31 * m; + dYIn[4] = 0.35 * m; + dYOut[4] = 0.31 * m; + gapIn[4] = 0.51 * m; + gapOut[4] = 0.11 * m; + dZ[4] = dZ5 - zgap / 2; + Z[4] = Z[3] + dZ[3] + dZ[4] + zgap; + + dXIn[5] = 0.03 * m; + dXOut[5] = 0.32 * m; + dYIn[5] = 0.54 * m; + dYOut[5] = 0.24 * m; + gapIn[5] = 0.08 * m; + gapOut[5] = 0.08 * m; + dZ[5] = dZ6 - zgap / 2; + Z[5] = Z[4] + dZ[4] + dZ[5] + zgap; + + dXIn[6] = 0.22 * m; + dXOut[6] = 0.32 * m; + dYIn[6] = 2.09 * m; + dYOut[6] = 0.35 * m; + gapIn[6] = 0.08 * m; + gapOut[6] = 0.13 * m; + dZ[6] = dZ7 - zgap / 2; + Z[6] = Z[5] + dZ[5] + dZ[6] + zgap; + + dXIn[7] = 0.33 * m; + dXOut[7] = 0.77 * m; + dYIn[7] = 0.85 * m; + dYOut[7] = 2.41 * m; + gapIn[7] = 0.09 * m; + gapOut[7] = 0.26 * m; + dZ[7] = dZ8 - zgap / 2; + Z[7] = Z[6] + dZ[6] + dZ[7] + zgap; + + dXIn[8] = dXOut[7]; + dYIn[8] = dYOut[7]; + dXOut[8] = dXIn[8]; + dYOut[8] = dYIn[8]; + gapIn[8] = gapOut[7]; + gapOut[8] = gapIn[8]; + dZ[8] = 0.1 * m; + Z[8] = Z[7] + dZ[7] + dZ[8]; + + for (int i = 0; i < nMagnets; ++i) { + midGapIn[i] = 0.; + midGapOut[i] = 0.; + HmainSideMagIn[i] = dYIn[i] / 2; + HmainSideMagOut[i] = dYOut[i] / 2; + } + + } else if (fDesign == 7) { + magnetName = {"MagnAbsorb1", "MagnAbsorb2", "Magn1", "Magn2", "Magn3", "Magn4", "Magn5", "Magn6", "Magn7"}; + + fieldDirection[0] = FieldDirection::up; + dXIn[0] = 0.4 * m; + dYIn[0] = 1.5 * m; + dXOut[0] = 0.40 * m; + dYOut[0] = 1.5 * m; + gapIn[0] = 0.02 * m; + gapOut[0] = 0.02 * m; + dZ[0] = dZ1 - zgap / 2; + Z[0] = zEndOfAbsorb + dZ[0] + zgap; + + fieldDirection[1] = FieldDirection::up; + dXIn[1] = 0.8 * m; + dYIn[1] = 1.5 * m; + dXOut[1] = 0.8 * m; + dYOut[1] = 1.5 * m; + gapIn[1] = 0.02 * m; + gapOut[1] = 0.02 * m; + dZ[1] = dZ2 - zgap / 2; + Z[1] = Z[0] + dZ[0] + dZ[1] + zgap; + + fieldDirection[2] = FieldDirection::up; + dXIn[2] = 0.87 * m; + dYIn[2] = 0.35 * m; + dXOut[2] = 0.65 * m; + dYOut[2] = 1.21 * m; + gapIn[2] = 0.11 * m; + gapOut[2] = 0.065 * m; + dZ[2] = dZ3 - zgap / 2; + Z[2] = Z[1] + dZ[1] + dZ[2] + zgap; + + fieldDirection[3] = FieldDirection::up; + dXIn[3] = 0.65 * m; + dYIn[3] = 1.21 * m; + dXOut[3] = 0.43 * m; + dYOut[3] = 2.07 * m; + gapIn[3] = 0.065 * m; + gapOut[3] = 0.02 * m; + dZ[3] = dZ4 - zgap / 2; + Z[3] = Z[2] + dZ[2] + dZ[3] + zgap; + + fieldDirection[4] = FieldDirection::up; + dXIn[4] = 0.06 * m; + dYIn[4] = 0.32 * m; + dXOut[4] = 0.33 * m; + dYOut[4] = 0.13 * m; + gapIn[4] = 0.7 * m; + gapOut[4] = 0.11 * m; + dZ[4] = dZ5 - zgap / 2; + Z[4] = Z[3] + dZ[3] + dZ[4] + zgap; + + fieldDirection[5] = FieldDirection::down; + dXIn[5] = 0.05 * m; + dYIn[5] = 1.12 * m; + dXOut[5] = 0.16 * m; + dYOut[5] = 0.05 * m; + gapIn[5] = 0.04 * m; + gapOut[5] = 0.02 * m; + dZ[5] = dZ6 - zgap / 2; + Z[5] = Z[4] + dZ[4] + dZ[5] + zgap; + + fieldDirection[6] = FieldDirection::down; + dXIn[6] = 0.15 * m; + dYIn[6] = 2.35 * m; + dXOut[6] = 0.34 * m; + dYOut[6] = 0.32 * m; + gapIn[6] = 0.05 * m; + gapOut[6] = 0.08 * m; + dZ[6] = dZ7 - zgap / 2; + Z[6] = Z[5] + dZ[5] + dZ[6] + zgap; + + Double_t clip_width = 0.1 * m; // clip field width by this width + fieldDirection[7] = FieldDirection::down; + dXIn[7] = 0.31 * m; + dYIn[7] = 1.86 * m; + dXOut[7] = 0.9 * m - clip_width; + dYOut[7] = 3.1 * m; + Double_t clip_len = (dZ8 - zgap / 2) * (1 - (dXOut[7] - dXIn[7]) / (dXOut[7] + clip_width - dXIn[7])); + gapIn[7] = 0.02 * m; + gapOut[7] = 0.55 * m; + dZ[7] = dZ8 - clip_len - zgap / 2; + Z[7] = Z[6] + dZ[6] + dZ[7] + zgap; + + fieldDirection[8] = FieldDirection::down; + dXIn[8] = dXOut[7]; + dYIn[8] = dYOut[7]; + dXOut[8] = dXOut[7]; + dYOut[8] = dYOut[7]; + gapIn[8] = 0.55 * m; + gapOut[8] = 0.55 * m; + dZ[8] = clip_len; + Z[8] = Z[7] + dZ[7] + dZ[8]; + + for (int i = 0; i < nMagnets; ++i) { + midGapIn[i] = 0.; + midGapOut[i] = 0.; + HmainSideMagIn[i] = dYIn[i] / 2; + HmainSideMagOut[i] = dYOut[i] / 2; + } + + } else { + + magnetName = {"1", "2", "3", "4", "5", "6", "7"}; + + fieldDirection[0] = FieldDirection::up; + dXIn[0] = 0.7 * m; + dYIn[0] = 1. * m; + dXOut[0] = 0.7 * m; + dYOut[0] = 0.8158 * m; + midGapIn[0] = 0; + midGapOut[0] = 0; + HmainSideMagIn[0] = dYIn[0]; + HmainSideMagOut[0] = dYOut[0]; + gapIn[0] = 20; + gapOut[0] = 20; + dZ[0] = dZ1 - zgap; + Z[0] = zEndOfAbsorb + dZ[0] + zgap; + + fieldDirection[1] = FieldDirection::up; + dXIn[1] = 0.36 * m; + dYIn[1] = 0.8158 * m; + dXOut[1] = 0.19 * m; + dYOut[1] = 0.499 * m; + midGapIn[1] = 0; + midGapOut[1] = 0; + HmainSideMagIn[1] = dYIn[1] / 2; + HmainSideMagOut[1] = dYOut[1] / 2; + gapIn[1] = 88; + gapOut[1] = 122; + dZ[1] = dZ2 - zgap / 2; + Z[1] = Z[0] + dZ[0] + dZ[1] + zgap; + + fieldDirection[2] = FieldDirection::down; + dXIn[2] = 0.075 * m; + dYIn[2] = 0.499 * m; + dXOut[2] = 0.25 * m; + dYOut[2] = 1.10162 * m; + midGapIn[2] = 0; + midGapOut[2] = 0; + HmainSideMagIn[2] = dYIn[2] / 2; + HmainSideMagOut[2] = dYOut[2] / 2; + gapIn[2] = 0; + gapOut[2] = 0; + dZ[2] = dZ3 - zgap / 2; + Z[2] = Z[1] + dZ[1] + dZ[2] + zgap; + + fieldDirection[3] = FieldDirection::down; + dXIn[3] = 0.25 * m; + dYIn[3] = 1.10262 * m; + dXOut[3] = 0.3 * m; + dYOut[3] = 1.82697 * m; + midGapIn[3] = 0; + midGapOut[3] = 0; + HmainSideMagIn[3] = dXIn[3]; + HmainSideMagOut[3] = dXOut[3]; + gapIn[3] = 0; + gapOut[3] = 25; + dZ[3] = dZ4 - zgap / 2; + Z[3] = Z[2] + dZ[2] + dZ[3] + zgap; + + fieldDirection[4] = FieldDirection::down; + dXIn[4] = 0.3 * m; + dYIn[4] = 1.82697 * m; + dXOut[4] = 0.4 * m; + dYOut[4] = 2.55131 * m; + midGapIn[4] = 5; + midGapOut[4] = 25; + HmainSideMagIn[4] = dXIn[4]; + HmainSideMagOut[4] = dXOut[4]; + gapIn[4] = 20; + gapOut[4] = 20; + dZ[4] = dZ6 - zgap / 2; + Z[4] = Z[3] + dZ[3] + dZ[4] + zgap; + + fieldDirection[5] = FieldDirection::down; + dXIn[5] = 0.4 * m; + dYIn[5] = 2.55131 * m; + dXOut[5] = 0.4 * m; + dYOut[5] = 3.27566 * m; + midGapIn[5] = 25; + midGapOut[5] = 65; + HmainSideMagIn[5] = dXIn[5]; + HmainSideMagOut[5] = dXOut[5]; + gapIn[5] = 20; + gapOut[5] = 20; + dZ[5] = dZ7 - zgap / 2; + Z[5] = Z[4] + dZ[4] + dZ[5] + zgap; + + fieldDirection[6] = FieldDirection::down; + dXIn[6] = 0.4 * m; + dYIn[6] = 3.27566 * m; + dXOut[6] = 0.75 * m; + dYOut[6] = 4 * m; + midGapIn[6] = 65; + midGapOut[6] = 75; + HmainSideMagIn[6] = dXIn[6]; + HmainSideMagOut[6] = dXOut[6]; + gapIn[6] = 20; + gapOut[6] = 20; + dZ[6] = dZ8 - zgap / 2; + Z[6] = Z[5] + dZ[5] + dZ[6] + zgap; + } + return nMagnets; } void ShipMuonShield::ConstructGeometry() { - TGeoVolume *top=gGeoManager->GetTopVolume(); - TGeoVolume *tShield = new TGeoVolumeAssembly("MuonShieldArea"); + TGeoVolume* top = gGeoManager->GetTopVolume(); + TGeoVolume* tShield = new TGeoVolumeAssembly("MuonShieldArea"); InitMedium("steel"); - TGeoMedium *steel =gGeoManager->GetMedium("steel"); + TGeoMedium* steel = gGeoManager->GetMedium("steel"); InitMedium("iron"); - TGeoMedium *iron =gGeoManager->GetMedium("iron"); + TGeoMedium* iron = gGeoManager->GetMedium("iron"); InitMedium("Concrete"); - TGeoMedium *concrete =gGeoManager->GetMedium("Concrete"); + TGeoMedium* concrete = gGeoManager->GetMedium("Concrete"); if (fDesign >= 7 && fDesign <= 9) { - Double_t ironField = fField*tesla; - TGeoUniformMagField *magFieldIron = new TGeoUniformMagField(0.,ironField,0.); - TGeoUniformMagField *RetField = new TGeoUniformMagField(0.,-ironField,0.); - TGeoUniformMagField *ConRField = new TGeoUniformMagField(-ironField,0.,0.); - TGeoUniformMagField *ConLField = new TGeoUniformMagField(ironField,0.,0.); - TGeoUniformMagField *fields[4] = {magFieldIron,RetField,ConRField,ConLField}; - - std::vector magnetName; - std::vector fieldDirection; - std::vector dXIn, dYIn, dXOut, dYOut, dZf, midGapIn, midGapOut, - HmainSideMagIn, HmainSideMagOut, gapIn, gapOut, Z; - const Int_t nMagnets = Initialize(magnetName, fieldDirection, dXIn, dYIn, dXOut, dYOut, dZf, - midGapIn, midGapOut, HmainSideMagIn, HmainSideMagOut, gapIn, - gapOut, Z); - - // Create TCC8 tunnel around muon shield - Double_t TCC8_length = 170 * m; - Double_t ECN3_length = 100 * m; - Double_t TCC8_trench_length = 12 * m; - Double_t zgap = 10 * cm; - Double_t absorber_offset = zgap; - Double_t absorber_half_length = (dZf[0] + dZf[1]) + zgap / 2.; - Double_t z_transition = zEndOfAbsorb + 2 * absorber_half_length + absorber_offset + 14 * cm + TCC8_trench_length; - auto *rock = new TGeoBBox("rock", 20 * m, 20 * m, TCC8_length / 2. + ECN3_length / 2. + 5 * m); - auto *muon_shield_cavern = new TGeoBBox("muon_shield_cavern", 5 * m, 3.75 * m, TCC8_length / 2.); - auto *TCC8_shift = new TGeoTranslation("TCC8_shift", 2.3 * m, 1.75 * m, - TCC8_length / 2.); - TCC8_shift->RegisterYourself(); - - // Create ECN3 cavern around vessel - auto *experiment_rock = new TGeoBBox("experiment_rock", 20 * m, 20 * m, ECN3_length / 2.); - auto *experiment_cavern = new TGeoBBox("experiment_cavern", 8 * m, 7.5 * m, ECN3_length / 2.); - auto *ECN3_shift = new TGeoTranslation("ECN3_shift", 3.5 * m, 4 * m, ECN3_length / 2.); - ECN3_shift->RegisterYourself(); - - auto *yoke_pit = new TGeoBBox("yoke_pit", 3.5 * m, 4.3 * m + 1 * cm, 2.5 * m); - auto *yoke_pit_shift = new TGeoTranslation("yoke_pit_shift", 0 * m, 0 * m, 31 * m - z_transition); - yoke_pit_shift->RegisterYourself(); - - auto *target_pit = new TGeoBBox("target_pit", 2 * m, 0.5 * m, 2 * m); - auto *target_pit_shift = new TGeoTranslation("target_pit_shift", 0 * m, -2.5 * m, zEndOfAbsorb - 2 * m - z_transition); - target_pit_shift->RegisterYourself(); + Double_t ironField = fField * tesla; + TGeoUniformMagField* magFieldIron = new TGeoUniformMagField(0., ironField, 0.); + TGeoUniformMagField* RetField = new TGeoUniformMagField(0., -ironField, 0.); + TGeoUniformMagField* ConRField = new TGeoUniformMagField(-ironField, 0., 0.); + TGeoUniformMagField* ConLField = new TGeoUniformMagField(ironField, 0., 0.); + TGeoUniformMagField* fields[4] = {magFieldIron, RetField, ConRField, ConLField}; + + std::vector magnetName; + std::vector fieldDirection; + std::vector dXIn, dYIn, dXOut, dYOut, dZf, midGapIn, midGapOut, HmainSideMagIn, HmainSideMagOut, + gapIn, gapOut, Z; + const Int_t nMagnets = Initialize(magnetName, + fieldDirection, + dXIn, + dYIn, + dXOut, + dYOut, + dZf, + midGapIn, + midGapOut, + HmainSideMagIn, + HmainSideMagOut, + gapIn, + gapOut, + Z); + + // Create TCC8 tunnel around muon shield + Double_t TCC8_length = 170 * m; + Double_t ECN3_length = 100 * m; + Double_t TCC8_trench_length = 12 * m; + Double_t zgap = 10 * cm; + Double_t absorber_offset = zgap; + Double_t absorber_half_length = (dZf[0] + dZf[1]) + zgap / 2.; + Double_t z_transition = + zEndOfAbsorb + 2 * absorber_half_length + absorber_offset + 14 * cm + TCC8_trench_length; + auto* rock = new TGeoBBox("rock", 20 * m, 20 * m, TCC8_length / 2. + ECN3_length / 2. + 5 * m); + auto* muon_shield_cavern = new TGeoBBox("muon_shield_cavern", 5 * m, 3.75 * m, TCC8_length / 2.); + auto* TCC8_shift = new TGeoTranslation("TCC8_shift", 2.3 * m, 1.75 * m, -TCC8_length / 2.); + TCC8_shift->RegisterYourself(); + + // Create ECN3 cavern around vessel + auto* experiment_rock = new TGeoBBox("experiment_rock", 20 * m, 20 * m, ECN3_length / 2.); + auto* experiment_cavern = new TGeoBBox("experiment_cavern", 8 * m, 7.5 * m, ECN3_length / 2.); + auto* ECN3_shift = new TGeoTranslation("ECN3_shift", 3.5 * m, 4 * m, ECN3_length / 2.); + ECN3_shift->RegisterYourself(); + + auto* yoke_pit = new TGeoBBox("yoke_pit", 3.5 * m, 4.3 * m + 1 * cm, 2.5 * m); + auto* yoke_pit_shift = new TGeoTranslation("yoke_pit_shift", 0 * m, 0 * m, 31 * m - z_transition); + yoke_pit_shift->RegisterYourself(); + + auto* target_pit = new TGeoBBox("target_pit", 2 * m, 0.5 * m, 2 * m); + auto* target_pit_shift = + new TGeoTranslation("target_pit_shift", 0 * m, -2.5 * m, zEndOfAbsorb - 2 * m - z_transition); + target_pit_shift->RegisterYourself(); float mField = 1.6 * tesla; - TGeoUniformMagField *fieldsAbsorber[4] = { - new TGeoUniformMagField(0., mField, 0.), - new TGeoUniformMagField(0., -mField, 0.), - new TGeoUniformMagField(-mField, 0., 0.), - new TGeoUniformMagField(mField, 0., 0.) - }; - - for (Int_t nM = (fDesign == 7) ? 0 : 1; nM < 2; nM++) { - CreateMagnet(magnetName[nM], iron, tShield, fieldsAbsorber, - fieldDirection[nM], dXIn[nM], dYIn[nM], dXOut[nM], - dYOut[nM], dZf[nM], midGapIn[nM], midGapOut[nM], - HmainSideMagIn[nM], HmainSideMagOut[nM], gapIn[nM], - gapOut[nM], Z[nM], true, false); - } - - std::vector mag_trans; - - if (fDesign == 7) { - auto mag1 = new TGeoTranslation("mag1", 0, 0, -dZ2); - mag1->RegisterYourself(); - mag_trans.push_back(mag1); - } - auto mag2 = new TGeoTranslation("mag2", 0, 0, +dZ1); - mag2->RegisterYourself(); - mag_trans.push_back(mag2); - - auto abs = new TGeoBBox("absorber", 3.95 * m, 3.4 * m, absorber_half_length); - const std::vector absorber_magnets = - (fDesign == 7) ? std::vector{"MagnAbsorb1", "MagnAbsorb2"} : std::vector{"MagnAbsorb2"}; - const std::vector magnet_components = fDesign == 7 ? std::vector{ + TGeoUniformMagField* fieldsAbsorber[4] = {new TGeoUniformMagField(0., mField, 0.), + new TGeoUniformMagField(0., -mField, 0.), + new TGeoUniformMagField(-mField, 0., 0.), + new TGeoUniformMagField(mField, 0., 0.)}; + + for (Int_t nM = (fDesign == 7) ? 0 : 1; nM < 2; nM++) { + CreateMagnet(magnetName[nM], + iron, + tShield, + fieldsAbsorber, + fieldDirection[nM], + dXIn[nM], + dYIn[nM], + dXOut[nM], + dYOut[nM], + dZf[nM], + midGapIn[nM], + midGapOut[nM], + HmainSideMagIn[nM], + HmainSideMagOut[nM], + gapIn[nM], + gapOut[nM], + Z[nM], + true, + false); + } + + std::vector mag_trans; + + if (fDesign == 7) { + auto mag1 = new TGeoTranslation("mag1", 0, 0, -dZ2); + mag1->RegisterYourself(); + mag_trans.push_back(mag1); + } + auto mag2 = new TGeoTranslation("mag2", 0, 0, +dZ1); + mag2->RegisterYourself(); + mag_trans.push_back(mag2); + + auto abs = new TGeoBBox("absorber", 3.95 * m, 3.4 * m, absorber_half_length); + const std::vector absorber_magnets = + (fDesign == 7) ? std::vector{"MagnAbsorb1", "MagnAbsorb2"} : std::vector{"MagnAbsorb2"}; + const std::vector magnet_components = fDesign == 7 ? std::vector{ "_MiddleMagL", "_MiddleMagR", "_MagRetL", "_MagRetR", "_MagCLB", "_MagCLT", "_MagCRT", "_MagCRB", "_MagTopLeft", "_MagTopRight", "_MagBotLeft", "_MagBotRight", @@ -901,159 +1102,189 @@ void ShipMuonShield::ConstructGeometry() "_MiddleMagL", "_MiddleMagR", "_MagRetL", "_MagRetR", "_MagTopLeft", "_MagTopRight", "_MagBotLeft", "_MagBotRight", }; - TString absorber_magnet_components; - for (auto &&magnet_component : magnet_components) { - // format: "-_:" - absorber_magnet_components += - ("-" + absorber_magnets[0] + magnet_component + ":" + - mag_trans[0]->GetName()); - if (fDesign == 7) { - absorber_magnet_components += - ("-" + absorber_magnets[1] + magnet_component + ":" + - mag_trans[1]->GetName()); - } - } - TGeoCompositeShape *absorberShape = new TGeoCompositeShape( - "Absorber", "absorber" + absorber_magnet_components); // cutting out - // magnet parts - // from absorber - TGeoVolume *absorber = new TGeoVolume("AbsorberVol", absorberShape, iron); - absorber->SetLineColor(42); // brown / light red - tShield->AddNode(absorber, 1, new TGeoTranslation(0, 0, zEndOfAbsorb + absorber_half_length + absorber_offset)); - - if (fDesign > 7) { - auto coatBox = new TGeoBBox("coat", 10 * m - 1 * mm, 10 * m - 1 * mm, absorber_half_length); - auto coatShape = new TGeoCompositeShape("CoatShape", "coat-absorber"); - auto coat = new TGeoVolume("CoatVol", coatShape, concrete); - auto *coat_shift = new TGeoTranslation("coat_shift", 0, 0, zEndOfAbsorb + absorber_half_length + absorber_offset); - coat_shift->RegisterYourself(); - auto *coat_shift_transition = new TGeoTranslation("coat_shift_transition", 0, 0, zEndOfAbsorb - z_transition + absorber_half_length + absorber_offset); - coat_shift_transition->RegisterYourself(); - tShield->AddNode(coat, 1, coat_shift); - TGeoVolume *coatWall = gGeoManager->MakeBox("CoatWall",concrete, 10 * m - 1 * mm, 10 * m - 1 * mm, 7 * cm - 1 * mm); - auto *coatWall_shift = new TGeoTranslation("coatWall_shift", 0, 0, zEndOfAbsorb + 2 * absorber_half_length + absorber_offset + 7 * cm); - coatWall_shift->RegisterYourself(); - auto *coatWall_shift_transition = new TGeoTranslation("coatWall_shift_transition", 0, 0, zEndOfAbsorb - z_transition + 2 * absorber_half_length + absorber_offset + 7 * cm); - coatWall_shift_transition->RegisterYourself(); - coatWall->SetLineColor(kRed); - tShield->AddNode(coatWall, 1, coatWall_shift); - } - - auto *compRock = new TGeoCompositeShape("compRock", - "rock - muon_shield_cavern:TCC8_shift" - "- experiment_cavern:ECN3_shift" - "- yoke_pit:yoke_pit_shift" - "- target_pit:target_pit_shift" - "- coat:coat_shift_transition" - "- CoatWall:coatWall_shift_transition" - ); - auto *Cavern = new TGeoVolume("Cavern", compRock, concrete); - Cavern->SetLineColor(11); // grey - Cavern->SetTransparency(50); - top->AddNode(Cavern, 1, new TGeoTranslation(0, 0, z_transition)); - - - std::array fieldScale = {{1., 1., 1., 1., 1., 1., 1., 1., 1.}}; - if (fWithCoMagnet > 0) - { - Double_t lengthSum = 0.; - for (int i = 2; i < 9; ++i) - { - lengthSum += dZf[i]; + TString absorber_magnet_components; + for (auto&& magnet_component : magnet_components) { + // format: "-_:" + absorber_magnet_components += + ("-" + absorber_magnets[0] + magnet_component + ":" + mag_trans[0]->GetName()); + if (fDesign == 7) { + absorber_magnet_components += + ("-" + absorber_magnets[1] + magnet_component + ":" + mag_trans[1]->GetName()); + } + } + TGeoCompositeShape* absorberShape = + new TGeoCompositeShape("Absorber", "absorber" + absorber_magnet_components); // cutting out + // magnet parts + // from absorber + TGeoVolume* absorber = new TGeoVolume("AbsorberVol", absorberShape, iron); + absorber->SetLineColor(42); // brown / light red + tShield->AddNode(absorber, 1, new TGeoTranslation(0, 0, zEndOfAbsorb + absorber_half_length + absorber_offset)); + + if (fDesign > 7) { + auto coatBox = new TGeoBBox("coat", 10 * m - 1 * mm, 10 * m - 1 * mm, absorber_half_length); + auto coatShape = new TGeoCompositeShape("CoatShape", "coat-absorber"); + auto coat = new TGeoVolume("CoatVol", coatShape, concrete); + auto* coat_shift = + new TGeoTranslation("coat_shift", 0, 0, zEndOfAbsorb + absorber_half_length + absorber_offset); + coat_shift->RegisterYourself(); + auto* coat_shift_transition = new TGeoTranslation( + "coat_shift_transition", 0, 0, zEndOfAbsorb - z_transition + absorber_half_length + absorber_offset); + coat_shift_transition->RegisterYourself(); + tShield->AddNode(coat, 1, coat_shift); + TGeoVolume* coatWall = + gGeoManager->MakeBox("CoatWall", concrete, 10 * m - 1 * mm, 10 * m - 1 * mm, 7 * cm - 1 * mm); + auto* coatWall_shift = new TGeoTranslation( + "coatWall_shift", 0, 0, zEndOfAbsorb + 2 * absorber_half_length + absorber_offset + 7 * cm); + coatWall_shift->RegisterYourself(); + auto* coatWall_shift_transition = + new TGeoTranslation("coatWall_shift_transition", + 0, + 0, + zEndOfAbsorb - z_transition + 2 * absorber_half_length + absorber_offset + 7 * cm); + coatWall_shift_transition->RegisterYourself(); + coatWall->SetLineColor(kRed); + tShield->AddNode(coatWall, 1, coatWall_shift); } - fieldScale.fill((fField * lengthSum - 2.2 * dZf[fWithCoMagnet])/fField/(lengthSum - dZf[fWithCoMagnet])); - fieldScale[0] = 1.; - fieldScale[1] = 1.; - try - { - fieldScale.at(fWithCoMagnet) = 2.2 / fField; + + auto* compRock = new TGeoCompositeShape("compRock", + "rock - muon_shield_cavern:TCC8_shift" + "- experiment_cavern:ECN3_shift" + "- yoke_pit:yoke_pit_shift" + "- target_pit:target_pit_shift" + "- coat:coat_shift_transition" + "- CoatWall:coatWall_shift_transition"); + auto* Cavern = new TGeoVolume("Cavern", compRock, concrete); + Cavern->SetLineColor(11); // grey + Cavern->SetTransparency(50); + top->AddNode(Cavern, 1, new TGeoTranslation(0, 0, z_transition)); + + std::array fieldScale = {{1., 1., 1., 1., 1., 1., 1., 1., 1.}}; + if (fWithCoMagnet > 0) { + Double_t lengthSum = 0.; + for (int i = 2; i < 9; ++i) { + lengthSum += dZf[i]; + } + fieldScale.fill((fField * lengthSum - 2.2 * dZf[fWithCoMagnet]) / fField + / (lengthSum - dZf[fWithCoMagnet])); + fieldScale[0] = 1.; + fieldScale[1] = 1.; + try { + fieldScale.at(fWithCoMagnet) = 2.2 / fField; + } catch (const std::out_of_range& e) { + Fatal("ShipMuonShield", "Exception out of range for --coMuonShield occurred \n"); + } } - catch(const std::out_of_range& e) - { - Fatal( "ShipMuonShield", "Exception out of range for --coMuonShield occurred \n"); + for (Int_t nM = 2; nM <= (nMagnets - 1); nM++) { + + // SC MAGNET + if ((dZf[nM] < 1e-5 || nM == 4) && fSC_mag) { + continue; + } + Double_t ironField_s_SC = fField * fieldScale[nM] * tesla; + Bool_t SC_key = false; + if (nM == 3 && fSC_mag) { + Double_t SC_FIELD = 5.1; + ironField_s_SC = SC_FIELD * fieldScale[nM] * tesla; + SC_key = true; + } + // END + Double_t ironField_s = fField * fieldScale[nM] * tesla; + TGeoUniformMagField* magFieldIron_s = new TGeoUniformMagField(0., ironField_s_SC, 0.); + TGeoUniformMagField* RetField_s = new TGeoUniformMagField(0., -ironField_s, 0.); + TGeoUniformMagField* ConRField_s = new TGeoUniformMagField(-ironField_s, 0., 0.); + TGeoUniformMagField* ConLField_s = new TGeoUniformMagField(ironField_s, 0., 0.); + TGeoUniformMagField* fields_s[4] = {magFieldIron_s, RetField_s, ConRField_s, ConLField_s}; + CreateMagnet(magnetName[nM], + iron, + tShield, + fields_s, + fieldDirection[nM], + dXIn[nM], + dYIn[nM], + dXOut[nM], + dYOut[nM], + dZf[nM], + midGapIn[nM], + midGapOut[nM], + HmainSideMagIn[nM], + HmainSideMagOut[nM], + gapIn[nM], + gapOut[nM], + Z[nM], + nM == 8, + fStepGeo, + SC_key); + + if (nM == 8 || !fSupport) + continue; + Double_t dymax = std::max(dYIn[nM] + dXIn[nM], dYOut[nM] + dXOut[nM]); + Double_t dymin = std::min(dYIn[nM] + dXIn[nM], dYOut[nM] + dXOut[nM]); + Double_t slope = (dYIn[nM] + dXIn[nM] - dYOut[nM] - dXOut[nM]) / (2 * dZf[nM]); + Double_t w1 = 2 * dXIn[nM] + std::max(20., gapIn[nM]); + Double_t w2 = 2 * dXOut[nM] + std::max(20., gapOut[nM]); + Double_t anti_overlap = 0.1; + Double_t h1 = 0.5 * (dYIn[nM] + dXIn[nM] + anti_overlap - 10 * m + fFloor); + Double_t h2 = 0.5 * (dYOut[nM] + dXOut[nM] + anti_overlap - 10 * m + fFloor); + Double_t length = std::min(0.5 * m, std::abs(dZf[nM] / 2. - 5 * cm)); + std::array verticesIn = { + -w1, + -h1, + +w1, + -h1, + +w1, + +h1, + -w1, + +h1, + -w1, + -h1 + slope * 2. * length, + +w1, + -h1 + slope * 2. * length, + +w1, + +h1, + -w1, + +h1, + }; + std::array verticesOut = { + -w2, + -h2 - slope * 2. * length, + +w2, + -h2 - slope * 2. * length, + +w2, + +h2, + -w2, + +h2, + -w2, + -h2, + +w2, + -h2, + +w2, + +h2, + -w2, + +h2, + }; + if (!fStepGeo) { + + TGeoVolume* pillar1 = + gGeoManager->MakeArb8(TString::Format("pillar_%d", 2 * nM - 1), steel, length, verticesIn.data()); + TGeoVolume* pillar2 = + gGeoManager->MakeArb8(TString::Format("pillar_%d", 2 * nM), steel, length, verticesOut.data()); + pillar1->SetLineColor(kGreen - 5); + pillar2->SetLineColor(kGreen - 5); + tShield->AddNode( + pillar1, + 1, + new TGeoTranslation(0, -0.5 * (dYIn[nM] + dXIn[nM] + 10 * m - fFloor), Z[nM] - dZf[nM] + length)); + tShield->AddNode( + pillar2, + 1, + new TGeoTranslation(0, -0.5 * (dYOut[nM] + dXOut[nM] + 10 * m - fFloor), Z[nM] + dZf[nM] - length)); + } } - } - for (Int_t nM = 2; nM <= (nMagnets - 1); nM++) { - - // SC MAGNET - if ((dZf[nM] < 1e-5 || nM == 4 ) && fSC_mag) { - continue; - } - Double_t ironField_s_SC = fField * fieldScale[nM] * tesla; - Bool_t SC_key = false; - if(nM == 3 && fSC_mag){ - Double_t SC_FIELD = 5.1; - ironField_s_SC = SC_FIELD * fieldScale[nM] * tesla; - SC_key = true; - } - // END - Double_t ironField_s = fField * fieldScale[nM] * tesla; - TGeoUniformMagField *magFieldIron_s = new TGeoUniformMagField(0.,ironField_s_SC,0.); - TGeoUniformMagField *RetField_s = new TGeoUniformMagField(0.,-ironField_s,0.); - TGeoUniformMagField *ConRField_s = new TGeoUniformMagField(-ironField_s,0.,0.); - TGeoUniformMagField *ConLField_s = new TGeoUniformMagField(ironField_s,0.,0.); - TGeoUniformMagField *fields_s[4] = {magFieldIron_s,RetField_s,ConRField_s,ConLField_s}; - CreateMagnet(magnetName[nM], iron, tShield, fields_s, fieldDirection[nM], - dXIn[nM], dYIn[nM], dXOut[nM], dYOut[nM], dZf[nM], - midGapIn[nM], midGapOut[nM], HmainSideMagIn[nM], - HmainSideMagOut[nM], gapIn[nM], gapOut[nM], Z[nM], nM==8, fStepGeo, SC_key); - - if (nM==8 || !fSupport) continue; - Double_t dymax = std::max(dYIn[nM] + dXIn[nM], dYOut[nM] + dXOut[nM]); - Double_t dymin = std::min(dYIn[nM] + dXIn[nM], dYOut[nM] + dXOut[nM]); - Double_t slope = - (dYIn[nM] + dXIn[nM] - dYOut[nM] - dXOut[nM]) / (2 * dZf[nM]); - Double_t w1 = 2 * dXIn[nM] + std::max(20., gapIn[nM]); - Double_t w2 = 2 * dXOut[nM] + std::max(20., gapOut[nM]); - Double_t anti_overlap = 0.1; - Double_t h1 = 0.5 * (dYIn[nM] + dXIn[nM] + anti_overlap - 10 * m + fFloor); - Double_t h2 = 0.5 * (dYOut[nM] + dXOut[nM] + anti_overlap - 10 * m + fFloor); - Double_t length = std::min(0.5 * m, std::abs(dZf[nM]/2. - 5 * cm)); - std::array verticesIn = { - -w1, -h1, - +w1, -h1, - +w1, +h1, - -w1, +h1, - -w1, -h1 + slope * 2. * length, - +w1, -h1 + slope * 2. * length, - +w1, +h1, - -w1, +h1, - }; - std::array verticesOut = { - -w2, -h2 - slope * 2. * length, - +w2, -h2 - slope * 2. * length, - +w2, +h2, - -w2, +h2, - -w2, -h2, - +w2, -h2, - +w2, +h2, - -w2, +h2, - }; - if (!fStepGeo) - { - - - TGeoVolume *pillar1 = - gGeoManager->MakeArb8(TString::Format("pillar_%d", 2 * nM - 1), - steel, length, verticesIn.data()); - TGeoVolume *pillar2 = - gGeoManager->MakeArb8(TString::Format("pillar_%d", 2 * nM), steel, - length, verticesOut.data()); - pillar1->SetLineColor(kGreen-5); - pillar2->SetLineColor(kGreen-5); - tShield->AddNode(pillar1, 1, new TGeoTranslation( - 0, -0.5 * (dYIn[nM] + dXIn[nM] + 10 * m - fFloor), - Z[nM] - dZf[nM] + length)); - tShield->AddNode(pillar2, 1, new TGeoTranslation( - 0, -0.5 * (dYOut[nM] + dXOut[nM] + 10 * m - fFloor), - Z[nM] + dZf[nM] - length)); - } - } - - // Place in origin of SHiP coordinate system as subnodes placed correctly - top->AddNode(tShield, 1); + + // Place in origin of SHiP coordinate system as subnodes placed correctly + top->AddNode(tShield, 1); } else { - Fatal("ShipMuonShield","Design %i does not match implemented designs",fDesign); + Fatal("ShipMuonShield", "Design %i does not match implemented designs", fDesign); } } diff --git a/passive/ShipMuonShield.h b/passive/ShipMuonShield.h index ea904dc79e..67f2282c33 100644 --- a/passive/ShipMuonShield.h +++ b/passive/ShipMuonShield.h @@ -1,100 +1,159 @@ #ifndef MuonShield_H #define MuonShield_H -#include "FairModule.h" // for FairModule #include "FairLogger.h" - -#include "Rtypes.h" // for ShipMuonShield::Class, Bool_t, etc - -#include "TGeoUniformMagField.h" +#include "FairModule.h" // for FairModule +#include "Rtypes.h" // for ShipMuonShield::Class, Bool_t, etc #include "TGeoMedium.h" #include "TGeoShapeAssembly.h" +#include "TGeoUniformMagField.h" #include "TString.h" -#include -#include #include "TVectorT.h" -enum class FieldDirection : bool { up, down }; +#include +#include + +enum class FieldDirection : bool +{ + up, + down +}; class ShipMuonShield : public FairModule { public: - - ShipMuonShield(const char* name, const Int_t Design=1, const char* Title="ShipMuonShield", - Double_t Z=0, Double_t L0=0, Double_t L1=0, Double_t L2=0, Double_t L3=0, Double_t L4=0, Double_t L5=0, Double_t L6=0, - Double_t L7=0, Double_t L8=0,Double_t gap=0,Double_t LE=0,Double_t y=400, Double_t floor=500, Double_t field=1.7, - const Int_t withCoMagnet=0, const Bool_t StepGeo=false, - const Bool_t WithConstAbsorberField=true, const Bool_t WithConstShieldField=true); - - ShipMuonShield(TString geofile, Double_t floor=500, const Int_t withCoMagnet=0, const Bool_t StepGeo=false, - const Bool_t WithConstAbsorberField=true, const Bool_t WithConstShieldField=true); - ShipMuonShield(TVectorT in_params, - Double_t floor, const Int_t withCoMagnet, const Bool_t StepGeo, const Bool_t WithConstAbsorberField, const Bool_t WithConstShieldField); - ShipMuonShield(); - virtual ~ShipMuonShield(); - void ConstructGeometry(); - ClassDef(ShipMuonShield,4) - - void SetSupports(Bool_t supports) { - fSupport = supports; - LOG(WARNING) <<"Setting supports to "<< (fSupport ? "true" : "false") << ". This will not have any effect if called after the geometry has been constructed."; - } - - protected: - - Int_t fDesign; // design of muon shield, 1=passive, active = ... - TString fGeofile; - Double_t fMuonShieldLength,fY,fField; - Double_t fFloor; - Bool_t fSupport; - Double_t dZ0,dZ1,dZ2,dZ3,dZ4,dZ5,dZ6,dZ7,dZ8,dXgap,zEndOfAbsorb,mag4Gap,midGapOut7,midGapOut8; - Int_t InitMedium(TString name); - - Int_t fWithCoMagnet; - Bool_t fStepGeo; - Bool_t fWithConstAbsorberField; - Bool_t fWithConstShieldField; - Bool_t fSC_mag; - std::vector shield_params; - - void CreateArb8(TString arbName, TGeoMedium *medium, Double_t dZ, - std::array corners, Int_t color, - TGeoUniformMagField *magField, TGeoVolume *top, - Double_t x_translation, Double_t y_translation, - Double_t z_translation); - - void CreateArb8(TString arbName, TGeoMedium *medium, Double_t dZ, - std::array corners, Int_t color, - TGeoUniformMagField *magField, TGeoVolume *top, - Double_t x_translation, Double_t y_translation, - Double_t z_translation, - Bool_t stepGeo); - - void CreateTube(TString tubeName, TGeoMedium *medium, Double_t dX, - Double_t dY, Double_t dZ, Int_t color, TGeoVolume *top, - Double_t x_translation, Double_t y_translation, - Double_t z_translation); - - Int_t Initialize(std::vector &magnetName, - std::vector &fieldDirection, - std::vector &dXIn, std::vector &dYIn, - std::vector &dXOut, std::vector &dYOut, - std::vector &dZ, std::vector &midGapIn, - std::vector &midGapOut, - std::vector &HmainSideMagIn, - std::vector &HmainSideMagOut, - std::vector &gapIn, std::vector &gapOut, - std::vector &Z); - - void CreateMagnet(TString magnetName, TGeoMedium *medium, TGeoVolume *tShield, - TGeoUniformMagField *fields[4], - FieldDirection fieldDirection, Double_t dX, Double_t dY, - Double_t dX2, Double_t dY2, Double_t dZ, Double_t middleGap, - Double_t middleGap2, Double_t HmainSideMag, - Double_t HmainSideMag2, Double_t gap, Double_t gap2, - Double_t Z, Bool_t NotMagnet, Bool_t stepGeo, Bool_t SC_key); - - + ShipMuonShield(const char* name, + const Int_t Design = 1, + const char* Title = "ShipMuonShield", + Double_t Z = 0, + Double_t L0 = 0, + Double_t L1 = 0, + Double_t L2 = 0, + Double_t L3 = 0, + Double_t L4 = 0, + Double_t L5 = 0, + Double_t L6 = 0, + Double_t L7 = 0, + Double_t L8 = 0, + Double_t gap = 0, + Double_t LE = 0, + Double_t y = 400, + Double_t floor = 500, + Double_t field = 1.7, + const Int_t withCoMagnet = 0, + const Bool_t StepGeo = false, + const Bool_t WithConstAbsorberField = true, + const Bool_t WithConstShieldField = true); + + ShipMuonShield(TString geofile, + Double_t floor = 500, + const Int_t withCoMagnet = 0, + const Bool_t StepGeo = false, + const Bool_t WithConstAbsorberField = true, + const Bool_t WithConstShieldField = true); + ShipMuonShield(TVectorT in_params, + Double_t floor, + const Int_t withCoMagnet, + const Bool_t StepGeo, + const Bool_t WithConstAbsorberField, + const Bool_t WithConstShieldField); + ShipMuonShield(); + virtual ~ShipMuonShield(); + void ConstructGeometry(); + ClassDef(ShipMuonShield, 4) + + void SetSupports(Bool_t supports) + { + fSupport = supports; + LOG(WARNING) << "Setting supports to " << (fSupport ? "true" : "false") + << ". This will not have any effect if called after the geometry has been constructed."; + } + + protected: + Int_t fDesign; // design of muon shield, 1=passive, active = ... + TString fGeofile; + Double_t fMuonShieldLength, fY, fField; + Double_t fFloor; + Bool_t fSupport; + Double_t dZ0, dZ1, dZ2, dZ3, dZ4, dZ5, dZ6, dZ7, dZ8, dXgap, zEndOfAbsorb, mag4Gap, midGapOut7, midGapOut8; + Int_t InitMedium(TString name); + + Int_t fWithCoMagnet; + Bool_t fStepGeo; + Bool_t fWithConstAbsorberField; + Bool_t fWithConstShieldField; + Bool_t fSC_mag; + std::vector shield_params; + + void CreateArb8(TString arbName, + TGeoMedium* medium, + Double_t dZ, + std::array corners, + Int_t color, + TGeoUniformMagField* magField, + TGeoVolume* top, + Double_t x_translation, + Double_t y_translation, + Double_t z_translation); + + void CreateArb8(TString arbName, + TGeoMedium* medium, + Double_t dZ, + std::array corners, + Int_t color, + TGeoUniformMagField* magField, + TGeoVolume* top, + Double_t x_translation, + Double_t y_translation, + Double_t z_translation, + Bool_t stepGeo); + + void CreateTube(TString tubeName, + TGeoMedium* medium, + Double_t dX, + Double_t dY, + Double_t dZ, + Int_t color, + TGeoVolume* top, + Double_t x_translation, + Double_t y_translation, + Double_t z_translation); + + Int_t Initialize(std::vector& magnetName, + std::vector& fieldDirection, + std::vector& dXIn, + std::vector& dYIn, + std::vector& dXOut, + std::vector& dYOut, + std::vector& dZ, + std::vector& midGapIn, + std::vector& midGapOut, + std::vector& HmainSideMagIn, + std::vector& HmainSideMagOut, + std::vector& gapIn, + std::vector& gapOut, + std::vector& Z); + + void CreateMagnet(TString magnetName, + TGeoMedium* medium, + TGeoVolume* tShield, + TGeoUniformMagField* fields[4], + FieldDirection fieldDirection, + Double_t dX, + Double_t dY, + Double_t dX2, + Double_t dY2, + Double_t dZ, + Double_t middleGap, + Double_t middleGap2, + Double_t HmainSideMag, + Double_t HmainSideMag2, + Double_t gap, + Double_t gap2, + Double_t Z, + Bool_t NotMagnet, + Bool_t stepGeo, + Bool_t SC_key); }; -#endif //MuonSield_H +#endif // MuonSield_H diff --git a/passive/ShipPassiveContFact.cxx b/passive/ShipPassiveContFact.cxx index c4798631f6..d45c326d7b 100644 --- a/passive/ShipPassiveContFact.cxx +++ b/passive/ShipPassiveContFact.cxx @@ -10,54 +10,50 @@ ///////////////////////////////////////////////////////////// #include "ShipPassiveContFact.h" -#include "FairRuntimeDb.h" // for FairRuntimeDb +#include "FairRuntimeDb.h" // for FairRuntimeDb +#include "TList.h" // for TList +#include "TString.h" // for TString -#include "TList.h" // for TList -#include "TString.h" // for TString - -#include // for strcmp, NULL +#include // for strcmp, NULL class FairParSet; using namespace std; - -//static ShipPassiveContFact gShipPassiveContFact; +// static ShipPassiveContFact gShipPassiveContFact; ShipPassiveContFact::ShipPassiveContFact() - : FairContFact() + : FairContFact() { - // Constructor (called when the library is loaded) - fName="ShipPassiveContFact"; - fTitle="Factory for parameter containers in libPassive"; - setAllContainers(); - FairRuntimeDb::instance()->addContFactory(this); + // Constructor (called when the library is loaded) + fName = "ShipPassiveContFact"; + fTitle = "Factory for parameter containers in libPassive"; + setAllContainers(); + FairRuntimeDb::instance()->addContFactory(this); } void ShipPassiveContFact::setAllContainers() { - /** Creates the Container objects with all accepted contexts and adds them to - * the list of containers for the STS library.*/ + /** Creates the Container objects with all accepted contexts and adds them to + * the list of containers for the STS library.*/ - FairContainer* p= new FairContainer("FairGeoPassivePar", - "Passive Geometry Parameters", - "TestDefaultContext"); - p->addContext("TestNonDefaultContext"); + FairContainer* p = new FairContainer("FairGeoPassivePar", "Passive Geometry Parameters", "TestDefaultContext"); + p->addContext("TestNonDefaultContext"); - containers->Add(p); + containers->Add(p); } FairParSet* ShipPassiveContFact::createContainer(FairContainer* c) { - /** Calls the constructor of the corresponding parameter container. - * For an actual context, which is not an empty string and not the default context - * of this container, the name is concatinated with the context. */ - /* const char* name=c->GetName(); - FairParSet* p=NULL; - if (strcmp(name,"FairGeoPassivePar")==0) { - p=new FairGeoPassivePar(c->getConcatName().Data(),c->GetTitle(),c->getContext()); - } - return p; -*/ - return 0; + /** Calls the constructor of the corresponding parameter container. + * For an actual context, which is not an empty string and not the default context + * of this container, the name is concatinated with the context. */ + /* const char* name=c->GetName(); + FairParSet* p=NULL; + if (strcmp(name,"FairGeoPassivePar")==0) { + p=new FairGeoPassivePar(c->getConcatName().Data(),c->GetTitle(),c->getContext()); + } + return p; + */ + return 0; } diff --git a/passive/ShipPassiveContFact.h b/passive/ShipPassiveContFact.h index 174583d565..f6272d7978 100644 --- a/passive/ShipPassiveContFact.h +++ b/passive/ShipPassiveContFact.h @@ -1,9 +1,8 @@ #ifndef PNDPASSIVECONTFACT_H #define PNDPASSIVECONTFACT_H -#include "FairContFact.h" // for FairContFact, etc - -#include "Rtypes.h" // for ShipPassiveContFact::Class, etc +#include "FairContFact.h" // for FairContFact, etc +#include "Rtypes.h" // for ShipPassiveContFact::Class, etc class FairParSet; @@ -11,11 +10,12 @@ class ShipPassiveContFact : public FairContFact { private: void setAllContainers(); + public: ShipPassiveContFact(); ~ShipPassiveContFact() {} FairParSet* createContainer(FairContainer*); - ClassDef( ShipPassiveContFact,0) // Factory for all Passive parameter containers + ClassDef(ShipPassiveContFact, 0) // Factory for all Passive parameter containers }; -#endif /* !PNDPASSIVECONTFACT_H */ +#endif /* !PNDPASSIVECONTFACT_H */ diff --git a/passive/ShipTAUMagneticSpectrometer.cxx b/passive/ShipTAUMagneticSpectrometer.cxx index ef667884a9..b901f5e4c7 100644 --- a/passive/ShipTAUMagneticSpectrometer.cxx +++ b/passive/ShipTAUMagneticSpectrometer.cxx @@ -1,38 +1,45 @@ #include "ShipTAUMagneticSpectrometer.h" +#include "FairRun.h" // for FairRun +#include "FairRuntimeDb.h" // for FairRuntimeDb #include "TGeoManager.h" -#include "FairRun.h" // for FairRun -#include "FairRuntimeDb.h" // for FairRuntimeDb -//#include "FairGeoMedia.h" -//#include "FairGeoBuilder.h" +// #include "FairGeoMedia.h" +// #include "FairGeoBuilder.h" -#include // for ostream -#include "TList.h" // for TListIter, TList (ptr only) -#include "TObjArray.h" // for TObjArray -#include "TString.h" // for TString #include "TGeoBBox.h" #include "TGeoCompositeShape.h" -#include "TGeoTube.h" -#include "TGeoMaterial.h" #include "TGeoElement.h" +#include "TGeoMaterial.h" #include "TGeoMedium.h" +#include "TGeoTube.h" #include "TGeoUniformMagField.h" -#include // for NULL -#include // for operator<<, basic_ostream, etc +#include "TList.h" // for TListIter, TList (ptr only) +#include "TObjArray.h" // for TObjArray +#include "TString.h" // for TString + +#include // for ostream +#include // for operator<<, basic_ostream, etc +#include // for NULL using namespace std; -ShipTAUMagneticSpectrometer::~ShipTAUMagneticSpectrometer() -{ -} +ShipTAUMagneticSpectrometer::~ShipTAUMagneticSpectrometer() {} ShipTAUMagneticSpectrometer::ShipTAUMagneticSpectrometer() - : FairModule("ShipTAUMagneticSpectrometer", "") -{ -} - -ShipTAUMagneticSpectrometer::ShipTAUMagneticSpectrometer(const char* name,const Double_t zLS,const Double_t FeL, const Double_t AirL, const Double_t SpectroL, const Double_t GapV, const Double_t DGap, const Double_t MGap, const Double_t mf, const char* Title) - : FairModule(name ,Title) + : FairModule("ShipTAUMagneticSpectrometer", "") +{} + +ShipTAUMagneticSpectrometer::ShipTAUMagneticSpectrometer(const char* name, + const Double_t zLS, + const Double_t FeL, + const Double_t AirL, + const Double_t SpectroL, + const Double_t GapV, + const Double_t DGap, + const Double_t MGap, + const Double_t mf, + const char* Title) + : FairModule(name, Title) { zLastSlab = zLS; IronLenght = FeL; @@ -48,40 +55,36 @@ void ShipTAUMagneticSpectrometer::ConstructGeometry() { Int_t NIronSlabs = 12; - TGeoVolume *top=gGeoManager->GetTopVolume(); - TGeoMedium *Fe = gGeoManager->GetMedium("iron"); + TGeoVolume* top = gGeoManager->GetTopVolume(); + TGeoMedium* Fe = gGeoManager->GetMedium("iron"); Double_t d = 0; - TGeoUniformMagField *magField = new TGeoUniformMagField(0.,-MagneticField,0.); - TGeoUniformMagField *RetField = new TGeoUniformMagField(0.,MagneticField,0.); + TGeoUniformMagField* magField = new TGeoUniformMagField(0., -MagneticField, 0.); + TGeoUniformMagField* RetField = new TGeoUniformMagField(0., MagneticField, 0.); - TGeoBBox *Layer = new TGeoBBox(225,400,IronLenght/2); - TGeoVolume *volLayer = new TGeoVolume("volLayer",Layer,Fe); - for(Int_t i = 0; i< NIronSlabs; i++) - { - d = zLastSlab - i*(IronLenght+AirLenght); - top->AddNode(volLayer,i,new TGeoTranslation(0, 0, d)); + TGeoBBox* Layer = new TGeoBBox(225, 400, IronLenght / 2); + TGeoVolume* volLayer = new TGeoVolume("volLayer", Layer, Fe); + for (Int_t i = 0; i < NIronSlabs; i++) { + d = zLastSlab - i * (IronLenght + AirLenght); + top->AddNode(volLayer, i, new TGeoTranslation(0, 0, d)); } volLayer->SetField(magField); - cout <<"************************************" << endl; - cout << " IronLenght+AirLenght = " << IronLenght+AirLenght << endl; + cout << "************************************" << endl; + cout << " IronLenght+AirLenght = " << IronLenght + AirLenght << endl; cout << " NIronSlabs = " << NIronSlabs << endl; - cout << " zLastSlab = "<< zLastSlab << endl; + cout << " zLastSlab = " << zLastSlab << endl; cout << d << endl; - Double_t d1 = d- (MiddleGap + IronLenght); //z coord of the center of the last layer of the first spectrometer + Double_t d1 = d - (MiddleGap + IronLenght); // z coord of the center of the last layer of the first spectrometer cout << d1 << endl; - TGeoVolume *volLayer2 = new TGeoVolume("volLayer2",Layer,Fe); - for(Int_t i = 0; i< NIronSlabs; i++) - { - Double_t d2 = d1-i*(IronLenght+AirLenght); - top->AddNode(volLayer2,i,new TGeoTranslation(0, 0, d2)); + TGeoVolume* volLayer2 = new TGeoVolume("volLayer2", Layer, Fe); + for (Int_t i = 0; i < NIronSlabs; i++) { + Double_t d2 = d1 - i * (IronLenght + AirLenght); + top->AddNode(volLayer2, i, new TGeoTranslation(0, 0, d2)); } volLayer2->SetField(RetField); - cout <<"************************************" << endl; - - + cout << "************************************" << endl; } diff --git a/passive/ShipTAUMagneticSpectrometer.h b/passive/ShipTAUMagneticSpectrometer.h index 2162a12cee..1c2ac53b1e 100644 --- a/passive/ShipTAUMagneticSpectrometer.h +++ b/passive/ShipTAUMagneticSpectrometer.h @@ -1,29 +1,34 @@ #ifndef TAUMAGNETICSPECTROMETER_H #define TAUMAGNETICSPECTROMETER_H -#include "FairModule.h" // for FairModule +#include "FairModule.h" // for FairModule +#include "Rtypes.h" // for ShipMagnet::Class, Bool_t, etc -#include "Rtypes.h" // for ShipMagnet::Class, Bool_t, etc - -#include // for string +#include // for string class ShipTAUMagneticSpectrometer : public FairModule { public: - ShipTAUMagneticSpectrometer(const char* name,const Double_t zLS,const Double_t FeL, const Double_t AirL, const Double_t SpectroL, - const Double_t GapV, const Double_t DGap, const Double_t MGap, const Double_t mf, - const char* Title="ShipTAUMagneticSpectrometer"); + ShipTAUMagneticSpectrometer(const char* name, + const Double_t zLS, + const Double_t FeL, + const Double_t AirL, + const Double_t SpectroL, + const Double_t GapV, + const Double_t DGap, + const Double_t MGap, + const Double_t mf, + const char* Title = "ShipTAUMagneticSpectrometer"); ShipTAUMagneticSpectrometer(); virtual ~ShipTAUMagneticSpectrometer(); void ConstructGeometry(); void Initialize(); - ClassDef(ShipTAUMagneticSpectrometer,1) - + ClassDef(ShipTAUMagneticSpectrometer, 1) -protected: - Double_t zLastSlab; //z distance of the center of the last Fe slab of the second spectrometer in cm from the center of the vacuum tube + protected : Double_t zLastSlab; // z distance of the center of the last Fe slab of the second spectrometer in cm + // from the center of the vacuum tube Double_t IronLenght; - Double_t AirLenght; // distance between the center of 2 iron slabs + Double_t AirLenght; // distance between the center of 2 iron slabs Double_t SpectrometerLenght; Double_t GapFromVacuum; Double_t DriftGap; @@ -31,6 +36,4 @@ class ShipTAUMagneticSpectrometer : public FairModule Double_t MagneticField; }; - - -#endif //TAUMAGNETICSPECTROMETER_H +#endif // TAUMAGNETICSPECTROMETER_H diff --git a/passive/ShipTargetStation.cxx b/passive/ShipTargetStation.cxx index c2489c3785..14b9e72e5e 100644 --- a/passive/ShipTargetStation.cxx +++ b/passive/ShipTargetStation.cxx @@ -1,192 +1,213 @@ #include "ShipTargetStation.h" -#include "TGeoManager.h" -#include "FairRun.h" // for FairRun -#include "FairRuntimeDb.h" // for FairRuntimeDb -#include // for ostream -#include "TList.h" // for TListIter, TList (ptr only) -#include "TObjArray.h" // for TObjArray -#include "TString.h" // for TString +#include "FairGeoBuilder.h" +#include "FairGeoMedia.h" +#include "FairRun.h" // for FairRun +#include "FairRuntimeDb.h" // for FairRuntimeDb #include "TGeoBBox.h" #include "TGeoCompositeShape.h" -#include "TGeoShapeAssembly.h" -#include "TGeoTube.h" +#include "TGeoManager.h" #include "TGeoMaterial.h" -#include "FairGeoMedia.h" -#include "FairGeoBuilder.h" #include "TGeoMedium.h" -#include // for NULL -#include // for operator<<, basic_ostream, etc +#include "TGeoShapeAssembly.h" +#include "TGeoTube.h" +#include "TList.h" // for TListIter, TList (ptr only) +#include "TObjArray.h" // for TObjArray +#include "TString.h" // for TString + +#include // for ostream +#include // for operator<<, basic_ostream, etc +#include // for NULL using std::cout; using std::endl; - -ShipTargetStation::~ShipTargetStation() -{ -} +ShipTargetStation::~ShipTargetStation() {} ShipTargetStation::ShipTargetStation() - : FairModule("ShipTargetStation", "") -{ -} - -ShipTargetStation::ShipTargetStation(const char* name, const Double_t tl,const Double_t al,const Double_t tz, - const Double_t az, const int nS, const Double_t sl, const char* Title ) - : FairModule(name ,Title) + : FairModule("ShipTargetStation", "") +{} + +ShipTargetStation::ShipTargetStation(const char* name, + const Double_t tl, + const Double_t al, + const Double_t tz, + const Double_t az, + const int nS, + const Double_t sl, + const char* Title) + : FairModule(name, Title) { - fTargetLength = tl; - fAbsorberLength = al; - fAbsorberZ = az; - fTargetZ = tz; - fnS = nS; - fsl = sl; + fTargetLength = tl; + fAbsorberLength = al; + fAbsorberZ = az; + fTargetZ = tz; + fnS = nS; + fsl = sl; } -ShipTargetStation::ShipTargetStation(const char* name, const Double_t tl,const Double_t tz, - const int nS, const Double_t sl, const char* Title ) - : FairModule(name ,Title) +ShipTargetStation::ShipTargetStation(const char* name, + const Double_t tl, + const Double_t tz, + const int nS, + const Double_t sl, + const char* Title) + : FairModule(name, Title) { - fTargetLength = tl; - fAbsorberLength = 0; - fAbsorberZ = 0; - fTargetZ = tz; - fnS = nS; - fsl = sl; + fTargetLength = tl; + fAbsorberLength = 0; + fAbsorberZ = 0; + fTargetZ = tz; + fnS = nS; + fsl = sl; } // ----- Private method InitMedium Int_t ShipTargetStation::InitMedium(const char* name) { - static FairGeoLoader *geoLoad=FairGeoLoader::Instance(); - static FairGeoInterface *geoFace=geoLoad->getGeoInterface(); - static FairGeoMedia *media=geoFace->getMedia(); - static FairGeoBuilder *geoBuild=geoLoad->getGeoBuilder(); - - FairGeoMedium *ShipMedium=media->getMedium(name); - - if (!ShipMedium) - { - Fatal("InitMedium","Material %s not defined in media file.", name); - return -1111; - } - TGeoMedium* medium=gGeoManager->GetMedium(name); - if (medium!=NULL) - return ShipMedium->getMediumIndex(); - return geoBuild->createMedium(ShipMedium); + static FairGeoLoader* geoLoad = FairGeoLoader::Instance(); + static FairGeoInterface* geoFace = geoLoad->getGeoInterface(); + static FairGeoMedia* media = geoFace->getMedia(); + static FairGeoBuilder* geoBuild = geoLoad->getGeoBuilder(); + + FairGeoMedium* ShipMedium = media->getMedium(name); + + if (!ShipMedium) { + Fatal("InitMedium", "Material %s not defined in media file.", name); + return -1111; + } + TGeoMedium* medium = gGeoManager->GetMedium(name); + if (medium != NULL) + return ShipMedium->getMediumIndex(); + return geoBuild->createMedium(ShipMedium); } void ShipTargetStation::ConstructGeometry() { - TGeoVolume *top=gGeoManager->GetTopVolume(); + TGeoVolume* top = gGeoManager->GetTopVolume(); InitMedium("tungsten"); - TGeoMedium *tungsten =gGeoManager->GetMedium("tungsten"); + TGeoMedium* tungsten = gGeoManager->GetMedium("tungsten"); InitMedium("iron"); - TGeoMedium *iron =gGeoManager->GetMedium("iron"); + TGeoMedium* iron = gGeoManager->GetMedium("iron"); InitMedium("H2O"); - TGeoMedium *water =gGeoManager->GetMedium("H2O"); + TGeoMedium* water = gGeoManager->GetMedium("H2O"); InitMedium("molybdenum"); - TGeoMedium *mo =gGeoManager->GetMedium("molybdenum"); - TGeoVolume *tTarget = new TGeoVolumeAssembly("TargetArea"); + TGeoMedium* mo = gGeoManager->GetMedium("molybdenum"); + TGeoVolume* tTarget = new TGeoVolumeAssembly("TargetArea"); - Double_t zPos = 0.; + Double_t zPos = 0.; Int_t slots = fnS; - slots = slots-1; - - if (fnS > 10){ - TGeoVolume *target; - TGeoVolume *slit; - //Double_t zPos = fTargetZ - fTargetLength/2.; - for (Int_t i=0; iMakeTube(nmi, material, 0., fDiameter/2., fL.at(i)/2.); - } - else { - target = gGeoManager->MakeBox(nmi, material, fDiameter/2., fDiameter/2., fL.at(i)/2.); - } - if (fM.at(i)=="molybdenum") { - target->SetLineColor(28); - } else {target->SetLineColor(38);}; // silver/blue - tTarget->AddNode(target, 1, new TGeoTranslation(0, 0, zPos + fL.at(i)/2.) ); - if (i < slots){ - if(fnS == 18) { - slit = gGeoManager->MakeTube(sm, water, 0., fDiameter/2., fsl/2.); - } - else { - slit = gGeoManager->MakeBox(sm, water, fDiameter/2., fDiameter/2., fsl/2.); - } - slit->SetLineColor(7); // cyan - tTarget->AddNode(slit, 1, new TGeoTranslation(0, 0, zPos+fL.at(i)+fsl/2.) ); - zPos+=fL.at(i)+fsl; - } else { - zPos+=fL.at(i); - } - } - }else if(fnS > 0){ - Double_t dZ = (fTargetLength - (fnS-1)*fsl)/float(fnS); - // target made of tungsten and air slits - for (Int_t i=0; iMakeTube(nmi, tungsten, 0, 25, dZ/2.); - target->SetLineColor(38); // silver/blue - tTarget->AddNode(target, 1, new TGeoTranslation(0, 0, zPos+dZ/2.)); - TGeoVolume *slit = gGeoManager->MakeTube(sm, water, 0, 25, fsl/2.); - slit->SetLineColor(7); // cyan - tTarget->AddNode(slit, 1, new TGeoTranslation(0, 0, zPos+dZ+fsl/2.)); - zPos+=dZ+fsl; - } - TString nmi = "Target_"; nmi += fnS; - TGeoVolume *target = gGeoManager->MakeTube(nmi, tungsten, 0, 25, dZ/2.); - target->SetLineColor(38); // silver/blue - tTarget->AddNode(target, 1, new TGeoTranslation(0, 0, zPos+dZ/2.)); - } - else{ - // target made of solid tungsten - TGeoVolume *target = gGeoManager->MakeTube("Target", tungsten, 0, 25, fTargetLength/2.); - target->SetLineColor(38); // silver/blue - tTarget->AddNode(target, 1, new TGeoTranslation(0, 0, fTargetZ)); + slots = slots - 1; + + if (fnS > 10) { + TGeoVolume* target; + TGeoVolume* slit; + // Double_t zPos = fTargetZ - fTargetLength/2.; + for (Int_t i = 0; i < fnS; i++) { + TString nmi = "Target_"; + nmi += i + 1; + TString sm = "Slit_"; + sm += i + 1; + TGeoMedium* material; + if (fM.at(i) == "molybdenum") { + material = mo; + }; + if (fM.at(i) == "tungsten") { + material = tungsten; + }; + + if (fnS == 18) { // new target layout + target = gGeoManager->MakeTube(nmi, material, 0., fDiameter / 2., fL.at(i) / 2.); + } else { + target = gGeoManager->MakeBox(nmi, material, fDiameter / 2., fDiameter / 2., fL.at(i) / 2.); + } + if (fM.at(i) == "molybdenum") { + target->SetLineColor(28); + } else { + target->SetLineColor(38); + }; // silver/blue + tTarget->AddNode(target, 1, new TGeoTranslation(0, 0, zPos + fL.at(i) / 2.)); + if (i < slots) { + if (fnS == 18) { + slit = gGeoManager->MakeTube(sm, water, 0., fDiameter / 2., fsl / 2.); + } else { + slit = gGeoManager->MakeBox(sm, water, fDiameter / 2., fDiameter / 2., fsl / 2.); + } + slit->SetLineColor(7); // cyan + tTarget->AddNode(slit, 1, new TGeoTranslation(0, 0, zPos + fL.at(i) + fsl / 2.)); + zPos += fL.at(i) + fsl; + } else { + zPos += fL.at(i); + } + } + } else if (fnS > 0) { + Double_t dZ = (fTargetLength - (fnS - 1) * fsl) / float(fnS); + // target made of tungsten and air slits + for (Int_t i = 0; i < fnS - 1; i++) { + TString nmi = "Target_"; + nmi += i; + TString sm = "Slit_"; + sm += i; + TGeoVolume* target = gGeoManager->MakeTube(nmi, tungsten, 0, 25, dZ / 2.); + target->SetLineColor(38); // silver/blue + tTarget->AddNode(target, 1, new TGeoTranslation(0, 0, zPos + dZ / 2.)); + TGeoVolume* slit = gGeoManager->MakeTube(sm, water, 0, 25, fsl / 2.); + slit->SetLineColor(7); // cyan + tTarget->AddNode(slit, 1, new TGeoTranslation(0, 0, zPos + dZ + fsl / 2.)); + zPos += dZ + fsl; + } + TString nmi = "Target_"; + nmi += fnS; + TGeoVolume* target = gGeoManager->MakeTube(nmi, tungsten, 0, 25, dZ / 2.); + target->SetLineColor(38); // silver/blue + tTarget->AddNode(target, 1, new TGeoTranslation(0, 0, zPos + dZ / 2.)); + } else { + // target made of solid tungsten + TGeoVolume* target = gGeoManager->MakeTube("Target", tungsten, 0, 25, fTargetLength / 2.); + target->SetLineColor(38); // silver/blue + tTarget->AddNode(target, 1, new TGeoTranslation(0, 0, fTargetZ)); } - if (fAbsorberLength>0){ // otherwise, magnetized hadron absorber defined in ShipMuonShield.cxx - zPos = fTargetZ - fTargetLength/2.; - // Absorber made of iron - TGeoVolume *absorber; - absorber = gGeoManager->MakeTube("Absorber", iron, 0, 400, fAbsorberLength/2.); // 1890 - absorber->SetLineColor(42); // brown / light red - tTarget->AddNode(absorber, 1, new TGeoTranslation(0, 0, fAbsorberZ-zPos)); + if (fAbsorberLength > 0) { // otherwise, magnetized hadron absorber defined in ShipMuonShield.cxx + zPos = fTargetZ - fTargetLength / 2.; + // Absorber made of iron + TGeoVolume* absorber; + absorber = gGeoManager->MakeTube("Absorber", iron, 0, 400, fAbsorberLength / 2.); // 1890 + absorber->SetLineColor(42); // brown / light red + tTarget->AddNode(absorber, 1, new TGeoTranslation(0, 0, fAbsorberZ - zPos)); } // put iron shielding around target - if (fnS > 10){ - Float_t xTot = 400./2.; // all in cm - Float_t yTot = 400./2.; - Float_t spaceTopBot = 10.; - Float_t spaceSide = 5.; - TGeoVolume *moreShieldingTopBot = gGeoManager->MakeBox("moreShieldingTopBot", iron, xTot, yTot/2., fTargetLength/2.); - moreShieldingTopBot->SetLineColor(33); - tTarget->AddNode(moreShieldingTopBot, 1, new TGeoTranslation(0., fDiameter/2. +spaceTopBot+yTot/2.,fTargetLength/2.)); - tTarget->AddNode(moreShieldingTopBot, 2, new TGeoTranslation(0.,-fDiameter/2. -spaceTopBot-yTot/2.,fTargetLength/2.)); - TGeoVolume *moreShieldingSide = gGeoManager->MakeBox("moreShieldingSide", iron, xTot/2., (fDiameter+1.9*spaceTopBot)/2., fTargetLength/2.); - moreShieldingSide->SetLineColor(33); - tTarget->AddNode(moreShieldingSide, 1, new TGeoTranslation(fDiameter/2.+spaceSide+xTot/2.,0.,fTargetLength/2.)); - tTarget->AddNode(moreShieldingSide, 2, new TGeoTranslation(-fDiameter/2.-spaceSide-xTot/2.,0.,fTargetLength/2.)); - }else{ - TGeoVolume *moreShielding = gGeoManager->MakeTube("MoreShielding", iron, 30, 400, fTargetLength/2.); - moreShielding->SetLineColor(43); // - tTarget->AddNode(moreShielding, 1, new TGeoTranslation(0, 0, fTargetLength/2.)); + if (fnS > 10) { + Float_t xTot = 400. / 2.; // all in cm + Float_t yTot = 400. / 2.; + Float_t spaceTopBot = 10.; + Float_t spaceSide = 5.; + TGeoVolume* moreShieldingTopBot = + gGeoManager->MakeBox("moreShieldingTopBot", iron, xTot, yTot / 2., fTargetLength / 2.); + moreShieldingTopBot->SetLineColor(33); + tTarget->AddNode(moreShieldingTopBot, + 1, + new TGeoTranslation(0., fDiameter / 2. + spaceTopBot + yTot / 2., fTargetLength / 2.)); + tTarget->AddNode(moreShieldingTopBot, + 2, + new TGeoTranslation(0., -fDiameter / 2. - spaceTopBot - yTot / 2., fTargetLength / 2.)); + TGeoVolume* moreShieldingSide = gGeoManager->MakeBox( + "moreShieldingSide", iron, xTot / 2., (fDiameter + 1.9 * spaceTopBot) / 2., fTargetLength / 2.); + moreShieldingSide->SetLineColor(33); + tTarget->AddNode( + moreShieldingSide, 1, new TGeoTranslation(fDiameter / 2. + spaceSide + xTot / 2., 0., fTargetLength / 2.)); + tTarget->AddNode( + moreShieldingSide, 2, new TGeoTranslation(-fDiameter / 2. - spaceSide - xTot / 2., 0., fTargetLength / 2.)); + } else { + TGeoVolume* moreShielding = gGeoManager->MakeTube("MoreShielding", iron, 30, 400, fTargetLength / 2.); + moreShielding->SetLineColor(43); // + tTarget->AddNode(moreShielding, 1, new TGeoTranslation(0, 0, fTargetLength / 2.)); } - top->AddNode(tTarget, 1, new TGeoTranslation(0, 0,fTargetZ - fTargetLength/2.)); + top->AddNode(tTarget, 1, new TGeoTranslation(0, 0, fTargetZ - fTargetLength / 2.)); - if (fAbsorberLength>0){ - cout << "target and absorber positioned at " << fTargetZ <<" "<< fAbsorberZ << " m"<< endl; - }else{ - cout << "target at " << fTargetZ/100. <<"m "<< endl; + if (fAbsorberLength > 0) { + cout << "target and absorber positioned at " << fTargetZ << " " << fAbsorberZ << " m" << endl; + } else { + cout << "target at " << fTargetZ / 100. << "m " << endl; } } diff --git a/passive/ShipTargetStation.h b/passive/ShipTargetStation.h index fa384a3f2a..a5a023774a 100644 --- a/passive/ShipTargetStation.h +++ b/passive/ShipTargetStation.h @@ -1,38 +1,50 @@ #ifndef TargetStation_H #define TargetStation_H -#include "FairModule.h" // for FairModule -#include "Rtypes.h" // for ShipTargetStation::Class, Bool_t, etc -#include // for string +#include "FairModule.h" // for FairModule +#include "Rtypes.h" // for ShipTargetStation::Class, Bool_t, etc + #include +#include // for string class ShipTargetStation : public FairModule { public: - ShipTargetStation(const char* name,const Double_t tl,const Double_t al,const Double_t tz,const Double_t az, - const int nS, const Double_t sl, const char* Title="ShipTargetStation"); - ShipTargetStation(const char* name,const Double_t tl,const Double_t tz, - const int nS, const Double_t sl, const char* Title="ShipTargetStation"); + ShipTargetStation(const char* name, + const Double_t tl, + const Double_t al, + const Double_t tz, + const Double_t az, + const int nS, + const Double_t sl, + const char* Title = "ShipTargetStation"); + ShipTargetStation(const char* name, + const Double_t tl, + const Double_t tz, + const int nS, + const Double_t sl, + const char* Title = "ShipTargetStation"); ShipTargetStation(); virtual ~ShipTargetStation(); void ConstructGeometry(); - void SetLayerPosMat(Float_t d, std::vector L, std::vector M){ - fDiameter = d; - fL = L; - fM = M; - } - ClassDef(ShipTargetStation,4) - protected: + void SetLayerPosMat(Float_t d, std::vector L, std::vector M) + { + fDiameter = d; + fL = L; + fM = M; + } + ClassDef(ShipTargetStation, 4) protected + : - Double_t fTargetLength; // - Double_t fAbsorberLength; // - Double_t fAbsorberZ; // - Double_t fTargetZ; // - Double_t fDiameter; // - std::vector fL; // - std::vector fM; // - Int_t InitMedium(const char* name); - Int_t fnS; - Double_t fsl; + Double_t fTargetLength; // + Double_t fAbsorberLength; // + Double_t fAbsorberZ; // + Double_t fTargetZ; // + Double_t fDiameter; // + std::vector fL; // + std::vector fM; // + Int_t InitMedium(const char* name); + Int_t fnS; + Double_t fsl; }; -#endif //TargetStation_H +#endif // TargetStation_H diff --git a/pid/CMakeLists.txt b/pid/CMakeLists.txt index 9d03c8c7cd..eb88d0551c 100644 --- a/pid/CMakeLists.txt +++ b/pid/CMakeLists.txt @@ -1,33 +1,23 @@ -# Create a library called "libmuon" which includes the source files given in -# the array . -# The extension is already found. Any number of sources could be listed here. +# Create a library called "libmuon" which includes the source files given in the +# array . The extension is already found. Any number of sources could be listed +# here. -set(INCLUDE_DIRECTORIES -${CMAKE_SOURCE_DIR}/shipdata -${CMAKE_SOURCE_DIR}/pid -${genfit2_INCDIR} -) +set(INCLUDE_DIRECTORIES ${CMAKE_SOURCE_DIR}/shipdata ${CMAKE_SOURCE_DIR}/pid + ${genfit2_INCDIR}) -include_directories( ${INCLUDE_DIRECTORIES}) +include_directories(${INCLUDE_DIRECTORIES}) include_directories(SYSTEM ${SYSTEM_INCLUDE_DIRECTORIES}) -set(LINK_DIRECTORIES -${ROOT_LIBRARY_DIR} -${FAIRROOT_LIBRARY_DIR} -${genfit2_LIBDIR} -) +set(LINK_DIRECTORIES ${ROOT_LIBRARY_DIR} ${FAIRROOT_LIBRARY_DIR} + ${genfit2_LIBDIR}) -link_directories( ${LINK_DIRECTORIES}) +link_directories(${LINK_DIRECTORIES}) -set(SRCS -#Put here your sourcefiles -pid.cxx -) +set(SRCS # Put here your sourcefiles + pid.cxx) -Set(LINKDEF pidLinkDef.h) -Set(LIBRARY_NAME pid) -Set(DEPENDENCIES - Base ShipData -) +set(LINKDEF pidLinkDef.h) +set(LIBRARY_NAME pid) +set(DEPENDENCIES Base ShipData) -GENERATE_LIBRARY() +generate_library() diff --git a/pid/pid.cxx b/pid/pid.cxx index 2d77848ff8..d09a0dee8d 100644 --- a/pid/pid.cxx +++ b/pid/pid.cxx @@ -6,17 +6,21 @@ using namespace std; pid::pid() - : TObject(), - fTrackID(-999), //! track index - fElectronID(-999), //! electron id - fHadronID(-999), //! hadron id - fMuonID(-999), //! muon id - fTrackPID(-999) //! track pid + : TObject() + , fTrackID(-999) + , //! track index + fElectronID(-999) + , //! electron id + fHadronID(-999) + , //! hadron id + fMuonID(-999) + , //! muon id + fTrackPID(-999) //! track pid { -// std::cout<<"create"< it is an electron @@ -59,7 +57,7 @@ class pid : public TObject /** container for data points */ - ClassDef(pid,2) + ClassDef(pid, 2) }; -#endif //PID_H +#endif // PID_H diff --git a/python/AddDiMuonDecayChannelsToG4.py b/python/AddDiMuonDecayChannelsToG4.py index c958d4c200..f331d4507f 100644 --- a/python/AddDiMuonDecayChannelsToG4.py +++ b/python/AddDiMuonDecayChannelsToG4.py @@ -1,26 +1,31 @@ import ROOT + ROOT.gROOT.ProcessLine('#include "Geant4/G4ParticleTable.hh"') ROOT.gROOT.ProcessLine('#include "Geant4/G4DecayTable.hh"') ROOT.gROOT.ProcessLine('#include "Geant4/G4PhaseSpaceDecayChannel.hh"') + def Initialize(p8): -# take decay and branching ratios from Pythia8 - pt = ROOT.G4ParticleTable.GetParticleTable() - for vreso in [223,333,113]: - particleG4 = pt.FindParticle(vreso) - particleP8 = p8.particleData.particleDataEntryPtr(vreso) - decayTable = ROOT.G4DecayTable() - for i in range(particleP8.sizeChannels()): - achannel = particleP8.channel(i) - bR = achannel.bRatio() - mul = achannel.multiplicity() - dl = [] - for daughter in range(4): - if daughterz0 = 716, sets the middle of the production area - #setup - CMBG.n_EVENTS = 400000; # #simulated events per "spill" - CMBG.minE = 1.0 #low energy limit for the Low-energy simulation [GeV] + CMBG.yBox = 600 # box top layer [cm] + CMBG.xBox = 300 # box side layer [cm] + CMBG.zBox = 3650 # box length [cm] + CMBG.z0 = zmiddle # relative coordinate system [cm] (Z_muonstation + (Z_veto - 2 * Z_Tub1))/2,... Z_veto <0 ! ->z0 = 716, sets the middle of the production area + # setup + CMBG.n_EVENTS = 400000 # #simulated events per "spill" + CMBG.minE = 1.0 # low energy limit for the Low-energy simulation [GeV] diff --git a/python/PythiaList.py b/python/PythiaList.py index 22289b7e66..1a64102579 100644 --- a/python/PythiaList.py +++ b/python/PythiaList.py @@ -1,5 +1,9 @@ -import ROOT,time,sys -id=int(sys.argv[1]) +import sys +import time + +import ROOT + +id = int(sys.argv[1]) ROOT.gSystem.Load("libEG") ROOT.gSystem.Load("libpythia8") ROOT.gSystem.Load("libEGPythia8") diff --git a/python/ShieldUtils.py b/python/ShieldUtils.py index 4cb40de2e6..010cbdb576 100644 --- a/python/ShieldUtils.py +++ b/python/ShieldUtils.py @@ -1,35 +1,26 @@ def find_shield_center(ship_geo): - zEndOfAbsorb = ship_geo.muShield.z - ship_geo.muShield.length / 2; + zEndOfAbsorb = ship_geo.muShield.z - ship_geo.muShield.length / 2 dZ = [None] * 9 Z = [None] * 9 - zgap = 10. - dZ[0] = ship_geo.muShield.dZ1 - zgap / 2; - Z[0] = zEndOfAbsorb + dZ[0] + zgap; - - dZ[1] = ship_geo.muShield.dZ2 - zgap / 2; - Z[1] = Z[0] + dZ[0] + dZ[1] + zgap; - - dZ[2] = ship_geo.muShield.dZ3 - zgap / 2; - Z[2] = Z[1] + dZ[1] + dZ[2] + 2 * zgap; - - dZ[3] = ship_geo.muShield.dZ4 - zgap / 2; - Z[3] = Z[2] + dZ[2] + dZ[3] + zgap; - - dZ[4] = ship_geo.muShield.dZ5 - zgap / 2; - Z[4] = Z[3] + dZ[3] + dZ[4] + zgap; - - dZ[5] = ship_geo.muShield.dZ6 - zgap / 2; - Z[5] = Z[4] + dZ[4] + dZ[5] + zgap; - - dZ[6] = ship_geo.muShield.dZ7 - zgap / 2; - Z[6] = Z[5] + dZ[5] + dZ[6] + zgap; - - dZ[7] = ship_geo.muShield.dZ8 - zgap / 2; - Z[7] = Z[6] + dZ[6] + dZ[7] + zgap; - - dZ[8] = 10.; - Z[8] = Z[7] + dZ[7] + dZ[8]; - + zgap = 10.0 + dZ[0] = ship_geo.muShield.dZ1 - zgap / 2 + Z[0] = zEndOfAbsorb + dZ[0] + zgap + dZ[1] = ship_geo.muShield.dZ2 - zgap / 2 + Z[1] = Z[0] + dZ[0] + dZ[1] + zgap + dZ[2] = ship_geo.muShield.dZ3 - zgap / 2 + Z[2] = Z[1] + dZ[1] + dZ[2] + 2 * zgap + dZ[3] = ship_geo.muShield.dZ4 - zgap / 2 + Z[3] = Z[2] + dZ[2] + dZ[3] + zgap + dZ[4] = ship_geo.muShield.dZ5 - zgap / 2 + Z[4] = Z[3] + dZ[3] + dZ[4] + zgap + dZ[5] = ship_geo.muShield.dZ6 - zgap / 2 + Z[5] = Z[4] + dZ[4] + dZ[5] + zgap + dZ[6] = ship_geo.muShield.dZ7 - zgap / 2 + Z[6] = Z[5] + dZ[5] + dZ[6] + zgap + dZ[7] = ship_geo.muShield.dZ8 - zgap / 2 + Z[7] = Z[6] + dZ[6] + dZ[7] + zgap + dZ[8] = 10.0 + Z[8] = Z[7] + dZ[7] + dZ[8] shield_center = (Z[2] + Z[8] + dZ[8] - dZ[2]) / 2 shield_half_lenth = abs((Z[2] - dZ[2]) - (Z[8] + dZ[8])) / 2 return shield_center, shield_half_lenth diff --git a/python/ShipGeo.py b/python/ShipGeo.py index d9fefed7d7..b45c04c47b 100644 --- a/python/ShipGeo.py +++ b/python/ShipGeo.py @@ -1,58 +1,77 @@ -import shipunit as u import ROOT +import shipunit as u + fDesign = 2 -class ShipGeo(): - def __init__(self,z=0): - self.z = z + + +class ShipGeo: + def __init__(self, z=0): + self.z = z + def zPositions(): - main = sys.modules['__main__'] - if hasattr(main,'ShipGeo'): - for x in ShipGeo: - if hasattr(eval('ShipGeo.'+x),'z'): print(x,'z=',eval('ShipGeo.'+x+'.z')) + main = sys.modules["__main__"] + if hasattr(main, "ShipGeo"): + for x in ShipGeo: + if hasattr(eval("ShipGeo." + x), "z"): + print(x, "z=", eval("ShipGeo." + x + ".z")) -vetoStation = ShipGeo(-2390.*u.cm) -TrackStation1 = ShipGeo(1510.*u.cm) -TrackStation2 = ShipGeo(1710.*u.cm) -TrackStation3 = ShipGeo(2150.*u.cm) -TrackStation4 = ShipGeo(2370.*u.cm) + +vetoStation = ShipGeo(-2390.0 * u.cm) +TrackStation1 = ShipGeo(1510.0 * u.cm) +TrackStation2 = ShipGeo(1710.0 * u.cm) +TrackStation3 = ShipGeo(2150.0 * u.cm) +TrackStation4 = ShipGeo(2370.0 * u.cm) z = TrackStation2.z + 0.5 * (TrackStation3.z - TrackStation2.z) Bfield = ShipGeo(z) -Bfield.max = 1.5*u.kilogauss # was 1.15 in EOI +Bfield.max = 1.5 * u.kilogauss # was 1.15 in EOI # target absorber muon shield setup -decayVolume = ShipGeo(0*u.cm) -decayVolume.length = 50*u.m - -muShield = ShipGeo(0*u.cm) -muShield.dZ1 = 2.5*u.m -muShield.dZ2 = 3.5*u.m -muShield.dZ3 = 3.0*u.m -muShield.dZ4 = 3.0*u.m -muShield.dZ5 = 2.5*u.m -muShield.dZ6 = 2.5*u.m -muShield.LE = 5*u.m +decayVolume = ShipGeo(0 * u.cm) +decayVolume.length = 50 * u.m + +muShield = ShipGeo(0 * u.cm) +muShield.dZ1 = 2.5 * u.m +muShield.dZ2 = 3.5 * u.m +muShield.dZ3 = 3.0 * u.m +muShield.dZ4 = 3.0 * u.m +muShield.dZ5 = 2.5 * u.m +muShield.dZ6 = 2.5 * u.m +muShield.LE = 5 * u.m # for passive design, fDesign==1 -if fDesign == 1: muShield.length = 70*u.m +if fDesign == 1: + muShield.length = 70 * u.m # for active design, fDesign==2 -if fDesign == 2: muShield.length = 2*(muShield.dZ1+muShield.dZ2+muShield.dZ3+muShield.dZ4+muShield.dZ5+muShield.dZ6) + muShield.LE # leave some space for nu-tau detector -muShield.z = -decayVolume.length/2.-muShield.length/2. +if fDesign == 2: + muShield.length = ( + 2 + * ( + muShield.dZ1 + + muShield.dZ2 + + muShield.dZ3 + + muShield.dZ4 + + muShield.dZ5 + + muShield.dZ6 + ) + + muShield.LE + ) # leave some space for nu-tau detector +muShield.z = -decayVolume.length / 2.0 - muShield.length / 2.0 -hadronAbsorber = ShipGeo(0*u.cm) -hadronAbsorber.length= 3.0*u.m -hadronAbsorber.z = muShield.z - muShield.length/2. - hadronAbsorber.length/2. +hadronAbsorber = ShipGeo(0 * u.cm) +hadronAbsorber.length = 3.0 * u.m +hadronAbsorber.z = muShield.z - muShield.length / 2.0 - hadronAbsorber.length / 2.0 -target = ShipGeo(0*u.cm) -target.length = 50*u.cm -target.z = hadronAbsorber.z - hadronAbsorber.length/2. - target.length/2. +target = ShipGeo(0 * u.cm) +target.length = 50 * u.cm +target.z = hadronAbsorber.z - hadronAbsorber.length / 2.0 - target.length / 2.0 # interaction point, start of target -target.z0 = target.z - target.length/2. +target.z0 = target.z - target.length / 2.0 # straws of tracking stations -straw = ShipGeo(0*u.cm) -straw.length = 250.*u.cm -straw.resol = 0.01*u.cm -straw.pitch = 1.*u.cm -straw.stereoAngle = 5./180.*ROOT.TMath.Pi() +straw = ShipGeo(0 * u.cm) +straw.length = 250.0 * u.cm +straw.resol = 0.01 * u.cm +straw.pitch = 1.0 * u.cm +straw.stereoAngle = 5.0 / 180.0 * ROOT.TMath.Pi() diff --git a/python/ShipGeoConfig.py b/python/ShipGeoConfig.py index 969b94293a..7f4b9ea815 100644 --- a/python/ShipGeoConfig.py +++ b/python/ShipGeoConfig.py @@ -1,8 +1,9 @@ import os -import re import pickle +import re from contextlib import contextmanager + def expand_env(string): """ Expand environment variables in string: @@ -13,7 +14,9 @@ def expand_env(string): if m is None: break (env_token, env_name) = m.groups() - assert env_name in os.environ, "Environment variable '%s' is not defined" % env_name + assert env_name in os.environ, ( + "Environment variable '%s' is not defined" % env_name + ) env_value = os.environ[env_name] string = string.replace(env_token, env_value) return string @@ -31,13 +34,14 @@ def __getitem__(cls, key): return cls._instances[cls][key] def delitem(cls, key): - del(cls._instances[cls][key]) + del cls._instances[cls][key] class ConfigRegistry(dict, metaclass=_SingletonDict): """ Singleton registry of all Configurations """ + recent_config_name = None @staticmethod @@ -47,7 +51,7 @@ def loadpy(filename, **kwargs): @staticmethod def loadpys(config_string, **kwargs): - string_unixlf = config_string.replace('\r', '') + string_unixlf = config_string.replace("\r", "") exec(string_unixlf, kwargs) return ConfigRegistry.get_latest_config() @@ -63,7 +67,9 @@ def __init__(self): def register_config(name=None, base=None): registry = ConfigRegistry() if base is not None: - assert base in registry, "no base configuration (%s) found in the registry" % base + assert base in registry, ( + "no base configuration (%s) found in the registry" % base + ) config = registry[base].clone() else: config = Config() @@ -93,6 +99,7 @@ class AttrDict(dict): d['key'] = 1 assert d.key == 1 """ + def __init__(self, *args, **kwargs): super(AttrDict, self).__init__(*args, **kwargs) self.__dict__ = self @@ -139,4 +146,10 @@ def dump(self, filename): return fh.write(self.dumps()) def __str__(self): - return "ShipGeoConfig:\n " + "\n ".join(["%s: %s" % (k, self[k].__str__()) for k in sorted(self.keys()) if not k.startswith("_")]) + return "ShipGeoConfig:\n " + "\n ".join( + [ + "%s: %s" % (k, self[k].__str__()) + for k in sorted(self.keys()) + if not k.startswith("_") + ] + ) diff --git a/python/ShipStyle.py b/python/ShipStyle.py index 2de83ac80e..0b98103e3b 100755 --- a/python/ShipStyle.py +++ b/python/ShipStyle.py @@ -1,189 +1,193 @@ # Global scope variables from ROOT import * from ROOT import Double -lhcbstyle = TStyle() # general lhcb style -lhcbName = TPaveText() # standard lhcb text for plot + +lhcbstyle = TStyle() # general lhcb style +lhcbName = TPaveText() # standard lhcb text for plot lhcbLabel = TText # style for Ttext -lhcbLatex = TLatex #style for TLatex +lhcbLatex = TLatex # style for TLatex # define names for colours -black=1 -red=2 -green=3 -blue=4 -yellow=5 -magenta=6 -cyan=7 -purple=9 +black = 1 +red = 2 +green = 3 +blue = 4 +yellow = 5 +magenta = 6 +cyan = 7 +purple = 9 -def lhcbstyleSetup(): -################################## -# PURPOSE: -# -# This macro defines a standard style for (black-and-white) -# "publication quality" LHCb ROOT plots. -# -# USAGE: -# -# Include the lines -# gROOT.ProcessLine(".L lhcbstyle.C") -# lhcbstyle() -# at the beginning of your root macro. -# -# Example usage is given in myPlot.C -# -# COMMENTS: -# -# Font: -# -# The font is chosen to be 62, this is helvetica-bold-r-normal with -# precision 2. -# -# "Landscape histograms": -# -# The style here is designed for more or less square plots. -# For longer histograms, or canvas with many pads, adjustements are needed. -# For instance, for a canvas with 1x5 histograms: -# TCanvas* c1 = new TCanvas("c1", "L0 muons", 600, 800) -# c1.Divide(1,5) -# Adaptions like the following will be needed: -# lhcbstyle.SetTickLength(0.05,"x") -# lhcbstyle.SetTickLength(0.01,"y") -# lhcbstyle.SetLabelSize(0.15,"x") -# lhcbstyle.SetLabelSize(0.1,"y") -# lhcbstyle.SetStatW(0.15) -# lhcbstyle.SetStatH(0.5) -# -# Authors: Thomas Schietinger, Andrew Powell, Chris Parkes -# Maintained by Editorial board member (currently Chris) -#################################/ - - lhcbstyle=TStyle("lhcbstyle","Standard LHCb plots style") - -# use helvetica-bold-r-normal, precision 2 (rotatable) - lhcbFont = 62 -# line thickness - lhcbWidth = int(3.00) - -# use plain black on white colors - lhcbstyle.SetFrameBorderMode(0) - lhcbstyle.SetCanvasBorderMode(0) - lhcbstyle.SetPadBorderMode(0) - lhcbstyle.SetPadColor(0) - lhcbstyle.SetCanvasColor(0) - lhcbstyle.SetStatColor(0) - lhcbstyle.SetPalette(1) - -# set the paper & margin sizes - lhcbstyle.SetPaperSize(20,26) - lhcbstyle.SetPadTopMargin(0.05) - lhcbstyle.SetPadRightMargin(0.05) # increase for colz plots - lhcbstyle.SetPadBottomMargin(0.16) - lhcbstyle.SetPadLeftMargin(0.14) - -# use large fonts - lhcbstyle.SetTextFont(lhcbFont) - lhcbstyle.SetTextSize(0.08) - lhcbstyle.SetLabelFont(lhcbFont,"x") - lhcbstyle.SetLabelFont(lhcbFont,"y") - lhcbstyle.SetLabelFont(lhcbFont,"z") - lhcbstyle.SetLabelSize(0.04,"x") - lhcbstyle.SetLabelSize(0.04,"y") - lhcbstyle.SetLabelSize(0.04,"z") - lhcbstyle.SetTitleFont(lhcbFont) - lhcbstyle.SetTitleSize(0.05,"x") - lhcbstyle.SetTitleSize(0.05,"y") - lhcbstyle.SetTitleSize(0.05,"z") - -# use bold lines and markers - lhcbstyle.SetLineWidth(lhcbWidth) - lhcbstyle.SetFrameLineWidth(lhcbWidth) - lhcbstyle.SetHistLineWidth(lhcbWidth) - lhcbstyle.SetFuncWidth(lhcbWidth) - lhcbstyle.SetGridWidth(lhcbWidth) - lhcbstyle.SetLineStyleString(2,"[12 12]") # postscript dashes - lhcbstyle.SetMarkerStyle(20) - lhcbstyle.SetMarkerSize(1.5) - -# label offsets - lhcbstyle.SetLabelOffset(0.015) - -# by default, do not display histogram decorations: - lhcbstyle.SetOptStat(0) - lhcbstyle.SetOptStat("emr") # show only nent -e , mean - m , rms -r -# full opts at http:#root.cern.ch/root/html/TStyle.html#TStyle:SetOptStat - lhcbstyle.SetStatFormat("6.3g") # specified as c printf options - lhcbstyle.SetOptTitle(0) - lhcbstyle.SetOptFit(0) -#lhcbstyle.SetOptFit(1011) # order is probability, Chi2, errors, parameters - -# look of the statistics box: - lhcbstyle.SetStatBorderSize(0) - lhcbstyle.SetStatFont(lhcbFont) - lhcbstyle.SetStatFontSize(0.05) - lhcbstyle.SetStatX(0.9) - lhcbstyle.SetStatY(0.9) - lhcbstyle.SetStatW(0.25) - lhcbstyle.SetStatH(0.15) -# put tick marks on top and RHS of plots - lhcbstyle.SetPadTickX(1) - lhcbstyle.SetPadTickY(1) - -# histogram divisions: only 5 in x to avoid label overlaps - lhcbstyle.SetNdivisions(505,"x") - lhcbstyle.SetNdivisions(510,"y") - - -#define style for text - lhcbLabel = TText() - lhcbLabel.SetTextFont(lhcbFont) - lhcbLabel.SetTextColor(1) - lhcbLabel.SetTextSize(0.04) - lhcbLabel.SetTextAlign(12) - -# define style of latex text - lhcbLatex = TLatex() - lhcbLatex.SetTextFont(lhcbFont) - lhcbLatex.SetTextColor(1) - lhcbLatex.SetTextSize(0.04) - lhcbLatex.SetTextAlign(12) - -# set this style - gROOT.SetStyle("lhcbstyle") - gROOT.ForceStyle() +def lhcbstyleSetup(): + ################################## + # PURPOSE: + # + # This macro defines a standard style for (black-and-white) + # "publication quality" LHCb ROOT plots. + # + # USAGE: + # + # Include the lines + # gROOT.ProcessLine(".L lhcbstyle.C") + # lhcbstyle() + # at the beginning of your root macro. + # + # Example usage is given in myPlot.C + # + # COMMENTS: + # + # Font: + # + # The font is chosen to be 62, this is helvetica-bold-r-normal with + # precision 2. + # + # "Landscape histograms": + # + # The style here is designed for more or less square plots. + # For longer histograms, or canvas with many pads, adjustements are needed. + # For instance, for a canvas with 1x5 histograms: + # TCanvas* c1 = new TCanvas("c1", "L0 muons", 600, 800) + # c1.Divide(1,5) + # Adaptions like the following will be needed: + # lhcbstyle.SetTickLength(0.05,"x") + # lhcbstyle.SetTickLength(0.01,"y") + # lhcbstyle.SetLabelSize(0.15,"x") + # lhcbstyle.SetLabelSize(0.1,"y") + # lhcbstyle.SetStatW(0.15) + # lhcbstyle.SetStatH(0.5) + # + # Authors: Thomas Schietinger, Andrew Powell, Chris Parkes + # Maintained by Editorial board member (currently Chris) + #################################/ + + lhcbstyle = TStyle("lhcbstyle", "Standard LHCb plots style") + + # use helvetica-bold-r-normal, precision 2 (rotatable) + lhcbFont = 62 + # line thickness + lhcbWidth = int(3.00) + + # use plain black on white colors + lhcbstyle.SetFrameBorderMode(0) + lhcbstyle.SetCanvasBorderMode(0) + lhcbstyle.SetPadBorderMode(0) + lhcbstyle.SetPadColor(0) + lhcbstyle.SetCanvasColor(0) + lhcbstyle.SetStatColor(0) + lhcbstyle.SetPalette(1) + + # set the paper & margin sizes + lhcbstyle.SetPaperSize(20, 26) + lhcbstyle.SetPadTopMargin(0.05) + lhcbstyle.SetPadRightMargin(0.05) # increase for colz plots + lhcbstyle.SetPadBottomMargin(0.16) + lhcbstyle.SetPadLeftMargin(0.14) + + # use large fonts + lhcbstyle.SetTextFont(lhcbFont) + lhcbstyle.SetTextSize(0.08) + lhcbstyle.SetLabelFont(lhcbFont, "x") + lhcbstyle.SetLabelFont(lhcbFont, "y") + lhcbstyle.SetLabelFont(lhcbFont, "z") + lhcbstyle.SetLabelSize(0.04, "x") + lhcbstyle.SetLabelSize(0.04, "y") + lhcbstyle.SetLabelSize(0.04, "z") + lhcbstyle.SetTitleFont(lhcbFont) + lhcbstyle.SetTitleSize(0.05, "x") + lhcbstyle.SetTitleSize(0.05, "y") + lhcbstyle.SetTitleSize(0.05, "z") + + # use bold lines and markers + lhcbstyle.SetLineWidth(lhcbWidth) + lhcbstyle.SetFrameLineWidth(lhcbWidth) + lhcbstyle.SetHistLineWidth(lhcbWidth) + lhcbstyle.SetFuncWidth(lhcbWidth) + lhcbstyle.SetGridWidth(lhcbWidth) + lhcbstyle.SetLineStyleString(2, "[12 12]") # postscript dashes + lhcbstyle.SetMarkerStyle(20) + lhcbstyle.SetMarkerSize(1.5) + + # label offsets + lhcbstyle.SetLabelOffset(0.015) + + # by default, do not display histogram decorations: + lhcbstyle.SetOptStat(0) + lhcbstyle.SetOptStat("emr") # show only nent -e , mean - m , rms -r + # full opts at http:#root.cern.ch/root/html/TStyle.html#TStyle:SetOptStat + lhcbstyle.SetStatFormat("6.3g") # specified as c printf options + lhcbstyle.SetOptTitle(0) + lhcbstyle.SetOptFit(0) + # lhcbstyle.SetOptFit(1011) # order is probability, Chi2, errors, parameters + + # look of the statistics box: + lhcbstyle.SetStatBorderSize(0) + lhcbstyle.SetStatFont(lhcbFont) + lhcbstyle.SetStatFontSize(0.05) + lhcbstyle.SetStatX(0.9) + lhcbstyle.SetStatY(0.9) + lhcbstyle.SetStatW(0.25) + lhcbstyle.SetStatH(0.15) + # put tick marks on top and RHS of plots + lhcbstyle.SetPadTickX(1) + lhcbstyle.SetPadTickY(1) + + # histogram divisions: only 5 in x to avoid label overlaps + lhcbstyle.SetNdivisions(505, "x") + lhcbstyle.SetNdivisions(510, "y") + + # define style for text + lhcbLabel = TText() + lhcbLabel.SetTextFont(lhcbFont) + lhcbLabel.SetTextColor(1) + lhcbLabel.SetTextSize(0.04) + lhcbLabel.SetTextAlign(12) + + # define style of latex text + lhcbLatex = TLatex() + lhcbLatex.SetTextFont(lhcbFont) + lhcbLatex.SetTextColor(1) + lhcbLatex.SetTextSize(0.04) + lhcbLatex.SetTextAlign(12) + + # set this style + gROOT.SetStyle("lhcbstyle") + gROOT.ForceStyle() def printLHCb(optLR="L", optPrelim="Final", optText=""): -##################################### -# routine to print 'LHCb', 'LHCb Preliminary' on plots -# options: optLR=L (top left) / R (top right) of plots -# optPrelim= Final (LHCb), Prelim (LHCb Preliminary), Other -# optText= text printed if 'Other' specified -################################## - if optLR=="R" : - lhcbName = TPaveText(0.70 - lhcbstyle.GetPadRightMargin(), - 0.75 - lhcbstyle.SetPadTopMargin(0.05), - 0.95 - lhcbstyle.GetPadRightMargin(), - 0.85 - lhcbstyle.SetPadTopMargin(0.05), - "BRNDC") - elif optLR=="L": - lhcbName = TPaveText(lhcbstyle.GetPadLeftMargin() + 0.05, - 0.87 - lhcbstyle.GetPadTopMargin(), - lhcbstyle.GetPadLeftMargin() + 0.30, - 0.95 - lhcbstyle.GetPadTopMargin(), - "BRNDC") - else : - print("printLHCb: option unknown" , optLR) - if optPrelim=="Final": - lhcbName.AddText("LHCb") - elif optPrelim=="Prelim": - lhcbName.AddText("#splitline{LHCb}{#scale[1.0]{Preliminary}}") - elif optPrelim=="Other": - lhcbName.AddText(optText) - else : - print("printLHCb: option unknown " , optPrelim) - lhcbName.SetFillColor(0) - lhcbName.SetTextAlign(12) - lhcbName.SetBorderSize(0) - lhcbName.Draw() + ##################################### + # routine to print 'LHCb', 'LHCb Preliminary' on plots + # options: optLR=L (top left) / R (top right) of plots + # optPrelim= Final (LHCb), Prelim (LHCb Preliminary), Other + # optText= text printed if 'Other' specified + ################################## + if optLR == "R": + lhcbName = TPaveText( + 0.70 - lhcbstyle.GetPadRightMargin(), + 0.75 - lhcbstyle.SetPadTopMargin(0.05), + 0.95 - lhcbstyle.GetPadRightMargin(), + 0.85 - lhcbstyle.SetPadTopMargin(0.05), + "BRNDC", + ) + elif optLR == "L": + lhcbName = TPaveText( + lhcbstyle.GetPadLeftMargin() + 0.05, + 0.87 - lhcbstyle.GetPadTopMargin(), + lhcbstyle.GetPadLeftMargin() + 0.30, + 0.95 - lhcbstyle.GetPadTopMargin(), + "BRNDC", + ) + else: + print("printLHCb: option unknown", optLR) + if optPrelim == "Final": + lhcbName.AddText("LHCb") + elif optPrelim == "Prelim": + lhcbName.AddText("#splitline{LHCb}{#scale[1.0]{Preliminary}}") + elif optPrelim == "Other": + lhcbName.AddText(optText) + else: + print("printLHCb: option unknown ", optPrelim) + lhcbName.SetFillColor(0) + lhcbName.SetTextAlign(12) + lhcbName.SetBorderSize(0) + lhcbName.Draw() diff --git a/python/TTCluster.py b/python/TTCluster.py index 4d6a3702c3..013e9f6721 100644 --- a/python/TTCluster.py +++ b/python/TTCluster.py @@ -1,13 +1,13 @@ #!/usr/bin/python -import ROOT -import numpy as np import math -from math import exp, sqrt, log, ceil import random -import matplotlib.pyplot as plt +from math import ceil, exp, log, sqrt -from ROOT.TMath import Landau, Gaus, Poisson +import matplotlib.pyplot as plt +import numpy as np +import ROOT +from ROOT.TMath import Gaus, Landau, Poisson from ShipGeoConfig import ConfigRegistry ##################################################### @@ -15,8 +15,8 @@ ##################################################### # Position of SiPMs in the detector (left/right and up/down) -sipm_hor_pos = +1 # at X = +len_vert / 2 -sipm_vert_pos = -1 # at Y = -len_hor / 2 +sipm_hor_pos = +1 # at X = +len_vert / 2 +sipm_vert_pos = -1 # at Y = -len_hor / 2 # If reversed is true the channels counted in reverse way # (0->511 => 511<-0). It connected with how the modules are placed @@ -30,12 +30,12 @@ # ch_max_num - max channel in the SiPM (0-511), # n_solid_sipms - number of "charr" arrays -hw = 13.06 / 2. +hw = 13.06 / 2.0 pitch = 0.025 charr = 1.6 edge = 0.017 gap = 0.025 -array = gap + 2.*charr +array = gap + 2.0 * charr biggap = 0.042 ch_max_num = 511 n_solid_sipms = 8 @@ -43,36 +43,60 @@ # SiPM geometry. If a point is in the solid part then the position will be counted. # Else false value returns. When sipm_map = ( - (-hw, -hw+edge, False), - (-hw+edge, -hw+edge+charr, (-0.5, 63.5)), - (-hw+edge+charr, -hw+edge+charr+gap, False), - (-hw+edge+charr+gap, -hw+edge+array, (63.5, 127.5)), - (-hw+edge+array, -hw+edge+array+biggap, False), - (-hw+edge+array+biggap, -hw+edge+array+biggap+charr, (127.5, 191.5)), - (-hw+edge+array+biggap+charr, -hw+edge+array+biggap+charr+gap, False), - (-hw+edge+array+biggap+charr+gap, -hw+edge+array+biggap+array, (191.5, 255.5)), - (-hw+edge+array+biggap+array, biggap/2., False), - (biggap/2., biggap/2.+charr, (255.5, 319.5)), - (biggap/2.+charr, biggap/2.+charr+gap, False), - (biggap/2.+charr+gap, biggap/2.+array, (319.5, 383.5)), - (biggap/2.+array, biggap/2.+array+biggap, False), - (biggap/2.+array+biggap, biggap/2.+array+biggap+charr, (383.5, 447.5)), - (biggap/2.+array+biggap+charr, biggap/2.+array+biggap+charr+gap, False), - (biggap/2.+array+biggap+charr+gap, biggap/2.+array+biggap+charr+array, (447.5, 511.5)), - (biggap/2.+array+biggap+charr+array, biggap/2.+array+biggap+charr+array+edge, False) + (-hw, -hw + edge, False), + (-hw + edge, -hw + edge + charr, (-0.5, 63.5)), + (-hw + edge + charr, -hw + edge + charr + gap, False), + (-hw + edge + charr + gap, -hw + edge + array, (63.5, 127.5)), + (-hw + edge + array, -hw + edge + array + biggap, False), + (-hw + edge + array + biggap, -hw + edge + array + biggap + charr, (127.5, 191.5)), + ( + -hw + edge + array + biggap + charr, + -hw + edge + array + biggap + charr + gap, + False, + ), + ( + -hw + edge + array + biggap + charr + gap, + -hw + edge + array + biggap + array, + (191.5, 255.5), + ), + (-hw + edge + array + biggap + array, biggap / 2.0, False), + (biggap / 2.0, biggap / 2.0 + charr, (255.5, 319.5)), + (biggap / 2.0 + charr, biggap / 2.0 + charr + gap, False), + (biggap / 2.0 + charr + gap, biggap / 2.0 + array, (319.5, 383.5)), + (biggap / 2.0 + array, biggap / 2.0 + array + biggap, False), + ( + biggap / 2.0 + array + biggap, + biggap / 2.0 + array + biggap + charr, + (383.5, 447.5), + ), + ( + biggap / 2.0 + array + biggap + charr, + biggap / 2.0 + array + biggap + charr + gap, + False, + ), + ( + biggap / 2.0 + array + biggap + charr + gap, + biggap / 2.0 + array + biggap + charr + array, + (447.5, 511.5), + ), + ( + biggap / 2.0 + array + biggap + charr + array, + biggap / 2.0 + array + biggap + charr + array + edge, + False, + ), ) # If a point is in the dead space then the following channel value will be selected gaps_map = { - 0.: -0.5, - 1.: 63.5, - 2.: 127.5, - 3.: 191.5, - 4.: 255.5, - 5.: 319.5, - 6.: 383.5, - 7.: 447.5, - 8.: 511.5 + 0.0: -0.5, + 1.0: 63.5, + 2.0: 127.5, + 3.0: 191.5, + 4.0: 255.5, + 5.0: 319.5, + 6.0: 383.5, + 7.0: 447.5, + 8.0: 511.5, } # Light yield attenuation A*exp(B*x) + C*exp(D*x) @@ -113,7 +137,7 @@ sigma_in_percent = 0.01 # 4 sigma range includes 95% of events. It needs for creating a cluster -sigma_from_width = 1 / 4. +sigma_from_width = 1 / 4.0 # The following parameters will be used in the converting from the energy distibution to # the light yield distibution. @@ -122,662 +146,729 @@ # ly_CDF_params - approximation of CDF of the light yield distribution. # It is doesn't used already. ly_CDF_params = { - (4.5, 13): ( - (-13.2, 1.976), - lambda ly, *p: exp(p[0] + p[1]*sqrt(ly)) - ), - (13, 104): ( - (0.0108183, -0.179752, -19.2, 0.00772965), - lambda ly, *p: p[0]*(1 - exp(p[1]*(ly+p[2]))) / (1 + exp(p[1]*(ly+p[2]))) + p[3] - ) + (4.5, 13): ((-13.2, 1.976), lambda ly, *p: exp(p[0] + p[1] * sqrt(ly))), + (13, 104): ( + (0.0108183, -0.179752, -19.2, 0.00772965), + lambda ly, *p: p[0] + * (1 - exp(p[1] * (ly + p[2]))) + / (1 + exp(p[1] * (ly + p[2]))) + + p[3], + ), } # Get a CDF value from LY (actually from an energy deposit which preliminarily linearly # converted to the range of the light yield (4.5 - 104 ph.e.) ly_CDF_landau_params = { - (4.5, 15): ( - (0.001038, -0.000378, 3.53e-05), - lambda ly, *p: p[0] + p[1]*ly + p[2]*ly**2 - ), - (15, 40): ( - (-0.001986, -0.0003014, 7.031e-05, -2.067e-06, 1.892e-08), - lambda ly, *p: p[0] + p[1]*ly + p[2]*ly**2 + p[3]*ly**3 + p[4]*ly**4 - ), - (40, 104): ( - (-0.007149, 0.001056, -1.779e-05, 1.41e-07, -4.29e-10), - lambda ly, *p: p[0] + p[1]*ly + p[2]*ly**2 + p[3]*ly**3 + p[4]*ly**4 - ) + (4.5, 15): ( + (0.001038, -0.000378, 3.53e-05), + lambda ly, *p: p[0] + p[1] * ly + p[2] * ly**2, + ), + (15, 40): ( + (-0.001986, -0.0003014, 7.031e-05, -2.067e-06, 1.892e-08), + lambda ly, *p: p[0] + p[1] * ly + p[2] * ly**2 + p[3] * ly**3 + p[4] * ly**4, + ), + (40, 104): ( + (-0.007149, 0.001056, -1.779e-05, 1.41e-07, -4.29e-10), + lambda ly, *p: p[0] + p[1] * ly + p[2] * ly**2 + p[3] * ly**3 + p[4] * ly**4, + ), } # Get a light yild value from a CDF values CDF_ly_params = { - (0., 0.0006): ( - (89., 4.152, 0.0001574, -1.326e+04, 4.3), - lambda cdf, *p: p[0] * sqrt(p[1]*(cdf+p[2])) * (1-exp(p[3]*cdf)) + p[4] - ), - (0.0006, 0.012): ( - (158, 1.035, 0.24, 217), - lambda cdf, *p: p[0] * log(sqrt(cdf)+p[1]) + p[2]*exp(p[3]*cdf) - ), - (0.012, 0.018561405): ( - (9.36, 335.984, -18100, -400, 15), - lambda cdf, *p: p[0] * log((p[1]-p[2]*cdf)/(p[1]+p[2]*cdf)) + p[3]*cdf + p[4] - ), - (0.018561405, 0.0185640424): ( - (9.36, 335.984, -18100, -400, 15), - lambda cdf, *p: (p[0] * log((p[1]-p[2]*0.018561405)/(p[1]+p[2]*0.018561405)) - + p[3]*0.018561405 + p[4]) - ) + (0.0, 0.0006): ( + (89.0, 4.152, 0.0001574, -1.326e04, 4.3), + lambda cdf, *p: p[0] * sqrt(p[1] * (cdf + p[2])) * (1 - exp(p[3] * cdf)) + p[4], + ), + (0.0006, 0.012): ( + (158, 1.035, 0.24, 217), + lambda cdf, *p: p[0] * log(sqrt(cdf) + p[1]) + p[2] * exp(p[3] * cdf), + ), + (0.012, 0.018561405): ( + (9.36, 335.984, -18100, -400, 15), + lambda cdf, *p: p[0] * log((p[1] - p[2] * cdf) / (p[1] + p[2] * cdf)) + + p[3] * cdf + + p[4], + ), + (0.018561405, 0.0185640424): ( + (9.36, 335.984, -18100, -400, 15), + lambda cdf, *p: ( + p[0] * log((p[1] - p[2] * 0.018561405) / (p[1] + p[2] * 0.018561405)) + + p[3] * 0.018561405 + + p[4] + ), + ), } ################################################## ##### LOAD THE TARGET TRACKER GEOMETRY ######### ################################################## -design2018 = {'dy': 10.,'dv': 6,'ds': 9,'nud': 3,'caloDesign': 3,'strawDesign': 10} -dy = design2018['dy'] -dv = design2018['dv'] -ds = design2018['ds'] -nud = design2018['nud'] -caloDesign = design2018['caloDesign'] -strawDesign = design2018['strawDesign'] +design2018 = { + "dy": 10.0, + "dv": 6, + "ds": 9, + "nud": 3, + "caloDesign": 3, + "strawDesign": 10, +} +dy = design2018["dy"] +dv = design2018["dv"] +ds = design2018["ds"] +nud = design2018["nud"] +caloDesign = design2018["caloDesign"] +strawDesign = design2018["strawDesign"] geofile = None -ship_geo = ConfigRegistry.loadpy("$FAIRSHIP/geometry/geometry_config.py", Yheight=dy, - tankDesign=dv, muShieldDesign=ds, nuTauTargetDesign=nud, CaloDesign=caloDesign, - strawDesign=strawDesign, muShieldGeo=geofile) +ship_geo = ConfigRegistry.loadpy( + "$FAIRSHIP/geometry/geometry_config.py", + Yheight=dy, + tankDesign=dv, + muShieldDesign=ds, + nuTauTargetDesign=nud, + CaloDesign=caloDesign, + strawDesign=strawDesign, + muShieldGeo=geofile, +) -n_hor_planes = ship_geo.NuTauTT.n_hor_planes # 11 -n_vert_planes = ship_geo.NuTauTT.n_vert_planes # 7 +n_hor_planes = ship_geo.NuTauTT.n_hor_planes # 11 +n_vert_planes = ship_geo.NuTauTT.n_vert_planes # 7 scifimat_hor = ship_geo.NuTauTT.scifimat_hor scifimat_vert = ship_geo.NuTauTT.scifimat_vert -scifimat_width = ship_geo.NuTauTT.scifimat_width # 13.06 cm -scifimat_z = ship_geo.NuTauTT.scifimat_z # 0.145 cm -n_tt_stations = ship_geo.NuTauTT.n # 19 +scifimat_width = ship_geo.NuTauTT.scifimat_width # 13.06 cm +scifimat_z = ship_geo.NuTauTT.scifimat_z # 0.145 cm +n_tt_stations = ship_geo.NuTauTT.n # 19 ######################################################################################### ##### FUNCTIONS FOR TTCLASS ##################################################### ######################################################################################### -def cm_to_channel(locpos, sipm_map=sipm_map, gaps_map=gaps_map, pitch=pitch, charr=charr, - reverse=False, ch_max_num=ch_max_num, n_solid_sipms=n_solid_sipms): - - """ - It converts a particle position (an event) measured in cm to a position measured - in channels. The SiPM map is used. The position is in the scifi modul frame. - """ - - if reverse is True: - for left, right, ch_range in sipm_map: - if left <= locpos <= right: - if not ch_range is False: - ch_start = ch_range[0] - return ch_max_num - ((locpos-left) / pitch + ch_start) - else: - return gaps_map.get((n_solid_sipms - (locpos + hw) // charr), False) - elif reverse is False: - for left, right, ch_range in sipm_map: - if left <= locpos <= right: - if not ch_range is False: - ch_start = ch_range[0] - return (locpos-left) / pitch + ch_start - else: - return gaps_map.get((locpos + hw) // charr, False) + +def cm_to_channel( + locpos, + sipm_map=sipm_map, + gaps_map=gaps_map, + pitch=pitch, + charr=charr, + reverse=False, + ch_max_num=ch_max_num, + n_solid_sipms=n_solid_sipms, +): + """ + It converts a particle position (an event) measured in cm to a position measured + in channels. The SiPM map is used. The position is in the scifi modul frame. + """ + + if reverse is True: + for left, right, ch_range in sipm_map: + if left <= locpos <= right: + if not ch_range is False: + ch_start = ch_range[0] + return ch_max_num - ((locpos - left) / pitch + ch_start) + else: + return gaps_map.get((n_solid_sipms - (locpos + hw) // charr), False) + elif reverse is False: + for left, right, ch_range in sipm_map: + if left <= locpos <= right: + if not ch_range is False: + ch_start = ch_range[0] + return (locpos - left) / pitch + ch_start + else: + return gaps_map.get((locpos + hw) // charr, False) + def channel_to_cm(channelpos, sipm_map=sipm_map, reverse=False, pitch=pitch): + """ + It converts a particle position measured channels to a position measured + in cm. The SiPM map is used. The position is in the scifi modul frame. + """ + + if reverse is True: + for left, _, ch_range in sipm_map: + if not ch_range is False: + ch_start, ch_end = ch_range + if ch_start <= channelpos <= ch_end: + return -(left + (channelpos - ch_start) * pitch) + if reverse is False: + for left, _, ch_range in sipm_map: + if not ch_range is False: + ch_start, ch_end = ch_range + if ch_start <= channelpos <= ch_end: + return left + (channelpos - ch_start) * pitch - """ - It converts a particle position measured channels to a position measured - in cm. The SiPM map is used. The position is in the scifi modul frame. - """ - - if reverse is True: - for left, _, ch_range in sipm_map: - if not ch_range is False: - ch_start, ch_end = ch_range - if ch_start <= channelpos <= ch_end: - return -(left + (channelpos - ch_start) * pitch) - if reverse is False: - for left, _, ch_range in sipm_map: - if not ch_range is False: - ch_start, ch_end = ch_range - if ch_start <= channelpos <= ch_end: - return left + (channelpos - ch_start) * pitch def GetMatType(DetID): + """ + It returns a type of a scifi module. + 1 - vertical scifi assembly + 0 - horizontal scifi assembly + """ - """ - It returns a type of a scifi module. - 1 - vertical scifi assembly - 0 - horizontal scifi assembly - """ - - if DetID < 1000: return False - return (DetID % 1000) // 100. + if DetID < 1000: + return False + return (DetID % 1000) // 100.0 def GetMatNum(DetID): + """ + It returns an id (number) of a scifi module. In current version one plane have 7 vertical + and 11 horisontal scifi assemblies. + """ - """ - It returns an id (number) of a scifi module. In current version one plane have 7 vertical - and 11 horisontal scifi assemblies. - """ + return int(DetID % 1000 % 100) - return int(DetID % 1000 % 100) def GetMatLength(DetID): + """ + It returns a length of a scifi mat. The values 'scifimat_vert', 'scifimat_hor' are set + in the FairShip geometry file. + """ - """ - It returns a length of a scifi mat. The values 'scifimat_vert', 'scifimat_hor' are set - in the FairShip geometry file. - """ + global scifimat_vert, scifimat_hor - global scifimat_vert, scifimat_hor + if GetMatType(DetID) == 1: + return scifimat_vert + elif GetMatType(DetID) == 0: + return scifimat_hor - if GetMatType(DetID) == 1: - return scifimat_vert - elif GetMatType(DetID) == 0: - return scifimat_hor def GetMatQty(DetID): + """ + It returns a number of scifi mats in a plane. In current version it is 7 for vertical + and 11 for horisontal scifi assemblies. + """ - """ - It returns a number of scifi mats in a plane. In current version it is 7 for vertical - and 11 for horisontal scifi assemblies. - """ + global n_vert_planes, n_hor_planes - global n_vert_planes, n_hor_planes + if GetMatType(DetID) == 1: + return n_vert_planes + elif GetMatType(DetID) == 0: + return n_hor_planes - if GetMatType(DetID) == 1: - return n_vert_planes - elif GetMatType(DetID) == 0: - return n_hor_planes def GetStationNum(DetID): + """ + It returns an id of a plane. In current the detector have 19 TT stations and 5 HPT stations. + """ - """ - It returns an id of a plane. In current the detector have 19 TT stations and 5 HPT stations. - """ + return int(hit.GetDetectorID() // 1000.0) - return int(hit.GetDetectorID() // 1000.) def global_to_local(DetID, globalpos): + """ + It returns the local coordinates in one scifi assembly frame from global coordinates. + """ - """ - It returns the local coordinates in one scifi assembly frame from global coordinates. - """ + global scifimat_width - global scifimat_width + matnum = GetMatNum(DetID) + nmats = GetMatQty(DetID) + return globalpos + ((nmats - 1) / 2.0 - matnum + 1) * scifimat_width - matnum = GetMatNum(DetID) - nmats = GetMatQty(DetID) - return globalpos + ((nmats-1)/2. - matnum + 1) * scifimat_width def local_to_global(DetID, localpos): + """ + It returns the global coordinates from the local coordinates in one scifi assembly frame. + """ - """ - It returns the global coordinates from the local coordinates in one scifi assembly frame. - """ + global scifimat_width - global scifimat_width + matnum = GetMatNum(DetID) + nmats = GetMatQty(DetID) + return localpos + (-nmats / 2.0 + matnum - 1 / 2.0) * scifimat_width - matnum = GetMatNum(DetID) - nmats = GetMatQty(DetID) - return localpos + (-nmats/2. + matnum - 1/2.) * scifimat_width def ly_loss_mean(distance, params=ly_loss_params): + """ + It return the light yield depending on the distance to SiPMs + """ - """ - It return the light yield depending on the distance to SiPMs - """ + A1, k1, A2, k2 = params + return A1 * exp(k1 * distance / 100.0) + A2 * exp(k2 * distance / 100.0) - A1, k1, A2, k2 = params - return A1 * exp(k1 * distance / 100.) + A2 * exp(k2 * distance / 100.) def ly_attenuation(distance): + """ + It return the light yield losses in percent depending on the distance to SiPMs + """ - """ - It return the light yield losses in percent depending on the distance to SiPMs - """ + res_ly_loss = ly_loss_mean(distance) / ly_loss_mean(0.0) + return res_ly_loss - res_ly_loss = ly_loss_mean(distance) / ly_loss_mean(0.) - return res_ly_loss def cluster_width_mean(distance, params=cluster_width_mean_params): + """ + It return a mean cluster width depending on the distance to SiPMs + """ - """ - It return a mean cluster width depending on the distance to SiPMs - """ + A, B, C = params + return exp(A + B * distance) + C - A, B, C = params - return exp(A + B*distance) + C def cluster_width_sigma(distance, params=cluster_width_sigma_params): + """ + It return a standard deviation of the mean cluster width depending on the distance to SiPMs + """ - """ - It return a standard deviation of the mean cluster width depending on the distance to SiPMs - """ + A, B = params + return A + B * distance - A, B = params - return A + B*distance -def cluster_width_random(distance, ly, persent=random_width_persent, - cluster_width_min=cluster_width_min, cluster_width_max=cluster_width_max): +def cluster_width_random( + distance, + ly, + persent=random_width_persent, + cluster_width_min=cluster_width_min, + cluster_width_max=cluster_width_max, +): + """ + It generates a cluster. The cluster have 'ly' photoelectrons. + The cluster width depends on the distance to SiPM + """ - """ - It generates a cluster. The cluster have 'ly' photoelectrons. - The cluster width depends on the distance to SiPM - """ + mean = cluster_width_mean(distance) + sigma = cluster_width_sigma(distance) + if random.random() <= persent: + return random.randint(cluster_width_min, cluster_width_max) + random_width = int(round(random.gauss(mean - 1, sigma))) + 1 - mean = cluster_width_mean(distance) - sigma = cluster_width_sigma(distance) - if random.random() <= persent: - return random.randint(cluster_width_min, cluster_width_max) - random_width = int(round(random.gauss(mean - 1, sigma))) + 1 + # Generate again if the width < minimal width and the light yield < the width + while random_width < 1 or ly < random_width: + random_width = int(round(random.gauss(mean - 1, sigma))) + 1 - # Generate again if the width < minimal width and the light yield < the width - while random_width < 1 or ly < random_width: - random_width = int(round(random.gauss(mean - 1, sigma))) + 1 + return random_width - return random_width def approx_function(var, approx_data): + """ + This universal function substitutes the parameters to the function. + The parameters and the function are in the dictionary + """ + + for (left, right), (params, func) in approx_data.items(): + if left <= var <= right: + return func(var, *params) + return False + + +def edep_to_ly( + energy, + CDF_integral=CDF_integral, + energy_range=energy_range, + ly_linear_params=ly_linear_params, + k_cdfs_corr=k_cdfs_corr, + sigma_in_percent=sigma_in_percent, + ly_CDF_params=ly_CDF_params, + CDF_ly_params=CDF_ly_params, + ly_CDF_landau_params=ly_CDF_landau_params, +): + """ + It returns the light yield calculated from the energy deposit. The calculations are based + on the equality of the cumulative distribution functions (CDF) : + energy => CDF(energy) => CDF(light yield) => ly + + The linear converting range 0.18 MeV < dE < 0.477 MeV corresponds 4.5 < LY < 104 ph.e. + + If energy more then 0.477 MeV the light yield calculated randomly (uniformly in the range) + according to the distribution + + Also a little randomness is added to the CDF value with a normal distribution and + standard deviation with 'sigma_in_percent' (in percent of the whole range 0 - max CDF) + """ + + e_min, e_max = energy_range + A, C = ly_linear_params + if e_min < energy < e_max: + ly_lin = A * energy + C + cdf_raw = approx_function(ly_lin, ly_CDF_landau_params) * k_cdfs_corr + elif e_max <= energy: + cdf_raw = CDF_integral * np.random.uniform(0.0, 1.0) + else: + return 0.0 + cdf_random = random.gauss(cdf_raw, sigma_in_percent * CDF_integral) + + # Generate again while the CDF value is not in the range + while cdf_random < 0 or cdf_random > CDF_integral: + cdf_random = random.gauss(cdf_raw, sigma_in_percent * CDF_integral) + + return approx_function(cdf_random, CDF_ly_params) + + +def cluster_generator( + amplitude, + width, + wmp, + cluster_width_max=cluster_width_max, + chpos_min=chpos_min, + chpos_max=chpos_max, +): + """ + It generates an event cluster with given weighted mean position in channels, width and + amplitude. + + If right side of the cluster can be out of range, the maximum of the right side will be + right channel. + + At first an array [0, 0, 0, ... ] is generated which corresponds to the channels. + Next the cluster generated in the array. + Final array will be like [0, 0, ..., 1, 2, 5, 1, 0, ...], + [0, 17, 0, ...] or etc. + """ + + if int(ceil(wmp + 0.5 + cluster_width_max)) < chpos_max: + max_fired_ch = int(ceil(wmp + 0.5 + cluster_width_max)) + else: + max_fired_ch = int(ceil(chpos_max)) + cluster = [0 for _ in range(max_fired_ch)] + mean = wmp + if width == 1: + if wmp == chpos_min: + fired_channel = 0 + elif wmp == chpos_max: + fired_channel = int(chpos_max) + else: + fired_channel = int(wmp + 0.5) + cluster[fired_channel] += amplitude + else: + sigma = width * sigma_from_width + for _ in range(amplitude): + fired_channel = int(round(random.gauss(mean, sigma))) + while not 0 <= fired_channel < len(cluster): + fired_channel = int(round(random.gauss(mean, sigma))) + cluster[fired_channel] += 1 + return cluster - """ - This universal function substitutes the parameters to the function. - The parameters and the function are in the dictionary - """ - - for (left, right), (params, func) in approx_data.items(): - if left <= var <= right: - return func(var, *params) - return False - -def edep_to_ly(energy, CDF_integral=CDF_integral, energy_range=energy_range, - ly_linear_params=ly_linear_params, k_cdfs_corr=k_cdfs_corr, sigma_in_percent=sigma_in_percent, - ly_CDF_params=ly_CDF_params, CDF_ly_params=CDF_ly_params, ly_CDF_landau_params=ly_CDF_landau_params): - - """ - It returns the light yield calculated from the energy deposit. The calculations are based - on the equality of the cumulative distribution functions (CDF) : - energy => CDF(energy) => CDF(light yield) => ly - - The linear converting range 0.18 MeV < dE < 0.477 MeV corresponds 4.5 < LY < 104 ph.e. - - If energy more then 0.477 MeV the light yield calculated randomly (uniformly in the range) - according to the distribution - - Also a little randomness is added to the CDF value with a normal distribution and - standard deviation with 'sigma_in_percent' (in percent of the whole range 0 - max CDF) - """ - - e_min, e_max = energy_range - A, C = ly_linear_params - if e_min < energy < e_max: - ly_lin = A * energy + C - cdf_raw = approx_function(ly_lin, ly_CDF_landau_params) * k_cdfs_corr - elif e_max <= energy: - cdf_raw = CDF_integral * np.random.uniform(0., 1.0) - else: - return 0. - cdf_random = random.gauss(cdf_raw, sigma_in_percent * CDF_integral) - - # Generate again while the CDF value is not in the range - while cdf_random < 0 or cdf_random > CDF_integral: - cdf_random = random.gauss(cdf_raw, sigma_in_percent * CDF_integral) - - return approx_function(cdf_random, CDF_ly_params) - -def cluster_generator(amplitude, width, wmp, cluster_width_max=cluster_width_max, - chpos_min=chpos_min, chpos_max=chpos_max): - - """ - It generates an event cluster with given weighted mean position in channels, width and - amplitude. - - If right side of the cluster can be out of range, the maximum of the right side will be - right channel. - - At first an array [0, 0, 0, ... ] is generated which corresponds to the channels. - Next the cluster generated in the array. - Final array will be like [0, 0, ..., 1, 2, 5, 1, 0, ...], - [0, 17, 0, ...] or etc. - """ - - if int(ceil(wmp + 0.5 + cluster_width_max)) < chpos_max: - max_fired_ch = int(ceil(wmp + 0.5 + cluster_width_max)) - else: - max_fired_ch = int(ceil(chpos_max)) - cluster = [0 for _ in range(max_fired_ch)] - mean = wmp - if width == 1: - if wmp == chpos_min: - fired_channel = 0 - elif wmp == chpos_max: - fired_channel = int(chpos_max) - else: - fired_channel = int(wmp + 0.5) - cluster[fired_channel] += amplitude - else: - sigma = width * sigma_from_width - for _ in range(amplitude): - fired_channel = int(round(random.gauss(mean, sigma))) - while not 0 <= fired_channel < len(cluster): - fired_channel = int(round(random.gauss(mean, sigma))) - cluster[fired_channel] += 1 - return cluster def is_realistic(cluster, width): + """ + It returns TRUE if cluster is realistic: it doesn't have a gap between numders, like + [..., 0, 1, 2, 0, 0, 5, 6, ...], and it doens't have the light yield less then width. + """ + + cluster_only_values = [ + (channel, value) for channel, value in enumerate(cluster) if value > 0 + ] + first_channel, _ = cluster_only_values[0] + last_channel, _ = cluster_only_values[-1] + if len(cluster_only_values) != width or (last_channel - first_channel + 1) != width: + return False + else: + return True - """ - It returns TRUE if cluster is realistic: it doesn't have a gap between numders, like - [..., 0, 1, 2, 0, 0, 5, 6, ...], and it doens't have the light yield less then width. - """ - - cluster_only_values = [(channel, value) for channel, value in enumerate(cluster) if value > 0] - first_channel, _ = cluster_only_values[0] - last_channel, _ = cluster_only_values[-1] - if len(cluster_only_values) != width or (last_channel - first_channel + 1) != width: - return False - else: - return True def create_cluster(amplitude, width, wmp): + """ + The final function for creating a signal cluster - """ - The final function for creating a signal cluster + """ + if not chpos_min < wmp < chpos_max: + return False + if wmp is False: + return False + if not ly_min <= amplitude >= width: + return False + shifted_wmp = wmp + 0.5 # For right counting + cluster = cluster_generator(amplitude, width, shifted_wmp) - """ - if not chpos_min < wmp < chpos_max: return False - if wmp is False: return False - if not ly_min <= amplitude >= width: return False - shifted_wmp = wmp + 0.5 # For right counting - cluster = cluster_generator(amplitude, width, shifted_wmp) + # Generate again if it doesn't look like real cluster + while is_realistic(cluster, width) is False: + cluster = cluster_generator(amplitude, width, shifted_wmp) - # Generate again if it doesn't look like real cluster - while is_realistic(cluster, width) is False: - cluster = cluster_generator(amplitude, width, shifted_wmp) + return cluster - return cluster def weigthed_mean_pos(cluster): + """ + Calculate the weighted mean position of the cluster + """ + + if cluster is False: + return False + sumup = 0.0 + sumdown = 0.0 + wmp = 0.0 + for channel, value in enumerate(cluster): + if value > 0: + sumup += value * channel + sumdown += value + if sumdown != 0: + wmp = sumup / sumdown - 0.5 + return wmp - """ - Calculate the weighted mean position of the cluster - """ - - if cluster is False: - return False - sumup = 0. - sumdown = 0. - wmp = 0. - for channel, value in enumerate(cluster): - if value > 0: - sumup += value * channel - sumdown += value - if sumdown != 0: - wmp = sumup / sumdown - 0.5 - return wmp ######################################################################################### ##### CLASS OF TT AND HPT EVENTS ###################################################### ######################################################################################### + class TTCluster: - # Constructor - def __init__(self, DetID, Xraw, Yraw, Edep): - self.DetID = DetID - self.Xraw = Xraw - self.Yraw = Yraw - self.Edep = Edep * 1000 # to MeV - self.ly = 0. - self.cluster = [] - self.station = 0 - self.matnum = 0 - self.Xrec = 0. - self.Yrec = 0. - self.is_created = False - # Only to check the edge events - self.recovery_globalpos = 0 - self.delta = -13 - # The default values should be set - self.sipm_hor_pos = +1 # +1 at X = +len_vert / 2 - self.sipm_vert_pos = +1 #-1 at Y = -len_hor / 2 - self.is_sipm_hor_reversed = False # Channels and axis are co-directional or not - self.is_sipm_vert_reversed = False - self.ly_min = 4.5 - self.ly_max = 104 - - def SetLYRange(self, ly_min, ly_max): - self.ly_min = ly_min - self.ly_max = ly_max - - def SetSipmPosition(self, sipm_hor_pos, sipm_vert_pos): - self.sipm_hor_pos = sipm_hor_pos - self.sipm_vert_pos = sipm_vert_pos - - def SetSipmIsReversed(self, is_sipm_hor_reversed, is_sipm_vert_reversed): - self.is_sipm_hor_reversed = is_sipm_hor_reversed - self.is_sipm_vert_reversed = is_sipm_vert_reversed - - # Cluster generator from the raw data. It returns False if it fails. - def ClusterGen(self): - if GetMatType(self.DetID) is False: - return False - elif GetMatType(self.DetID) == 1: # vert - first_coord = self.Xraw - second_coord = self.Yraw - sipm_pos = self.sipm_vert_pos - is_sipm_reversed = self.is_sipm_hor_reversed - elif GetMatType(self.DetID) == 0: # hor - first_coord = self.Yraw - second_coord = self.Xraw - sipm_pos = self.sipm_hor_pos - is_sipm_reversed = self.is_sipm_vert_reversed - self.matnum = GetMatNum(self.DetID) - nmats = GetMatQty(self.DetID) - matlen = GetMatLength(self.DetID) - self.station = GetStationNum(self.DetID) - localpos = global_to_local(self.DetID, first_coord) - - if sipm_pos == +1: - distance = GetMatLength(self.DetID)/2. - second_coord - elif sipm_pos == -1: - distance = GetMatLength(self.DetID)/2. + second_coord - - channelpos = cm_to_channel(localpos, reverse=is_sipm_reversed) - self.ly = int(round( - edep_to_ly(self.Edep) * ly_attenuation(distance) - )) - - if not self.ly_min < self.ly < self.ly_max: - return False - - cluster_width = int(round(cluster_width_random(distance, ly=self.ly))) - cluster = create_cluster(self.ly, cluster_width, channelpos) - wmp_of_cluster = weigthed_mean_pos(cluster) - recovery_localpos = channel_to_cm(wmp_of_cluster, reverse=is_sipm_reversed) - - self.recovery_globalpos = local_to_global(self.DetID, recovery_localpos) - self.delta = first_coord - self.recovery_globalpos - - # Some edge events may be reconstructed incorrectly - if abs(self.delta) > 1: - return False - - if GetMatType(self.DetID) == 1: # vert - self.Xrec = self.recovery_globalpos - elif GetMatType(self.DetID) == 0: # hor - self.Yrec = self.recovery_globalpos - self.is_created = True - return cluster - - def GetXYZ(self): - if self.is_created: - return self.Xrec, self.Yrec, self.station - else: - return 0, 0, 0 -###################################################################################### + # Constructor + def __init__(self, DetID, Xraw, Yraw, Edep): + self.DetID = DetID + self.Xraw = Xraw + self.Yraw = Yraw + self.Edep = Edep * 1000 # to MeV + self.ly = 0.0 + self.cluster = [] + self.station = 0 + self.matnum = 0 + self.Xrec = 0.0 + self.Yrec = 0.0 + self.is_created = False + # Only to check the edge events + self.recovery_globalpos = 0 + self.delta = -13 + # The default values should be set + self.sipm_hor_pos = +1 # +1 at X = +len_vert / 2 + self.sipm_vert_pos = +1 # -1 at Y = -len_hor / 2 + self.is_sipm_hor_reversed = False # Channels and axis are co-directional or not + self.is_sipm_vert_reversed = False + self.ly_min = 4.5 + self.ly_max = 104 + + def SetLYRange(self, ly_min, ly_max): + self.ly_min = ly_min + self.ly_max = ly_max + + def SetSipmPosition(self, sipm_hor_pos, sipm_vert_pos): + self.sipm_hor_pos = sipm_hor_pos + self.sipm_vert_pos = sipm_vert_pos + + def SetSipmIsReversed(self, is_sipm_hor_reversed, is_sipm_vert_reversed): + self.is_sipm_hor_reversed = is_sipm_hor_reversed + self.is_sipm_vert_reversed = is_sipm_vert_reversed + + # Cluster generator from the raw data. It returns False if it fails. + def ClusterGen(self): + if GetMatType(self.DetID) is False: + return False + elif GetMatType(self.DetID) == 1: # vert + first_coord = self.Xraw + second_coord = self.Yraw + sipm_pos = self.sipm_vert_pos + is_sipm_reversed = self.is_sipm_hor_reversed + elif GetMatType(self.DetID) == 0: # hor + first_coord = self.Yraw + second_coord = self.Xraw + sipm_pos = self.sipm_hor_pos + is_sipm_reversed = self.is_sipm_vert_reversed + self.matnum = GetMatNum(self.DetID) + nmats = GetMatQty(self.DetID) + matlen = GetMatLength(self.DetID) + self.station = GetStationNum(self.DetID) + localpos = global_to_local(self.DetID, first_coord) + + if sipm_pos == +1: + distance = GetMatLength(self.DetID) / 2.0 - second_coord + elif sipm_pos == -1: + distance = GetMatLength(self.DetID) / 2.0 + second_coord + + channelpos = cm_to_channel(localpos, reverse=is_sipm_reversed) + self.ly = int(round(edep_to_ly(self.Edep) * ly_attenuation(distance))) + + if not self.ly_min < self.ly < self.ly_max: + return False + + cluster_width = int(round(cluster_width_random(distance, ly=self.ly))) + cluster = create_cluster(self.ly, cluster_width, channelpos) + wmp_of_cluster = weigthed_mean_pos(cluster) + recovery_localpos = channel_to_cm(wmp_of_cluster, reverse=is_sipm_reversed) + + self.recovery_globalpos = local_to_global(self.DetID, recovery_localpos) + self.delta = first_coord - self.recovery_globalpos + + # Some edge events may be reconstructed incorrectly + if abs(self.delta) > 1: + return False + + if GetMatType(self.DetID) == 1: # vert + self.Xrec = self.recovery_globalpos + elif GetMatType(self.DetID) == 0: # hor + self.Yrec = self.recovery_globalpos + self.is_created = True + return cluster + + def GetXYZ(self): + if self.is_created: + return self.Xrec, self.Yrec, self.station + else: + return 0, 0, 0 +###################################################################################### + -if __name__ == '__main__': - - ############################################### - ########## EXAMPLE OF USING THE CLASS ####### - ############################################### - - tt_points = [] - hpt_points = [] - tt_raw = [] - hpt_raw = [] - - # Set the path to the file - muonfile = ROOT.TFile("$PWD/ship.conical.PG_13-TGeant4.root") - tree = muonfile.Get("cbmsim") - - for index, event in enumerate(tree): - for hit in event.TTPoint: - - pnt = TTCluster(hit.GetDetectorID(), hit.GetX(), hit.GetY(), hit.GetEnergyLoss()) - pnt.SetLYRange(ly_min, ly_max) - pnt.SetSipmPosition(sipm_hor_pos, sipm_vert_pos) - pnt.SetSipmIsReversed(is_sipm_hor_reversed, is_sipm_vert_reversed) - pnt.ClusterGen() - if pnt.is_created is False: continue - - tt_points.append([ - hit.GetTime(), # 0; ns - pnt.station, # 1 - pnt.matnum, # 2 ;~100-vert, ~0-hor - False, # 3 ; in one mat - pnt.ly, #ly signal, # 4 - False, # 5 - pnt.recovery_globalpos, # 6 - GetMatType(pnt.DetID), # 7 # 0-vert (X), 1-hor (Y) - pnt.delta, # 8 - ]) - - tt_raw.append([ - hit.GetTrackID(), # 0 - hit.GetTime(), # 1 ; ns - hit.PdgCode(), # 2 - hit.GetEventID(), # 3 - hit.GetDetectorID(), # 4 - hit.GetX(), # 5 ; cm - hit.GetY(), # 6 ; cm - hit.GetZ(), # 7 ; cm - hit.GetEnergyLoss() * 1.0e03, # 8 ; MeV - hit.GetPx(), # 9 - hit.GetPy(), # 10 - hit.GetPz(), # 11 - hit.GetLength() # 12 - ]) - # Convert to numpy array - tt_raw = np.array(tt_raw) - tt_points = np.array(tt_points) - - # HPT - for index, event in enumerate(tree): - for hit in event.HptPoint: - pnt = TTCluster(hit.GetDetectorID(), hit.GetX(), hit.GetY(), hit.GetEnergyLoss()) - pnt.ClusterGen() - if pnt.is_created is False: continue - - hpt_points.append([ - hit.GetTime(), # 0; ns - pnt.station + n_tt_stations, # 1 - pnt.matnum, # 2 ;~100-vert, ~0-hor - False, # 3 ; in one mat - pnt.ly, #ly signal, # 4 - False, # 5 - pnt.recovery_globalpos, # 6 - GetMatType(pnt.DetID), # 7 # 1-vert (X), 0-hor (Y) - pnt.delta, # 8 - ]) - - hpt_raw.append([ - hit.GetTrackID(), # 0 - hit.GetTime(), # 1 ; ns - hit.PdgCode(), # 2 - hit.GetEventID(), # 3 - hit.GetDetectorID(), # 4 - hit.GetX(), # 5 ; cm - hit.GetY(), # 6 ; cm - hit.GetZ(), # 7 ; cm - hit.GetEnergyLoss() * 1.0e03, # 8 ; MeV - hit.GetPx(), # 9 - hit.GetPy(), # 10 - hit.GetPz(), # 11 - hit.GetLength() # 12 - ]) - - # Convert to numpy array - hpt_raw = np.array(hpt_raw) - hpt_points = np.array(hpt_points) - - # Merge the arrays - tt_raw = np.vstack((tt_raw, hpt_raw)) - tt_points = np.vstack((tt_points, hpt_points)) - # ---------------------------------------------- - - - # ---- 3. SHOW THE DATA -------------------------- - fig, axs = plt.subplots(2,2) - plt.subplot(2, 2, 1) - axs = plt.gca() - ly_bins = np.linspace(4,104,100) - plt.hist(tt_points[:,4], bins=ly_bins, label="Light yield") - axs.set_xlabel("LY, [ph.e.]") - axs.set_ylabel("Events") - plt.legend(loc="upper right") - - plt.subplot(2, 2, 2) - axs = plt.gca() - nbins = 24 - plt.hist(tt_points[:,1], bins=nbins, label="TT station") - axs.set_xlabel("Station number") - axs.set_ylabel("Events") - plt.legend(loc="upper right") - - # Print 'X-Z' and 'Y-Z' as output data. - # 'X-Y-Z' graphics need additional analysis (linking by time). - xz_points = [] - yz_points = [] - for index, event in enumerate(tt_points): - if tt_points[index, 7] == 1: # vertical - xz_points.append([ - tt_raw[index, 7], # Z - tt_points[index, 6] - ]) - elif tt_points[index, 7] == 0: # horizontal - yz_points.append([ - tt_raw[index, 7], # Z - tt_points[index, 6] - ]) - xz_points = np.array(xz_points) - yz_points = np.array(yz_points) - - plt.subplot(2, 2, 3) - axs = plt.gca() - axs.scatter(xz_points[:,0], xz_points[:, 1]) - axs.set_xlabel("Z, [cm]") - axs.set_ylabel("X, [cm]") - axs.set_ylim(-50, +50) # +-73.2475 - - plt.subplot(2, 2, 4) - axs = plt.gca() - axs.scatter(yz_points[:,0], yz_points[:, 1]) - axs.set_xlabel("Z, [cm]") - axs.set_ylabel("Y, [cm]") - axs.set_ylim(-80, +80) # +-47.1575 - - plt.show() - # ---------------------------------------------- - - fig, axs = plt.subplots(1,1) - plt.subplot(1, 1, 1) - axs = plt.gca() - plt.hist(tt_points[:,8], bins=100, label="delta") - plt.show() +if __name__ == "__main__": + ############################################### + ########## EXAMPLE OF USING THE CLASS ####### + ############################################### + + tt_points = [] + hpt_points = [] + tt_raw = [] + hpt_raw = [] + + # Set the path to the file + muonfile = ROOT.TFile("$PWD/ship.conical.PG_13-TGeant4.root") + tree = muonfile.Get("cbmsim") + + for index, event in enumerate(tree): + for hit in event.TTPoint: + pnt = TTCluster( + hit.GetDetectorID(), hit.GetX(), hit.GetY(), hit.GetEnergyLoss() + ) + pnt.SetLYRange(ly_min, ly_max) + pnt.SetSipmPosition(sipm_hor_pos, sipm_vert_pos) + pnt.SetSipmIsReversed(is_sipm_hor_reversed, is_sipm_vert_reversed) + pnt.ClusterGen() + if pnt.is_created is False: + continue + + tt_points.append( + [ + hit.GetTime(), # 0; ns + pnt.station, # 1 + pnt.matnum, # 2 ;~100-vert, ~0-hor + False, # 3 ; in one mat + pnt.ly, # ly signal, # 4 + False, # 5 + pnt.recovery_globalpos, # 6 + GetMatType(pnt.DetID), # 7 # 0-vert (X), 1-hor (Y) + pnt.delta, # 8 + ] + ) + + tt_raw.append( + [ + hit.GetTrackID(), # 0 + hit.GetTime(), # 1 ; ns + hit.PdgCode(), # 2 + hit.GetEventID(), # 3 + hit.GetDetectorID(), # 4 + hit.GetX(), # 5 ; cm + hit.GetY(), # 6 ; cm + hit.GetZ(), # 7 ; cm + hit.GetEnergyLoss() * 1.0e03, # 8 ; MeV + hit.GetPx(), # 9 + hit.GetPy(), # 10 + hit.GetPz(), # 11 + hit.GetLength(), # 12 + ] + ) + # Convert to numpy array + tt_raw = np.array(tt_raw) + tt_points = np.array(tt_points) + + # HPT + for index, event in enumerate(tree): + for hit in event.HptPoint: + pnt = TTCluster( + hit.GetDetectorID(), hit.GetX(), hit.GetY(), hit.GetEnergyLoss() + ) + pnt.ClusterGen() + if pnt.is_created is False: + continue + + hpt_points.append( + [ + hit.GetTime(), # 0; ns + pnt.station + n_tt_stations, # 1 + pnt.matnum, # 2 ;~100-vert, ~0-hor + False, # 3 ; in one mat + pnt.ly, # ly signal, # 4 + False, # 5 + pnt.recovery_globalpos, # 6 + GetMatType(pnt.DetID), # 7 # 1-vert (X), 0-hor (Y) + pnt.delta, # 8 + ] + ) + + hpt_raw.append( + [ + hit.GetTrackID(), # 0 + hit.GetTime(), # 1 ; ns + hit.PdgCode(), # 2 + hit.GetEventID(), # 3 + hit.GetDetectorID(), # 4 + hit.GetX(), # 5 ; cm + hit.GetY(), # 6 ; cm + hit.GetZ(), # 7 ; cm + hit.GetEnergyLoss() * 1.0e03, # 8 ; MeV + hit.GetPx(), # 9 + hit.GetPy(), # 10 + hit.GetPz(), # 11 + hit.GetLength(), # 12 + ] + ) + + # Convert to numpy array + hpt_raw = np.array(hpt_raw) + hpt_points = np.array(hpt_points) + + # Merge the arrays + tt_raw = np.vstack((tt_raw, hpt_raw)) + tt_points = np.vstack((tt_points, hpt_points)) + # ---------------------------------------------- + + # ---- 3. SHOW THE DATA -------------------------- + fig, axs = plt.subplots(2, 2) + plt.subplot(2, 2, 1) + axs = plt.gca() + ly_bins = np.linspace(4, 104, 100) + plt.hist(tt_points[:, 4], bins=ly_bins, label="Light yield") + axs.set_xlabel("LY, [ph.e.]") + axs.set_ylabel("Events") + plt.legend(loc="upper right") + + plt.subplot(2, 2, 2) + axs = plt.gca() + nbins = 24 + plt.hist(tt_points[:, 1], bins=nbins, label="TT station") + axs.set_xlabel("Station number") + axs.set_ylabel("Events") + plt.legend(loc="upper right") + + # Print 'X-Z' and 'Y-Z' as output data. + # 'X-Y-Z' graphics need additional analysis (linking by time). + xz_points = [] + yz_points = [] + for index, event in enumerate(tt_points): + if tt_points[index, 7] == 1: # vertical + xz_points.append( + [ + tt_raw[index, 7], # Z + tt_points[index, 6], + ] + ) + elif tt_points[index, 7] == 0: # horizontal + yz_points.append( + [ + tt_raw[index, 7], # Z + tt_points[index, 6], + ] + ) + xz_points = np.array(xz_points) + yz_points = np.array(yz_points) + + plt.subplot(2, 2, 3) + axs = plt.gca() + axs.scatter(xz_points[:, 0], xz_points[:, 1]) + axs.set_xlabel("Z, [cm]") + axs.set_ylabel("X, [cm]") + axs.set_ylim(-50, +50) # +-73.2475 + + plt.subplot(2, 2, 4) + axs = plt.gca() + axs.scatter(yz_points[:, 0], yz_points[:, 1]) + axs.set_xlabel("Z, [cm]") + axs.set_ylabel("Y, [cm]") + axs.set_ylim(-80, +80) # +-47.1575 + + plt.show() + # ---------------------------------------------- + + fig, axs = plt.subplots(1, 1) + plt.subplot(1, 1, 1) + axs = plt.gca() + plt.hist(tt_points[:, 8], bins=100, label="delta") + plt.show() diff --git a/python/TrackExtrapolateTool.py b/python/TrackExtrapolateTool.py index b1f0b705b4..189553046a 100644 --- a/python/TrackExtrapolateTool.py +++ b/python/TrackExtrapolateTool.py @@ -1,44 +1,52 @@ import ROOT import shipunit as u + def cmp(a, b): return (a > b) - (a < b) + minNdf = 20 -parallelToZ = ROOT.TVector3(0., 0., 1.) +parallelToZ = ROOT.TVector3(0.0, 0.0, 1.0) top = ROOT.gGeoManager.GetTopVolume() -if top.GetNode('Ecal_1'): z_ecal = top.GetNode('Ecal_1').GetMatrix().GetTranslation()[2] -elif top.GetNode('SplitCalDetector_1'): z_ecal = top.GetNode('SplitCalDetector_1').GetMatrix().GetTranslation()[2] +if top.GetNode("Ecal_1"): + z_ecal = top.GetNode("Ecal_1").GetMatrix().GetTranslation()[2] +elif top.GetNode("SplitCalDetector_1"): + z_ecal = top.GetNode("SplitCalDetector_1").GetMatrix().GetTranslation()[2] else: - print("TrackExtraploate tool: Error, no calo present") - z_ecal = 100*u.m -def extrapolateToPlane(fT,z): -# etrapolate to a plane perpendicular to beam direction (z) - rc,pos,mom = False,None,None - fst = fT.getFitStatus() - if fst.isFitConverged() and fst.getNdf() > minNdf: -# test for fit status for each point - if fT.getPoint(0).getFitterInfo() and fT.getPoint(1).getFitterInfo(): - fstate0,fstate1 = fT.getFittedState(0),fT.getFittedState(1) - fPos0,fPos1 = fstate0.getPos(),fstate1.getPos() - if abs(z-fPos0.z()) < abs(z-fPos1.z()): fstate = fstate0 - else: fstate = fstate1 - zs = min(z,z_ecal) - NewPosition = ROOT.TVector3(0., 0., zs) - rep = ROOT.genfit.RKTrackRep(13*cmp(fstate.getPDG(),0) ) - state = ROOT.genfit.StateOnPlane(rep) - pos,mom = fstate.getPos(),fstate.getMom() - rep.setPosMom(state,pos,mom) - try: - rep.extrapolateToPlane(state, NewPosition, parallelToZ ) - pos,mom = state.getPos(),state.getMom() - rc = True - except: - # print 'error with extrapolation: z=',z/u.m,'m',pos.X(),pos.Y(),pos.Z(),mom.X(),mom.Y(),mom.Z() - pass - if not rc or z>z_ecal: - # use linear extrapolation - px,py,pz = mom.X(),mom.Y(),mom.Z() - lam = (z-pos.Z())/pz - pos = ROOT.TVector3( pos.X()+lam*px, pos.Y()+lam*py, z ) - return rc,pos,mom + print("TrackExtraploate tool: Error, no calo present") + z_ecal = 100 * u.m + + +def extrapolateToPlane(fT, z): + # etrapolate to a plane perpendicular to beam direction (z) + rc, pos, mom = False, None, None + fst = fT.getFitStatus() + if fst.isFitConverged() and fst.getNdf() > minNdf: + # test for fit status for each point + if fT.getPoint(0).getFitterInfo() and fT.getPoint(1).getFitterInfo(): + fstate0, fstate1 = fT.getFittedState(0), fT.getFittedState(1) + fPos0, fPos1 = fstate0.getPos(), fstate1.getPos() + if abs(z - fPos0.z()) < abs(z - fPos1.z()): + fstate = fstate0 + else: + fstate = fstate1 + zs = min(z, z_ecal) + NewPosition = ROOT.TVector3(0.0, 0.0, zs) + rep = ROOT.genfit.RKTrackRep(13 * cmp(fstate.getPDG(), 0)) + state = ROOT.genfit.StateOnPlane(rep) + pos, mom = fstate.getPos(), fstate.getMom() + rep.setPosMom(state, pos, mom) + try: + rep.extrapolateToPlane(state, NewPosition, parallelToZ) + pos, mom = state.getPos(), state.getMom() + rc = True + except: + # print 'error with extrapolation: z=',z/u.m,'m',pos.X(),pos.Y(),pos.Z(),mom.X(),mom.Y(),mom.Z() + pass + if not rc or z > z_ecal: + # use linear extrapolation + px, py, pz = mom.X(), mom.Y(), mom.Z() + lam = (z - pos.Z()) / pz + pos = ROOT.TVector3(pos.X() + lam * px, pos.Y() + lam * py, z) + return rc, pos, mom diff --git a/python/basiclibs.py b/python/basiclibs.py index 8500e33c4a..c9285a2599 100644 --- a/python/basiclibs.py +++ b/python/basiclibs.py @@ -1,16 +1,17 @@ # Macro for loading basic libraries used with both Geant3 and Geant4 from ROOT import gSystem -#gSystem.Load("libEventDisplay.so") -#gSystem.Load("libRIO.so") -#gSystem.Load("libGeom.so") -#gSystem.Load("libGeomPainter.so") -#gSystem.Load("libVMC.so") -#gSystem.Load("libEG.so") + +# gSystem.Load("libEventDisplay.so") +# gSystem.Load("libRIO.so") +# gSystem.Load("libGeom.so") +# gSystem.Load("libGeomPainter.so") +# gSystem.Load("libVMC.so") +# gSystem.Load("libEG.so") gSystem.Load("libEGPythia6.so") gSystem.Load("libPythia6.so") -#gSystem.Load("libPhysics.so") -#gSystem.Load("libNet.so") -#gSystem.Load("libTree.so") -#gSystem.Load("libMinuit.so") -#gSystem.Load("libMathMore.so") +# gSystem.Load("libPhysics.so") +# gSystem.Load("libNet.so") +# gSystem.Load("libTree.so") +# gSystem.Load("libMinuit.so") +# gSystem.Load("libMathMore.so") gSystem.Load("libpythia8.so") diff --git a/python/checkMagFields.py b/python/checkMagFields.py index b29879770e..cdbed2301d 100644 --- a/python/checkMagFields.py +++ b/python/checkMagFields.py @@ -1,67 +1,168 @@ -import ROOT,sys +import sys + +import ROOT import rootUtils as ut import shipunit as u + def run(): - fGeo = ROOT.gGeoManager - run = sys.modules['__main__'].run - if hasattr(sys.modules['__main__'],'h'): h = sys.modules['__main__'].h - else: h={} - grid = 120,100,1500 - xmin,ymin,zmin = -4*u.m,-5*u.m,-100*u.m - xmax,ymax,zmax = 4*u.m,5*u.m,50*u.m - dx,dy,dz = (xmax-xmin)/grid[0],(ymax-ymin)/grid[1],(zmax-zmin)/grid[2] - ut.bookHist(h,'Bx-','Bx- component ;z [cm];x [cm];y [cm]',grid[2],zmin,zmax,grid[0],xmin,xmax,grid[1],ymin,ymax) - ut.bookHist(h,'By-','By- component ;z [cm];x [cm];y [cm]',grid[2],zmin,zmax,grid[0],xmin,xmax,grid[1],ymin,ymax) - ut.bookHist(h,'Bz-','Bz- component ;z [cm];x [cm];y [cm]',grid[2],zmin,zmax,grid[0],xmin,xmax,grid[1],ymin,ymax) - ut.bookHist(h,'Bx+','Bx+ component ;z [cm];x [cm];y [cm]',grid[2],zmin,zmax,grid[0],xmin,xmax,grid[1],ymin,ymax) - ut.bookHist(h,'By+','By+ component ;z [cm];x [cm];y [cm]',grid[2],zmin,zmax,grid[0],xmin,xmax,grid[1],ymin,ymax) - ut.bookHist(h,'Bz+','Bz+ component ;z [cm];x [cm];y [cm]',grid[2],zmin,zmax,grid[0],xmin,xmax,grid[1],ymin,ymax) - h['Bx-'].SetMarkerColor(ROOT.kGreen-3) - h['Bx+'].SetMarkerColor(ROOT.kGreen+3) - h['By-'].SetMarkerColor(ROOT.kBlue-3) - h['By+'].SetMarkerColor(ROOT.kBlue+3) - h['Bz-'].SetMarkerColor(ROOT.kCyan-2) - h['Bz+'].SetMarkerColor(ROOT.kCyan+2) - for ix in range(grid[0]): - for iy in range(grid[1]): - for iz in range(grid[2]): - x,y,z = xmin + ix*dx,ymin + iy*dy,zmin + iz*dz - n = fGeo.FindNode(x,y,z) - f = n.GetVolume().GetField() - if f: - if f.GetFieldValue()[0]<0: rc=h['Bx-'].Fill(z,x,y,-f.GetFieldValue()[0]/u.tesla) - if f.GetFieldValue()[0]>0: rc=h['Bx+'].Fill(z,x,y,f.GetFieldValue()[0]/u.tesla) - if f.GetFieldValue()[1]<0: rc=h['By-'].Fill(z,x,y,-f.GetFieldValue()[1]/u.tesla) - if f.GetFieldValue()[1]>0: rc=h['By+'].Fill(z,x,y,f.GetFieldValue()[1]/u.tesla) - if f.GetFieldValue()[2]<0: rc=h['Bz-'].Fill(z,x,y,-f.GetFieldValue()[2]/u.tesla) - if f.GetFieldValue()[2]>0: rc=h['Bz+'].Fill(z,x,y,f.GetFieldValue()[2]/u.tesla) - f = run.GetField() - if f.GetBx(x,y,z)<0: rc=h['Bx-'].Fill(z,x,y,-f.GetBx(x,y,z)/u.tesla) - if f.GetBx(x,y,z)>0: rc=h['Bx+'].Fill(z,x,y,f.GetBx(x,y,z)/u.tesla) - if f.GetBy(x,y,z)<0: rc=h['By-'].Fill(z,x,y,-f.GetBy(x,y,z)/u.tesla) - if f.GetBy(x,y,z)>0: rc=h['By+'].Fill(z,x,y,f.GetBy(x,y,z)/u.tesla) - for x in h.keys(): - hi = h[x] - if hi.ClassName()=='TH3F': - h[x+'_xz']=h[x].Project3D('xy') - h[x+'_xz'].SetTitle(hi.GetTitle()+' top view') - h[x+'_yz']=h[x].Project3D('xz') - h[x+'_yz'].SetTitle(hi.GetTitle()+' side view') - for x in h: - h[x].SetStats(0) - h[x].SetMarkerSize(3) - txt = {'y':[' Up',' Down'],'x':[' Right',' Left']} - for pol in ['y','x']: - for p in ['_xz','_yz']: - cn = 'c'+pol+p - ut.bookCanvas(h,key=cn,title='field check',nx=1600,ny=1200,cx=1,cy=1) - h[cn].cd(1) - h['B'+pol+'+'+p].Draw() - h['B'+pol+'-'+p].Draw('same') - h['B'+pol+'L'+p] = ROOT.TLegend(0.79,0.72,0.91,0.87) - h['B'+pol+'L'+p].AddEntry(h['B'+pol+'+'],'B'+pol+txt[pol][0],'PM') - h['B'+pol+'L'+p].AddEntry(h['B'+pol+'-'],'B'+pol+txt[pol][1],'PM') - h['B'+pol+'L'+p].Draw() - h[cn].Update() - h[cn].Print('FieldB'+pol+'Proj'+p+'.png') + fGeo = ROOT.gGeoManager + run = sys.modules["__main__"].run + if hasattr(sys.modules["__main__"], "h"): + h = sys.modules["__main__"].h + else: + h = {} + grid = 120, 100, 1500 + xmin, ymin, zmin = -4 * u.m, -5 * u.m, -100 * u.m + xmax, ymax, zmax = 4 * u.m, 5 * u.m, 50 * u.m + dx, dy, dz = ( + (xmax - xmin) / grid[0], + (ymax - ymin) / grid[1], + (zmax - zmin) / grid[2], + ) + ut.bookHist( + h, + "Bx-", + "Bx- component ;z [cm];x [cm];y [cm]", + grid[2], + zmin, + zmax, + grid[0], + xmin, + xmax, + grid[1], + ymin, + ymax, + ) + ut.bookHist( + h, + "By-", + "By- component ;z [cm];x [cm];y [cm]", + grid[2], + zmin, + zmax, + grid[0], + xmin, + xmax, + grid[1], + ymin, + ymax, + ) + ut.bookHist( + h, + "Bz-", + "Bz- component ;z [cm];x [cm];y [cm]", + grid[2], + zmin, + zmax, + grid[0], + xmin, + xmax, + grid[1], + ymin, + ymax, + ) + ut.bookHist( + h, + "Bx+", + "Bx+ component ;z [cm];x [cm];y [cm]", + grid[2], + zmin, + zmax, + grid[0], + xmin, + xmax, + grid[1], + ymin, + ymax, + ) + ut.bookHist( + h, + "By+", + "By+ component ;z [cm];x [cm];y [cm]", + grid[2], + zmin, + zmax, + grid[0], + xmin, + xmax, + grid[1], + ymin, + ymax, + ) + ut.bookHist( + h, + "Bz+", + "Bz+ component ;z [cm];x [cm];y [cm]", + grid[2], + zmin, + zmax, + grid[0], + xmin, + xmax, + grid[1], + ymin, + ymax, + ) + h["Bx-"].SetMarkerColor(ROOT.kGreen - 3) + h["Bx+"].SetMarkerColor(ROOT.kGreen + 3) + h["By-"].SetMarkerColor(ROOT.kBlue - 3) + h["By+"].SetMarkerColor(ROOT.kBlue + 3) + h["Bz-"].SetMarkerColor(ROOT.kCyan - 2) + h["Bz+"].SetMarkerColor(ROOT.kCyan + 2) + for ix in range(grid[0]): + for iy in range(grid[1]): + for iz in range(grid[2]): + x, y, z = xmin + ix * dx, ymin + iy * dy, zmin + iz * dz + n = fGeo.FindNode(x, y, z) + f = n.GetVolume().GetField() + if f: + if f.GetFieldValue()[0] < 0: + rc = h["Bx-"].Fill(z, x, y, -f.GetFieldValue()[0] / u.tesla) + if f.GetFieldValue()[0] > 0: + rc = h["Bx+"].Fill(z, x, y, f.GetFieldValue()[0] / u.tesla) + if f.GetFieldValue()[1] < 0: + rc = h["By-"].Fill(z, x, y, -f.GetFieldValue()[1] / u.tesla) + if f.GetFieldValue()[1] > 0: + rc = h["By+"].Fill(z, x, y, f.GetFieldValue()[1] / u.tesla) + if f.GetFieldValue()[2] < 0: + rc = h["Bz-"].Fill(z, x, y, -f.GetFieldValue()[2] / u.tesla) + if f.GetFieldValue()[2] > 0: + rc = h["Bz+"].Fill(z, x, y, f.GetFieldValue()[2] / u.tesla) + f = run.GetField() + if f.GetBx(x, y, z) < 0: + rc = h["Bx-"].Fill(z, x, y, -f.GetBx(x, y, z) / u.tesla) + if f.GetBx(x, y, z) > 0: + rc = h["Bx+"].Fill(z, x, y, f.GetBx(x, y, z) / u.tesla) + if f.GetBy(x, y, z) < 0: + rc = h["By-"].Fill(z, x, y, -f.GetBy(x, y, z) / u.tesla) + if f.GetBy(x, y, z) > 0: + rc = h["By+"].Fill(z, x, y, f.GetBy(x, y, z) / u.tesla) + for x in h.keys(): + hi = h[x] + if hi.ClassName() == "TH3F": + h[x + "_xz"] = h[x].Project3D("xy") + h[x + "_xz"].SetTitle(hi.GetTitle() + " top view") + h[x + "_yz"] = h[x].Project3D("xz") + h[x + "_yz"].SetTitle(hi.GetTitle() + " side view") + for x in h: + h[x].SetStats(0) + h[x].SetMarkerSize(3) + txt = {"y": [" Up", " Down"], "x": [" Right", " Left"]} + for pol in ["y", "x"]: + for p in ["_xz", "_yz"]: + cn = "c" + pol + p + ut.bookCanvas(h, key=cn, title="field check", nx=1600, ny=1200, cx=1, cy=1) + h[cn].cd(1) + h["B" + pol + "+" + p].Draw() + h["B" + pol + "-" + p].Draw("same") + h["B" + pol + "L" + p] = ROOT.TLegend(0.79, 0.72, 0.91, 0.87) + h["B" + pol + "L" + p].AddEntry( + h["B" + pol + "+"], "B" + pol + txt[pol][0], "PM" + ) + h["B" + pol + "L" + p].AddEntry( + h["B" + pol + "-"], "B" + pol + txt[pol][1], "PM" + ) + h["B" + pol + "L" + p].Draw() + h[cn].Update() + h[cn].Print("FieldB" + pol + "Proj" + p + ".png") diff --git a/python/configGenieGenerator.py b/python/configGenieGenerator.py index f356e1a82b..089e124d01 100644 --- a/python/configGenieGenerator.py +++ b/python/configGenieGenerator.py @@ -1,40 +1,72 @@ import ROOT + + # configure the GenieGenerator def config(GenieGen): - fGeo = ROOT.gGeoManager - top = fGeo.GetTopVolume() -# positions for nu events inside the nutau detector volume - muDetector = top.FindNode("volNuTauMudet_1") - muDetectorTrans = muSpectrometer.GetMatrix().GetTranslation() -# upper and lower yokes: -# volFeYoke_1, volFeYoke_2, volFeYoke1_1 (in UpYoke) and volFeYoke_3, volFeYoke_4, volFeYoke1_1 (in LowYoke). - yokes = ["volUpYoke_1","volLowYoke_1","volArm2Mudet_1"] - vols = ["volFeYoke_1", "volFeYoke_2", "volFeYoke1_1","volFeYoke_3", "volFeYoke_4","volIron_12","volIron_23"] - dVec = {} - box = {} - for anode in muSpectrometer.GetNodes(): - if anode.GetName() in yokes: - aTrans = anode.GetMatrix().GetTranslation() - for bnode in anode.GetNodes(): - if bnode.GetName() in vols: - bTrans = bnode.GetMatrix().GetTranslation() - nm = anode.GetName()+'/'+bnode.GetName() - dVec[nm] = ROOT.TVector3() - x = [] - for k in range(3): x.append(aTrans[k]+bTrans[k]+muSpectrometerTrans[k]) - dVec[nm].SetXYZ(x[0],x[1],x[2]) - sbnode = bnode.GetVolume().GetShape() - box[nm]=ROOT.TVector3(sbnode.GetDX(),sbnode.GetDY(),sbnode.GetDZ()) - print("Debug muonSpectro ",nm,dVec[nm],box[nm]) - length = dVec["volArm2Mudet_1/volIron_23"].Z()-dVec["volArm2Mudet_1/volIron_12"].Z() - zpos = ( dVec["volArm2Mudet_1/volIron_12"].Z()+dVec["volArm2Mudet_1/volIron_23"].Z() )/2. - box["volArm2Mudet_1/volIron_12-23"] = ROOT.TVector3(box["volArm2Mudet_1/volIron_12"].X(),box["volArm2Mudet_1/volIron_12"].Y(),length) - dVec["volArm2Mudet_1/volIron_12-23"] = ROOT.TVector3(0,0,zpos) - rc = box.pop("volArm2Mudet_1/volIron_23") - rc = box.pop("volArm2Mudet_1/volIron_12") - if GenieGen=='debug': - for aVol in box: - print('%50s %6.2F %6.2F %6.2F %5.2F %7.2F %7.2F '%(aVol,box[aVol].X(),box[aVol].Y(),box[aVol].Z(),dVec[aVol].X(),dVec[aVol].Y(),dVec[aVol].Z())) - else: - for aVol in box: - GenieGen.AddBox(dVec[aVol],box[aVol]) + fGeo = ROOT.gGeoManager + top = fGeo.GetTopVolume() + # positions for nu events inside the nutau detector volume + muDetector = top.FindNode("volNuTauMudet_1") + muDetectorTrans = muSpectrometer.GetMatrix().GetTranslation() + # upper and lower yokes: + # volFeYoke_1, volFeYoke_2, volFeYoke1_1 (in UpYoke) and volFeYoke_3, volFeYoke_4, volFeYoke1_1 (in LowYoke). + yokes = ["volUpYoke_1", "volLowYoke_1", "volArm2Mudet_1"] + vols = [ + "volFeYoke_1", + "volFeYoke_2", + "volFeYoke1_1", + "volFeYoke_3", + "volFeYoke_4", + "volIron_12", + "volIron_23", + ] + dVec = {} + box = {} + for anode in muSpectrometer.GetNodes(): + if anode.GetName() in yokes: + aTrans = anode.GetMatrix().GetTranslation() + for bnode in anode.GetNodes(): + if bnode.GetName() in vols: + bTrans = bnode.GetMatrix().GetTranslation() + nm = anode.GetName() + "/" + bnode.GetName() + dVec[nm] = ROOT.TVector3() + x = [] + for k in range(3): + x.append(aTrans[k] + bTrans[k] + muSpectrometerTrans[k]) + dVec[nm].SetXYZ(x[0], x[1], x[2]) + sbnode = bnode.GetVolume().GetShape() + box[nm] = ROOT.TVector3( + sbnode.GetDX(), sbnode.GetDY(), sbnode.GetDZ() + ) + print("Debug muonSpectro ", nm, dVec[nm], box[nm]) + length = ( + dVec["volArm2Mudet_1/volIron_23"].Z() - dVec["volArm2Mudet_1/volIron_12"].Z() + ) + zpos = ( + dVec["volArm2Mudet_1/volIron_12"].Z() + dVec["volArm2Mudet_1/volIron_23"].Z() + ) / 2.0 + box["volArm2Mudet_1/volIron_12-23"] = ROOT.TVector3( + box["volArm2Mudet_1/volIron_12"].X(), + box["volArm2Mudet_1/volIron_12"].Y(), + length, + ) + dVec["volArm2Mudet_1/volIron_12-23"] = ROOT.TVector3(0, 0, zpos) + rc = box.pop("volArm2Mudet_1/volIron_23") + rc = box.pop("volArm2Mudet_1/volIron_12") + if GenieGen == "debug": + for aVol in box: + print( + "%50s %6.2F %6.2F %6.2F %5.2F %7.2F %7.2F " + % ( + aVol, + box[aVol].X(), + box[aVol].Y(), + box[aVol].Z(), + dVec[aVol].X(), + dVec[aVol].Y(), + dVec[aVol].Z(), + ) + ) + else: + for aVol in box: + GenieGen.AddBox(dVec[aVol], box[aVol]) diff --git a/python/darkphoton.py b/python/darkphoton.py index c8e90da198..fc44dbd07a 100644 --- a/python/darkphoton.py +++ b/python/darkphoton.py @@ -1,35 +1,37 @@ import math import os -import ROOT as r -#from settings import * -#from functions import * -from hnl import mass -from hnl import PDGname +import ROOT as r +# from settings import * +# from functions import * +from hnl import PDGname, mass # constants -alphaQED = 1./137. -ccm = 2.99792458e+10 -hGeV = 6.58211928*pow(10.,-16)* pow(10.,-9) # no units or it messes up!! +alphaQED = 1.0 / 137.0 +ccm = 2.99792458e10 +hGeV = 6.58211928 * pow(10.0, -16) * pow(10.0, -9) # no units or it messes up!! -#utilities +# utilities # sigma(e+e- -> hadrons) / sigma(e+e- -> mu+mu-) + class DarkPhoton: "dark photon setup" def __init__(self, mass, eps): self.mDarkPhoton = mass self.epsilon = eps - self.dataEcm,self.dataR = self.readPDGtable() + self.dataEcm, self.dataR = self.readPDGtable() self.PdgR = self.interpolatePDGtable() def readPDGtable(self): - """ Returns R data from PDG in a easy to use format """ - ecm=r.vector('double')() - ratio=r.vector('double')() + """Returns R data from PDG in a easy to use format""" + ecm = r.vector("double")() + ratio = r.vector("double")() """ecm,ratio = [],[]""" - with open(os.path.expandvars('$FAIRSHIP/input/rpp2012-hadronicrpp_page1001.dat'),'r') as f: + with open( + os.path.expandvars("$FAIRSHIP/input/rpp2012-hadronicrpp_page1001.dat"), "r" + ) as f: for line in f: line = line.split() try: @@ -37,133 +39,143 @@ def readPDGtable(self): numR = float(line[3]) strType = line[7] strBis = line[8] - #if numEcm<2: + # if numEcm<2: # print numEcm,numR,strType - if (('EXCLSUM' in strType) or ('EDWARDS' in strType) or ('BLINOV' in strType)): + if ( + ("EXCLSUM" in strType) + or ("EDWARDS" in strType) + or ("BLINOV" in strType) + ): ecm.push_back(numEcm) ratio.push_back(numR) - #print numEcm,numR,strType - if 'BAI' in strType and '01' in strBis: + # print numEcm,numR,strType + if "BAI" in strType and "01" in strBis: ecm.push_back(numEcm) ratio.push_back(numR) - #print numEcm,numR,strType + # print numEcm,numR,strType except: continue - return ecm,ratio - + return ecm, ratio def interpolatePDGtable(self): - """ Find the best value for R for the given center-of-mass energy """ - fun = r.Math.Interpolator(self.dataEcm.size(),r.Math.Interpolation.kLINEAR) - fun.SetData(self.dataEcm,self.dataR); + """Find the best value for R for the given center-of-mass energy""" + fun = r.Math.Interpolator(self.dataEcm.size(), r.Math.Interpolation.kLINEAR) + fun.SetData(self.dataEcm, self.dataR) return fun - def Ree_interp(self,s): # s in GeV - """ Using PDG values for sigma(e+e- -> hadrons) / sigma(e+e- -> mu+mu-) """ + def Ree_interp(self, s): # s in GeV + """Using PDG values for sigma(e+e- -> hadrons) / sigma(e+e- -> mu+mu-)""" # Da http://pdg.lbl.gov/2012/hadronic-xsections/hadron.html#miscplots - #ecm = math.sqrt(s) + # ecm = math.sqrt(s) ecm = s - if ecm>=10.29: - print('Warning! Asking for interpolation beyond 10.29 GeV: not implemented, needs extending! Taking value at 10.29 GeV') - result=float(self.PdgR.Eval(10.29)) - elif ecm>=self.dataEcm[0]: + if ecm >= 10.29: + print( + "Warning! Asking for interpolation beyond 10.29 GeV: not implemented, needs extending! Taking value at 10.29 GeV" + ) + result = float(self.PdgR.Eval(10.29)) + elif ecm >= self.dataEcm[0]: result = float(self.PdgR.Eval(ecm)) else: - result=0 - #print 'Ree_interp for mass %3.3f is %.3e'%(s,result) + result = 0 + # print 'Ree_interp for mass %3.3f is %.3e'%(s,result) return result - def leptonicDecayWidth(self,lepton): # mDarkPhoton in GeV - """ Dark photon decay width into leptons, in GeV (input short name of lepton family) """ + def leptonicDecayWidth(self, lepton): # mDarkPhoton in GeV + """Dark photon decay width into leptons, in GeV (input short name of lepton family)""" ml = mass(lepton) - #print 'lepton %s mass %.3e'%(lepton,ml) + # print 'lepton %s mass %.3e'%(lepton,ml) - constant = (1./3.) * alphaQED * self.mDarkPhoton * pow(self.epsilon, 2.) - if 2.*ml < self.mDarkPhoton: - rad = math.sqrt( 1. - (4.*ml*ml)/(self.mDarkPhoton*self.mDarkPhoton) ) + constant = (1.0 / 3.0) * alphaQED * self.mDarkPhoton * pow(self.epsilon, 2.0) + if 2.0 * ml < self.mDarkPhoton: + rad = math.sqrt( + 1.0 - (4.0 * ml * ml) / (self.mDarkPhoton * self.mDarkPhoton) + ) else: - rad = 0. + rad = 0.0 - par = 1. + (2.*ml*ml)/(self.mDarkPhoton*self.mDarkPhoton) - tdw=math.fabs(constant*rad*par) - #print 'Leptonic decay width to %s is %.3e'%(lepton,tdw) + par = 1.0 + (2.0 * ml * ml) / (self.mDarkPhoton * self.mDarkPhoton) + tdw = math.fabs(constant * rad * par) + # print 'Leptonic decay width to %s is %.3e'%(lepton,tdw) return tdw - def leptonicBranchingRatio(self,lepton): + def leptonicBranchingRatio(self, lepton): return self.leptonicDecayWidth(lepton) / self.totalDecayWidth() def hadronicDecayWidth(self): - """ Dark photon decay into hadrons """ + """Dark photon decay into hadrons""" """(mumu)*R""" - gmumu=self.leptonicDecayWidth('mu-') - tdw=gmumu*self.Ree_interp(self.mDarkPhoton) - #print 'Hadronic decay width is %.3e'%(tdw) - return tdw; + gmumu = self.leptonicDecayWidth("mu-") + tdw = gmumu * self.Ree_interp(self.mDarkPhoton) + # print 'Hadronic decay width is %.3e'%(tdw) + return tdw def hadronicBranchingRatio(self): return self.hadronicDecayWidth() / self.totalDecayWidth() - def totalDecayWidth(self): # mDarkPhoton in GeV - """ Total decay width in GeV """ - #return hGeV*c / cTau(mDarkPhoton, epsilon) - tdw = (self.leptonicDecayWidth('e-') - + self.leptonicDecayWidth('mu-') - + self.leptonicDecayWidth('tau-') - + self.hadronicDecayWidth()) + def totalDecayWidth(self): # mDarkPhoton in GeV + """Total decay width in GeV""" + # return hGeV*c / cTau(mDarkPhoton, epsilon) + tdw = ( + self.leptonicDecayWidth("e-") + + self.leptonicDecayWidth("mu-") + + self.leptonicDecayWidth("tau-") + + self.hadronicDecayWidth() + ) - #print 'Total decay width %e'%(tdw) + # print 'Total decay width %e'%(tdw) return tdw - def cTau(self): # decay length in meters, dark photon mass in GeV - """ Dark Photon lifetime in cm""" - ctau=hGeV*ccm/self.totalDecayWidth() - #print "ctau dp.py %.3e"%(ctau) - return ctau #GeV/MeV conversion + def cTau(self): # decay length in meters, dark photon mass in GeV + """Dark Photon lifetime in cm""" + ctau = hGeV * ccm / self.totalDecayWidth() + # print "ctau dp.py %.3e"%(ctau) + return ctau # GeV/MeV conversion def lifetime(self): - return self.cTau()/ccm - - def findBranchingRatio(self,decayString): - br = 0. - if decayString == 'A -> e- e+': br = self.leptonicBranchingRatio('e-') - elif decayString == 'A -> mu- mu+': br = self.leptonicBranchingRatio('mu-') - elif decayString == 'A -> tau- tau+': br = self.leptonicBranchingRatio('tau-') - elif decayString == 'A -> hadrons': br = self.hadronicBranchingRatio() + return self.cTau() / ccm + + def findBranchingRatio(self, decayString): + br = 0.0 + if decayString == "A -> e- e+": + br = self.leptonicBranchingRatio("e-") + elif decayString == "A -> mu- mu+": + br = self.leptonicBranchingRatio("mu-") + elif decayString == "A -> tau- tau+": + br = self.leptonicBranchingRatio("tau-") + elif decayString == "A -> hadrons": + br = self.hadronicBranchingRatio() else: - print('findBranchingRatio ERROR: unknown decay %s'%decayString) + print("findBranchingRatio ERROR: unknown decay %s" % decayString) quit() return br def allowedChannels(self): - print("Allowed channels for dark photon mass = %3.3f"%self.mDarkPhoton) - allowedDecays = {'A -> hadrons':'yes'} - if self.mDarkPhoton > 2.*mass('e-'): - allowedDecays.update({'A -> e- e+':'yes'}) + print("Allowed channels for dark photon mass = %3.3f" % self.mDarkPhoton) + allowedDecays = {"A -> hadrons": "yes"} + if self.mDarkPhoton > 2.0 * mass("e-"): + allowedDecays.update({"A -> e- e+": "yes"}) print("allowing decay to e") - if self.mDarkPhoton > 2.*mass('mu-'): - allowedDecays.update({'A -> mu- mu+':'yes'}) + if self.mDarkPhoton > 2.0 * mass("mu-"): + allowedDecays.update({"A -> mu- mu+": "yes"}) print("allowing decay to mu") - if self.mDarkPhoton > 2.*mass('tau-'): - allowedDecays.update({'A -> tau- tau+':'yes'}) + if self.mDarkPhoton > 2.0 * mass("tau-"): + allowedDecays.update({"A -> tau- tau+": "yes"}) print("allowing decay to tau") return allowedDecays - - def scaleNEventsIncludingHadrons(self,n): - """ Very simple patch to take into account A' -> hadrons """ + def scaleNEventsIncludingHadrons(self, n): + """Very simple patch to take into account A' -> hadrons""" brh = self.hadronicBranchingRatio() - #print brh + # print brh # if M > m(c cbar): - if self.mDarkPhoton > 2.*mass('c'): - visible_frac = 1. + if self.mDarkPhoton > 2.0 * mass("c"): + visible_frac = 1.0 else: - visible_frac = 2./3. - - increase = brh*visible_frac - #print increase - return n*(1. + increase) - + visible_frac = 2.0 / 3.0 + increase = brh * visible_frac + # print increase + return n * (1.0 + increase) diff --git a/python/decorators.py b/python/decorators.py index bb7f0dfbd0..429a829615 100644 --- a/python/decorators.py +++ b/python/decorators.py @@ -1,77 +1,152 @@ from ctypes import c_double + import ROOT import shipunit as u + def MCPointPrintOut(x): - p = ROOT.TDatabasePDG.Instance().GetParticle(x.PdgCode()) - n='' - if p: n = p.GetName() - txt = '("%s") X:%6.3Fcm Y:%6.3Fcm Z:%6.3Fcm dE/dx:%6.2FMeV %s'%(\ - x.Class_Name(),x.GetX(),x.GetY(),x.GetZ(),x.GetEnergyLoss()/u.MeV,n) - return txt + p = ROOT.TDatabasePDG.Instance().GetParticle(x.PdgCode()) + n = "" + if p: + n = p.GetName() + txt = '("%s") X:%6.3Fcm Y:%6.3Fcm Z:%6.3Fcm dE/dx:%6.2FMeV %s' % ( + x.Class_Name(), + x.GetX(), + x.GetY(), + x.GetZ(), + x.GetEnergyLoss() / u.MeV, + n, + ) + return txt + + def MCTrackPrintOut(x): - c = x.GetPdgCode() - p = ROOT.TDatabasePDG.Instance().GetParticle(c) - n='' - if p: n = p.GetName() - m = x.GetMotherId() - txt = '("ShipMCTrack") pdgCode: %7i(%10s) Z=%6.1F m P=%6.3F GeV/c mother=%i %s'%(c,n,x.GetStartZ()/u.m,x.GetP(),m,x.GetProcName()) - return txt + c = x.GetPdgCode() + p = ROOT.TDatabasePDG.Instance().GetParticle(c) + n = "" + if p: + n = p.GetName() + m = x.GetMotherId() + txt = '("ShipMCTrack") pdgCode: %7i(%10s) Z=%6.1F m P=%6.3F GeV/c mother=%i %s' % ( + c, + n, + x.GetStartZ() / u.m, + x.GetP(), + m, + x.GetProcName(), + ) + return txt + + def vetoHitPrintOut(x): - txt = '("vetoHit") detID:%7i ADC:%5.2F TDC:%5.2F'%(x.GetDetectorID(),x.GetADC(),x.GetTDC()) - return txt + txt = '("vetoHit") detID:%7i ADC:%5.2F TDC:%5.2F' % ( + x.GetDetectorID(), + x.GetADC(), + x.GetTDC(), + ) + return txt + + def muonHitPrintOut(x): - txt = '("muonHit") detID:%7i TDC:%5.2F isValid:%r'%(x.GetDetectorID(),x.GetDigi(),x.isValid()) - return txt + txt = '("muonHit") detID:%7i TDC:%5.2F isValid:%r' % ( + x.GetDetectorID(), + x.GetDigi(), + x.isValid(), + ) + return txt + + def TimeDetHitPrintOut(x): - t = x.GetMeasurements() - txt = '("TimeDetHit") detID:%7i TDC1:%5.2F TDC2:%5.2F isValid:%r'%(x.GetDetectorID(),t[0],t[1],x.isValid()) - return txt + t = x.GetMeasurements() + txt = '("TimeDetHit") detID:%7i TDC1:%5.2F TDC2:%5.2F isValid:%r' % ( + x.GetDetectorID(), + t[0], + t[1], + x.isValid(), + ) + return txt + + def FitTrackPrintOut(x): - st = x.getFitStatus() - if st.isFitConverged(): - chi2DoF = st.getChi2()/st.getNdf() - sta = x.getFittedState() - P = sta.getMomMag() - txt = '("FitTrack") chi2/dof:%3.1F P:%5.2FGeV/c pdg:%i'%(chi2DoF,P,sta.getPDG()) - else: - txt = '("FitTrack") fit not converged' - return txt + st = x.getFitStatus() + if st.isFitConverged(): + chi2DoF = st.getChi2() / st.getNdf() + sta = x.getFittedState() + P = sta.getMomMag() + txt = '("FitTrack") chi2/dof:%3.1F P:%5.2FGeV/c pdg:%i' % ( + chi2DoF, + P, + sta.getPDG(), + ) + else: + txt = '("FitTrack") fit not converged' + return txt + + def TParticlePrintOut(x): - txt = '("TParticle") %s P:%5.2FGeV/c VxZ:%5.2Fm'%(x.GetName(),x.P(),x.Vz()/u.m) - return txt + txt = '("TParticle") %s P:%5.2FGeV/c VxZ:%5.2Fm' % ( + x.GetName(), + x.P(), + x.Vz() / u.m, + ) + return txt + + def ShipParticlePrintOut(x): - txt = '("ShipParticle") %s M:%5.2FGeV/c2 P:%5.2FGeV/c VxZ:%5.2Fm'%(x.GetName(),x.GetMass(),x.P(),x.Vz()/u.m) - return txt + txt = '("ShipParticle") %s M:%5.2FGeV/c2 P:%5.2FGeV/c VxZ:%5.2Fm' % ( + x.GetName(), + x.GetMass(), + x.P(), + x.Vz() / u.m, + ) + return txt + + def ecalReconstructedPrintOut(cl): - txt = '("EcalCluster") E:%5.2FGeV/c X:%5.2Fm Y:%5.2Fm'%(cl.RecoE(),cl.X()/u.m,cl.Y()/u.m) - return txt + txt = '("EcalCluster") E:%5.2FGeV/c X:%5.2Fm Y:%5.2Fm' % ( + cl.RecoE(), + cl.X() / u.m, + cl.Y() / u.m, + ) + return txt + + def ecalClusterPrintOut(cl): - txt = '("EcalCluster") E:%5.2FGeV/c X:%5.2Fm Y:%5.2Fm'%(cl.Energy(),cl.X()/u.m,cl.Y()/u.m) - return txt + txt = '("EcalCluster") E:%5.2FGeV/c X:%5.2Fm Y:%5.2Fm' % ( + cl.Energy(), + cl.X() / u.m, + cl.Y() / u.m, + ) + return txt + + def Dump(x): - k=0 - for obj in x: - print(k,obj.__repr__()) - k+=1 + k = 0 + for obj in x: + print(k, obj.__repr__()) + k += 1 + def TVector3PrintOut(x): - txt = '%9.5F,%9.5F,%9.5F'%(x.X(),x.Y(),x.Z()) - return txt + txt = "%9.5F,%9.5F,%9.5F" % (x.X(), x.Y(), x.Z()) + return txt + def TLorentzVectorPrintOut(x): - txt = '%9.5F,%9.5F,%9.5F,%9.5F,%9.5F'%(x.Px(),x.Py(),x.Pz(),x.E(),x.Mag()) - return txt + txt = "%9.5F,%9.5F,%9.5F,%9.5F,%9.5F" % (x.Px(), x.Py(), x.Pz(), x.E(), x.Mag()) + return txt + def TEvePointSetPrintOut(P): - x, y, z = c_double(), c_double(), c_double() - txt = '' - if P.GetN()==0: txt = '' - for n in range(P.GetN()): - rc = P.GetPoint(n,x,y,z) - txt += f'{n:6d} {x.value:7.1f}, {y.value:7.1f}, {z.value:9.1f} x, y, z cm\n' - - return txt + x, y, z = c_double(), c_double(), c_double() + txt = "" + if P.GetN() == 0: + txt = "" + for n in range(P.GetN()): + rc = P.GetPoint(n, x, y, z) + txt += f"{n:6d} {x.value:7.1f}, {y.value:7.1f}, {z.value:9.1f} x, y, z cm\n" + + return txt ROOT.FairMCPoint.__repr__ = MCPointPrintOut diff --git a/python/detectArch b/python/detectArch index 683cbb3143..d77fb88f67 100755 --- a/python/detectArch +++ b/python/detectArch @@ -1,5 +1,8 @@ #!/usr/bin/env python -import os,sys +import os +import sys + sys.path.append(os.environ['SHIPBUILD']+'/alibuild') -from alibuild_helpers.utilities import getVersion, detectArch +from alibuild_helpers.utilities import detectArch, getVersion + print detectArch() diff --git a/python/dpProductionRates.py b/python/dpProductionRates.py index 39ab549f36..8105660d04 100644 --- a/python/dpProductionRates.py +++ b/python/dpProductionRates.py @@ -1,114 +1,167 @@ -import ROOT,os,sys,math -import shipunit as u -import proton_bremsstrahlung +import math +import os +import sys +import proton_bremsstrahlung +import ROOT +import shipunit as u PDG = ROOT.TDatabasePDG.Instance() protonFlux = 2e20 def isDP(pdg): - if (pdg==9900015 or pdg==4900023): + if pdg == 9900015 or pdg == 4900023: return True return False -def pbremProdRateVDM(mass,epsilon,doprint=True): + +def pbremProdRateVDM(mass, epsilon, doprint=True): xswg = proton_bremsstrahlung.prodRate(mass, epsilon) - if doprint: print("A' production rate per p.o.t: \t %.8g"%(xswg)) - rhoff = proton_bremsstrahlung.rhoFormFactor(mass)**2 - if doprint: print("A' rho form factor: \t %.8g"%rhoff) - if doprint: print("A' rescaled production rate per p.o.t:\t %.8g"%(xswg*rhoff)) - return xswg*rhoff + if doprint: + print("A' production rate per p.o.t: \t %.8g" % (xswg)) + rhoff = proton_bremsstrahlung.rhoFormFactor(mass) ** 2 + if doprint: + print("A' rho form factor: \t %.8g" % rhoff) + if doprint: + print("A' rescaled production rate per p.o.t:\t %.8g" % (xswg * rhoff)) + return xswg * rhoff -def pbremProdRateDipole(mass,epsilon,doprint=False): + +def pbremProdRateDipole(mass, epsilon, doprint=False): xswg = proton_bremsstrahlung.prodRate(mass, epsilon) - if doprint: print("A' production rate per p.o.t: \t %.8g"%(xswg)) + if doprint: + print("A' production rate per p.o.t: \t %.8g" % (xswg)) penalty = proton_bremsstrahlung.penaltyFactor(mass) - if doprint: print("A' penalty factor: \t %.8g"%penalty) - if doprint: print("A' rescaled production rate per p.o.t:\t %.8g"%(xswg*penalty)) - return xswg*penalty + if doprint: + print("A' penalty factor: \t %.8g" % penalty) + if doprint: + print("A' rescaled production rate per p.o.t:\t %.8g" % (xswg * penalty)) + return xswg * penalty + -#obtained with Pythia8: average number of meson expected per p.o.t from inclusive pp to X production, 100k events produced +# obtained with Pythia8: average number of meson expected per p.o.t from inclusive pp to X production, 100k events produced def getAverageMesonRate(mumPdg): - if (mumPdg==111): return 6.166 - if (mumPdg==221): return 0.7012 - if (mumPdg==223): return 0.8295 - if (mumPdg==331): return 0.07825 - print(" -- ERROR, unknown mother pdgId %d"%mumPdg) + if mumPdg == 111: + return 6.166 + if mumPdg == 221: + return 0.7012 + if mumPdg == 223: + return 0.8295 + if mumPdg == 331: + return 0.07825 + print(" -- ERROR, unknown mother pdgId %d" % mumPdg) return 0 -#from the PDG, decay to photon channels available for mixing with DP -def mesonBRtoPhoton(mumPdg,doprint=False): + +# from the PDG, decay to photon channels available for mixing with DP +def mesonBRtoPhoton(mumPdg, doprint=False): br = 1 - if (mumPdg==111): br = 0.9879900 - if (mumPdg==221): br = 0.3931181 - if (mumPdg==223): br = 0.0834941 - if (mumPdg==331): br = 0.0219297 - if (doprint==True): print("BR of %d meson to photons: %.8g"%(mumPdg,br)) + if mumPdg == 111: + br = 0.9879900 + if mumPdg == 221: + br = 0.3931181 + if mumPdg == 223: + br = 0.0834941 + if mumPdg == 331: + br = 0.0219297 + if doprint == True: + print("BR of %d meson to photons: %.8g" % (mumPdg, br)) return br -def brMesonToGammaDP(mass,epsilon,mumPdg,doprint=False): + +def brMesonToGammaDP(mass, epsilon, mumPdg, doprint=False): mMeson = PDG.GetParticle(mumPdg).Mass() - if (doprint==True): print("Mass of mother %d meson is %3.3f"%(mumPdg,mMeson)) - if (mass 3.): - xs = math.exp(-5.928-0.8669*mass) - elif (mass > 1.4): - xs = math.exp(-4.1477-1.4745*mass) + +def mesonProdRate(mass, epsilon, mumPdg, doprint=False): + brM2DP = brMesonToDP(mass, epsilon, mumPdg, doprint) + if mumPdg == 331: + avgMeson = getAverageMesonRate(mumPdg) * brM2DP[0] + avgMeson1 = getAverageMesonRate(mumPdg) * brM2DP[1] + return avgMeson * 0.6, avgMeson1 * 0.6 + # return avgMeson + avgMeson1 + if not mumPdg == 331: + avgMeson = getAverageMesonRate(mumPdg) * brM2DP + return avgMeson * 0.6 + + +# from interpolation of Pythia XS, normalised to epsilon^2 +def qcdprodRate(mass, epsilon, doprint=False): + if mass > 3.0: + xs = math.exp(-5.928 - 0.8669 * mass) + elif mass > 1.4: + xs = math.exp(-4.1477 - 1.4745 * mass) else: - xs = 0. - return xs*epsilon*epsilon + xs = 0.0 + return xs * epsilon * epsilon + -def getDPprodRate(mass,epsilon,prodMode,mumPdg,doprint=False): - if ('pbrem' in prodMode): +def getDPprodRate(mass, epsilon, prodMode, mumPdg, doprint=False): + if "pbrem" in prodMode: print("VDM") - return pbremProdRateVDM(mass,epsilon,doprint) - elif ('pbrem1' in prodMode): + return pbremProdRateVDM(mass, epsilon, doprint) + elif "pbrem1" in prodMode: print("Dipole") - return pbremProdRateDipole(mass,epsilon,doprint) - elif ('meson' in prodMode): - return mesonProdRate(mass,epsilon,mumPdg,doprint) - elif ('qcd' in prodMode): - return qcdprodRate(mass,epsilon,doprint) + return pbremProdRateDipole(mass, epsilon, doprint) + elif "meson" in prodMode: + return mesonProdRate(mass, epsilon, mumPdg, doprint) + elif "qcd" in prodMode: + return qcdprodRate(mass, epsilon, doprint) else: print("Unknown production mode! Choose among pbrem, meson or qcd.") return 1 diff --git a/python/experimental/analysis_toolkit.py b/python/experimental/analysis_toolkit.py index 436d8ca37b..568bf0d0c4 100644 --- a/python/experimental/analysis_toolkit.py +++ b/python/experimental/analysis_toolkit.py @@ -250,7 +250,7 @@ def preselection_cut(self, candidate, IP_cut=250, show_table=False): [ "Impact Parameter (cm)", self.impact_parameter(candidate), - f"IP < {IP_cut*u.cm} cm", + f"IP < {IP_cut * u.cm} cm", self.impact_parameter(candidate) < IP_cut * u.cm, ], [ diff --git a/python/genie_interface.py b/python/genie_interface.py index 8df3cd5308..0f5588ec8d 100644 --- a/python/genie_interface.py +++ b/python/genie_interface.py @@ -1,6 +1,10 @@ -import ROOT, os, sys, time +import os +import sys +import time from subprocess import call +import ROOT + def get_1D_flux_name(nupdg): """returns name of TH1D p spectrum as stored in input files: diff --git a/python/geomGeant4.py b/python/geomGeant4.py index d971e3950b..b8bac7c23a 100644 --- a/python/geomGeant4.py +++ b/python/geomGeant4.py @@ -1,8 +1,10 @@ -import shipunit as u from array import array + import hepunit as G4Unit -import ShieldUtils import ROOT +import ShieldUtils +import shipunit as u + ROOT.gROOT.ProcessLine('#include "Geant4/G4TransportationManager.hh"') ROOT.gROOT.ProcessLine('#include "Geant4/G4FieldManager.hh"') ROOT.gROOT.ProcessLine('#include "Geant4/G4UIterminal.hh"') @@ -10,178 +12,228 @@ ROOT.gROOT.ProcessLine('#include "TG4GeometryServices.h"') ROOT.gROOT.ProcessLine('#include "TG4GeometryManager.h"') + def check4OrphanVolumes(fGeo): -# fill list with volumes from nodes and compare with list of volumes - top = fGeo.GetTopVolume() - listOfVolumes = [top.GetName()] - findNode(top,listOfVolumes) - orphan = [] - gIndex = {} - for v in fGeo.GetListOfVolumes(): - name = v.GetName() - if not name in listOfVolumes: - orphan.append(name) - if not name in gIndex: gIndex[name]=[] - gIndex[name].append(v.GetNumber()) - print("list of orphan volumes:",orphan) - vSame = {} - for x in gIndex: - if len(gIndex[x])>1: vSame[x]=len(gIndex[x]) - print("list of volumes with same name",vSame) + # fill list with volumes from nodes and compare with list of volumes + top = fGeo.GetTopVolume() + listOfVolumes = [top.GetName()] + findNode(top, listOfVolumes) + orphan = [] + gIndex = {} + for v in fGeo.GetListOfVolumes(): + name = v.GetName() + if not name in listOfVolumes: + orphan.append(name) + if not name in gIndex: + gIndex[name] = [] + gIndex[name].append(v.GetNumber()) + print("list of orphan volumes:", orphan) + vSame = {} + for x in gIndex: + if len(gIndex[x]) > 1: + vSame[x] = len(gIndex[x]) + print("list of volumes with same name", vSame) + def setMagnetField(flag=None): - print('setMagnetField() called. Out of date, does not set field for tau neutrino detector!') + print( + "setMagnetField() called. Out of date, does not set field for tau neutrino detector!" + ) fGeo = ROOT.gGeoManager vols = fGeo.GetListOfVolumes() - #copy field by hand to geant4 - listOfFields={} + # copy field by hand to geant4 + listOfFields = {} for v in vols: - field = v.GetField() - if not field: continue - bx = field.GetFieldValue()[0]/u.tesla*G4Unit.tesla - by = field.GetFieldValue()[1]/u.tesla*G4Unit.tesla - bz = field.GetFieldValue()[2]/u.tesla*G4Unit.tesla - magFieldIron = G4UniformMagField(G4ThreeVector(bx,by,bz)) - FieldIronMgr = G4FieldManager(magFieldIron) - FieldIronMgr.CreateChordFinder(magFieldIron) - listOfFields[v.GetName()]=FieldIronMgr + field = v.GetField() + if not field: + continue + bx = field.GetFieldValue()[0] / u.tesla * G4Unit.tesla + by = field.GetFieldValue()[1] / u.tesla * G4Unit.tesla + bz = field.GetFieldValue()[2] / u.tesla * G4Unit.tesla + magFieldIron = G4UniformMagField(G4ThreeVector(bx, by, bz)) + FieldIronMgr = G4FieldManager(magFieldIron) + FieldIronMgr.CreateChordFinder(magFieldIron) + listOfFields[v.GetName()] = FieldIronMgr gt = ROOT.G4TransportationManager.GetTransportationManager() gn = gt.GetNavigatorForTracking() world = gn.GetWorldVolume().GetLogicalVolume() setField = {} for da in range(world.GetNoDaughters()): - vl0 = world.GetDaughter(da) - vln = vl0.GetName().c_str() + vl0 = world.GetDaughter(da) + vln = vl0.GetName().c_str() lvl0 = vl0.GetLogicalVolume() - if vln in listOfFields : setField[lvl0]=vln + if vln in listOfFields: + setField[lvl0] = vln for dda in range(lvl0.GetNoDaughters()): - vl = lvl0.GetDaughter(dda) - vln = vl.GetName().c_str() - lvl = vl.GetLogicalVolume() - if vln in listOfFields : setField[lvl]=vln + vl = lvl0.GetDaughter(dda) + vln = vl.GetName().c_str() + lvl = vl.GetLogicalVolume() + if vln in listOfFields: + setField[lvl] = vln modified = False for lvl in setField: - # check if field already exists - fm = lvl.GetFieldManager() - if not fm.DoesFieldExist(): - lvl.SetFieldManager(listOfFields[setField[lvl]],True) - modified = True - if flag=='dump': - constField = listOfFields[setField[lvl]].GetDetectorField().GetConstantFieldValue() - print('set field for ',setField[lvl], constField) - else: - if flag=='dump': - print('field already set:',setField[lvl]) + # check if field already exists + fm = lvl.GetFieldManager() + if not fm.DoesFieldExist(): + lvl.SetFieldManager(listOfFields[setField[lvl]], True) + modified = True + if flag == "dump": + constField = ( + listOfFields[setField[lvl]] + .GetDetectorField() + .GetConstantFieldValue() + ) + print("set field for ", setField[lvl], constField) + else: + if flag == "dump": + print("field already set:", setField[lvl]) if modified: - g4Run = G4RunManager.GetRunManager() - g4Run.GeometryHasBeenModified(True) + g4Run = G4RunManager.GetRunManager() + g4Run.GeometryHasBeenModified(True) + -def printWF(vl,alreadyPrinted,onlyWithField=True): +def printWF(vl, alreadyPrinted, onlyWithField=True): magnetMass = 0 vname = vl.GetName().data() - if vname in alreadyPrinted: return magnetMass - vln = vname+' '+str(vl.GetCopyNo()) - mvl = vl.GetMotherLogical().GetName().data() - alreadyPrinted[vname]=mvl - if mvl !='cave': vln = mvl+'/'+vln - lvl = vl.GetLogicalVolume() - cvol = lvl.GetSolid().GetCubicVolume()/G4Unit.m3 - M = lvl.GetMass()/G4Unit.kg + if vname in alreadyPrinted: + return magnetMass + vln = vname + " " + str(vl.GetCopyNo()) + mvl = vl.GetMotherLogical().GetName().data() + alreadyPrinted[vname] = mvl + if mvl != "cave": + vln = mvl + "/" + vln + lvl = vl.GetLogicalVolume() + cvol = lvl.GetSolid().GetCubicVolume() / G4Unit.m3 + M = lvl.GetMass() / G4Unit.kg fm = lvl.GetFieldManager() - if not fm and onlyWithField: return magnetMass - if M < 5000.: print('%-35s volume = %5.2Fm3 mass = %5.2F kg'%(vln,cvol,M)) - else: print('%-35s volume = %5.2Fm3 mass = %5.2F t'%(vln,cvol,M/1000.)) + if not fm and onlyWithField: + return magnetMass + if M < 5000.0: + print("%-35s volume = %5.2Fm3 mass = %5.2F kg" % (vln, cvol, M)) + else: + print("%-35s volume = %5.2Fm3 mass = %5.2F t" % (vln, cvol, M / 1000.0)) if fm: - fi = fm.GetDetectorField() - if hasattr(fi,'GetConstantFieldValue'): - print(' Magnetic field:',fi.GetConstantFieldValue()/G4Unit.tesla) - else: - serv = ROOT.TG4GeometryServices.Instance() - pos = array('d',[0,0,0]) - bf = array('d',[0,0,0]) - name = ROOT.G4String(lvl.GetName().c_str()) - print ('debug',name,lvl.GetName(),lvl) - serv.GetField(name,pos,bf) - print(' Magnetic field Bx,By,Bz: %4.2F %4.2F %4.2F'%(bf[0]/G4Unit.tesla,bf[1]/G4Unit.tesla,bf[2]/G4Unit.tesla)) - #if vl.GetName().c_str()[0:3]=='Mag': magnetMass = M # only count volumes starting with Mag + fi = fm.GetDetectorField() + if hasattr(fi, "GetConstantFieldValue"): + print(" Magnetic field:", fi.GetConstantFieldValue() / G4Unit.tesla) + else: + serv = ROOT.TG4GeometryServices.Instance() + pos = array("d", [0, 0, 0]) + bf = array("d", [0, 0, 0]) + name = ROOT.G4String(lvl.GetName().c_str()) + print("debug", name, lvl.GetName(), lvl) + serv.GetField(name, pos, bf) + print( + " Magnetic field Bx,By,Bz: %4.2F %4.2F %4.2F" + % (bf[0] / G4Unit.tesla, bf[1] / G4Unit.tesla, bf[2] / G4Unit.tesla) + ) + # if vl.GetName().c_str()[0:3]=='Mag': magnetMass = M # only count volumes starting with Mag name = vl.GetName().c_str() - if "_" in name and "Mag" in name.split('_')[1]: magnetMass = M # only count volumes starting with Mag + if "_" in name and "Mag" in name.split("_")[1]: + magnetMass = M # only count volumes starting with Mag return magnetMass -def nextLevel(lv,magnetMass,onlyWithField,exclude,alreadyPrinted): + + +def nextLevel(lv, magnetMass, onlyWithField, exclude, alreadyPrinted): tmp = 0 for da in range(lv.GetNoDaughters()): - lvn = lv.GetDaughter(da) - name = lvn.GetName().c_str() - if name in exclude: continue - lvln = lvn.GetLogicalVolume() - if lvln.GetNoDaughters()>0: - xtmp,dummy = nextLevel(lvln,magnetMass,onlyWithField,exclude,alreadyPrinted) - magnetMass+=xtmp - else: - tmp+=printWF(lvn,alreadyPrinted,onlyWithField) - return tmp,magnetMass -def printWeightsandFields(onlyWithField = True,exclude=[]): - if len(exclude)!=0: - print("will not search in ",exclude) - gt = ROOT.G4TransportationManager.GetTransportationManager() - gn = gt.GetNavigatorForTracking() - world = gn.GetWorldVolume().GetLogicalVolume() - magnetMass = 0 - alreadyPrinted = {} - dummy,nM = nextLevel(world,magnetMass,onlyWithField,exclude,alreadyPrinted) - print('total magnet mass',nM/1000.,'t') - return - -def addVMCFields(shipGeo, controlFile = '', verbose = False, withVirtualMC = True): - ''' + lvn = lv.GetDaughter(da) + name = lvn.GetName().c_str() + if name in exclude: + continue + lvln = lvn.GetLogicalVolume() + if lvln.GetNoDaughters() > 0: + xtmp, dummy = nextLevel( + lvln, magnetMass, onlyWithField, exclude, alreadyPrinted + ) + magnetMass += xtmp + else: + tmp += printWF(lvn, alreadyPrinted, onlyWithField) + return tmp, magnetMass + + +def printWeightsandFields(onlyWithField=True, exclude=[]): + if len(exclude) != 0: + print("will not search in ", exclude) + gt = ROOT.G4TransportationManager.GetTransportationManager() + gn = gt.GetNavigatorForTracking() + world = gn.GetWorldVolume().GetLogicalVolume() + magnetMass = 0 + alreadyPrinted = {} + dummy, nM = nextLevel(world, magnetMass, onlyWithField, exclude, alreadyPrinted) + print("total magnet mass", nM / 1000.0, "t") + return + + +def addVMCFields(shipGeo, controlFile="", verbose=False, withVirtualMC=True): + """ Define VMC B fields, e.g. global field, field maps, local or local+global fields - ''' - print('Calling addVMCFields') + """ + print("Calling addVMCFields") fieldMaker = ROOT.ShipFieldMaker(verbose) # Read the input control file. If this is empty then the only fields that are # defined (so far) are those within the C++ geometry classes - if controlFile != '': - fieldMaker.readInputFile(controlFile) + if controlFile != "": + fieldMaker.readInputFile(controlFile) # Set the main spectrometer field map as a global field - if hasattr(shipGeo, 'Bfield'): - fieldsList = [] - fieldMaker.defineFieldMap('MainSpecMap', 'files/MainSpectrometerField.root', - ROOT.TVector3(0.0, 0.0, shipGeo.Bfield.z)) - fieldsList.append('MainSpecMap') - - if shipGeo.EmuMagnet.MagneticField: - withConstFieldNuTauDet = False - if hasattr(shipGeo.EmuMagnet,'WithConstField'): withConstFieldNuTauDet = shipGeo.EmuMagnet.WithConstField - if not withConstFieldNuTauDet: - fieldMaker.defineFieldMap('NuMap','files/nuTauDetField.root', ROOT.TVector3(0.0,0.0,shipGeo.EmuMagnet.zC)) - fieldsList.append('NuMap') - - if not shipGeo.hadronAbsorber.WithConstField: - fieldMaker.defineFieldMap('HadronAbsorberMap','files/FieldHadronStopper_raised_20190411.root', ROOT.TVector3(0.0,0.0,shipGeo.hadronAbsorber.z)) - fieldsList.append('HadronAbsorberMap') - - if not shipGeo.muShield.WithConstField: - field_center, _ = ShieldUtils.find_shield_center(shipGeo) - fieldMaker.defineFieldMap('muonShieldField', 'files/MuonShieldField.root', - ROOT.TVector3(0.0, 0.0, field_center), ROOT.TVector3(0.0, 0.0, 0.0), True) - fieldsList.append('muonShieldField') - # Combine the fields to obtain the global field - if len(fieldsList) > 1: - fieldMaker.defineComposite('TotalField', *fieldsList) #fieldsList MUST have length <=4 - fieldMaker.defineGlobalField('TotalField') - else: - fieldMaker.defineGlobalField('MainSpecMap') + if hasattr(shipGeo, "Bfield"): + fieldsList = [] + fieldMaker.defineFieldMap( + "MainSpecMap", + "files/MainSpectrometerField.root", + ROOT.TVector3(0.0, 0.0, shipGeo.Bfield.z), + ) + fieldsList.append("MainSpecMap") + + if shipGeo.EmuMagnet.MagneticField: + withConstFieldNuTauDet = False + if hasattr(shipGeo.EmuMagnet, "WithConstField"): + withConstFieldNuTauDet = shipGeo.EmuMagnet.WithConstField + if not withConstFieldNuTauDet: + fieldMaker.defineFieldMap( + "NuMap", + "files/nuTauDetField.root", + ROOT.TVector3(0.0, 0.0, shipGeo.EmuMagnet.zC), + ) + fieldsList.append("NuMap") + + if not shipGeo.hadronAbsorber.WithConstField: + fieldMaker.defineFieldMap( + "HadronAbsorberMap", + "files/FieldHadronStopper_raised_20190411.root", + ROOT.TVector3(0.0, 0.0, shipGeo.hadronAbsorber.z), + ) + fieldsList.append("HadronAbsorberMap") + + if not shipGeo.muShield.WithConstField: + field_center, _ = ShieldUtils.find_shield_center(shipGeo) + fieldMaker.defineFieldMap( + "muonShieldField", + "files/MuonShieldField.root", + ROOT.TVector3(0.0, 0.0, field_center), + ROOT.TVector3(0.0, 0.0, 0.0), + True, + ) + fieldsList.append("muonShieldField") + # Combine the fields to obtain the global field + if len(fieldsList) > 1: + fieldMaker.defineComposite( + "TotalField", *fieldsList + ) # fieldsList MUST have length <=4 + fieldMaker.defineGlobalField("TotalField") + else: + fieldMaker.defineGlobalField("MainSpecMap") if withVirtualMC: - # Force the VMC to update/reset the fields defined by the fieldMaker object. - # Get the ROOT/Geant4 geometry manager - geom = ROOT.TG4GeometryManager.Instance() - # Let the geometry know about the fieldMaker object - geom.SetUserPostDetConstruction(fieldMaker) - # Update the fields via the overriden ShipFieldMaker::Contruct() function - geom.ConstructSDandField() + # Force the VMC to update/reset the fields defined by the fieldMaker object. + # Get the ROOT/Geant4 geometry manager + geom = ROOT.TG4GeometryManager.Instance() + # Let the geometry know about the fieldMaker object + geom.SetUserPostDetConstruction(fieldMaker) + # Update the fields via the overriden ShipFieldMaker::Contruct() function + geom.ConstructSDandField() # Return the fieldMaker object, otherwise it will "go out of scope" and its # content will be deleted @@ -189,59 +241,66 @@ def addVMCFields(shipGeo, controlFile = '', verbose = False, withVirtualMC = Tru def printVMCFields(): - ''' + """ Method to print out information about VMC fields - ''' - print('Printing VMC fields and associated volumes') + """ + print("Printing VMC fields and associated volumes") fGeo = ROOT.gGeoManager vols = fGeo.GetListOfVolumes() for v in vols: - - field = v.GetField() + field = v.GetField() if field: - print('Vol is {0}, field is {1}'.format(v.GetName(), field)) + print("Vol is {0}, field is {1}".format(v.GetName(), field)) else: - print('Vol is {0}'.format(v.GetName())) + print("Vol is {0}".format(v.GetName())) if field: # Get the field value assuming the global co-ordinate origin. # This needs to be modified to use the local volume centre - centre = array('d',[0.0, 0.0, 0.0]) - B = array('d',[0.0, 0.0, 0.0]) + centre = array("d", [0.0, 0.0, 0.0]) + B = array("d", [0.0, 0.0, 0.0]) field.Field(centre, B) - print('Volume {0} has B = ({1}, {2}, {3}) T'.format(v.GetName(), B[0]/u.tesla, - B[1]/u.tesla, B[2]/u.tesla)) + print( + "Volume {0} has B = ({1}, {2}, {3}) T".format( + v.GetName(), B[0] / u.tesla, B[1] / u.tesla, B[2] / u.tesla + ) + ) + def getRunManager(): - return G4RunManager.GetRunManager() + return G4RunManager.GetRunManager() + + def startUI(): - session = ROOT.G4UIterminal() - session.SessionStart() + session = ROOT.G4UIterminal() + session.SessionStart() + + def debug(): - gt = ROOT.G4TransportationManager.GetTransportationManager() - gn = gt.GetNavigatorForTracking() - world = gn.GetWorldVolume().GetLogicalVolume() - vmap = {} - for da in range(world.GetNoDaughters()): - vl = world.GetDaughter(da) - vmap[vl.GetName().c_str()] = vl - print(da, vl.GetName()) - lvl = vmap['MagB'].GetLogicalVolume() - print(lvl.GetMass()/G4Unit.kg,lvl.GetMaterial().GetName()) - print(lvl.GetFieldManager()) -# - for da in range(world.GetNoDaughters()): - vl = world.GetDaughter(da) - vln = vl.GetName().c_str() - lvl = vl.GetLogicalVolume() - fm = lvl.GetFieldManager() - if fm : - v = fm.GetDetectorField().GetConstantFieldValue() - print(vln,fm,v.getX(),v.getY()) -# FairROOT view - fgeom = ROOT.gGeoManager - magB = fgeom.GetVolume('MagB') - fl = magB.GetField() - print(fl.GetFieldValue()[0],fl.GetFieldValue()[1],fl.GetFieldValue()[2]) + gt = ROOT.G4TransportationManager.GetTransportationManager() + gn = gt.GetNavigatorForTracking() + world = gn.GetWorldVolume().GetLogicalVolume() + vmap = {} + for da in range(world.GetNoDaughters()): + vl = world.GetDaughter(da) + vmap[vl.GetName().c_str()] = vl + print(da, vl.GetName()) + lvl = vmap["MagB"].GetLogicalVolume() + print(lvl.GetMass() / G4Unit.kg, lvl.GetMaterial().GetName()) + print(lvl.GetFieldManager()) + # + for da in range(world.GetNoDaughters()): + vl = world.GetDaughter(da) + vln = vl.GetName().c_str() + lvl = vl.GetLogicalVolume() + fm = lvl.GetFieldManager() + if fm: + v = fm.GetDetectorField().GetConstantFieldValue() + print(vln, fm, v.getX(), v.getY()) + # FairROOT view + fgeom = ROOT.gGeoManager + magB = fgeom.GetVolume("MagB") + fl = magB.GetField() + print(fl.GetFieldValue()[0], fl.GetFieldValue()[1], fl.GetFieldValue()[2]) diff --git a/python/goliath2root.py b/python/goliath2root.py index 90b1aaa1de..168d4a9c11 100644 --- a/python/goliath2root.py +++ b/python/goliath2root.py @@ -3,38 +3,42 @@ # EvH 11/4/2018 -import ROOT,os,sys +import os +import sys + +import ROOT import rootUtils as ut -import shipunit as u import shipRoot_conf +import shipunit as u -h={} +h = {} # new limits x: -1118.6, 1241.4 (59); y: -411.40, 768.60 (20); z: -2512.7, 2537.3 (101) # -ut.bookHist(h,'Bx','Bx',60,-113.86,126.14,21,-44.09,79.81,102,-253.77,256.27) -ut.bookHist(h,'By','By',60,-113.86,126.14,21,-44.09,79.81,102,-253.77,256.27) -ut.bookHist(h,'Bz','Bz',60,-113.86,126.14,21,-44.09,79.81,102,-253.77,256.27) -ut.bookHist(h,'Byvsz','By vs z for x=1.4,y=1.6',102,-253.77,256.27) -f=open('ExtGoliathFieldMap.txt','r') +ut.bookHist(h, "Bx", "Bx", 60, -113.86, 126.14, 21, -44.09, 79.81, 102, -253.77, 256.27) +ut.bookHist(h, "By", "By", 60, -113.86, 126.14, 21, -44.09, 79.81, 102, -253.77, 256.27) +ut.bookHist(h, "Bz", "Bz", 60, -113.86, 126.14, 21, -44.09, 79.81, 102, -253.77, 256.27) +ut.bookHist(h, "Byvsz", "By vs z for x=1.4,y=1.6", 102, -253.77, 256.27) +f = open("ExtGoliathFieldMap.txt", "r") -i=0 +i = 0 for line in f: - i+=1 - if i<6: continue - x,y,z,Bx,By,Bz = line.split() - x=float(x)/10. - y=float(y)/10. - z=float(z)/10. - Bx = Bx - By = By - Bz = Bz - - rc=h['Bx'].Fill(float(x),float(y),float(z),float(Bx)) - rc=h['By'].Fill(float(x),float(y),float(z),float(By)) - rc=h['Bz'].Fill(float(x),float(y),float(z),float(Bz)) - - if (round(x,2)==0.14) and (round(y,2)==0.16): - rc=h['Byvsz'].Fill(float(z),float(By)) - -ut.writeHists(h,"GoliathFieldMap.root") + i += 1 + if i < 6: + continue + x, y, z, Bx, By, Bz = line.split() + x = float(x) / 10.0 + y = float(y) / 10.0 + z = float(z) / 10.0 + Bx = Bx + By = By + Bz = Bz + + rc = h["Bx"].Fill(float(x), float(y), float(z), float(Bx)) + rc = h["By"].Fill(float(x), float(y), float(z), float(By)) + rc = h["Bz"].Fill(float(x), float(y), float(z), float(Bz)) + + if (round(x, 2) == 0.14) and (round(y, 2) == 0.16): + rc = h["Byvsz"].Fill(float(z), float(By)) + +ut.writeHists(h, "GoliathFieldMap.root") diff --git a/python/hepunit.py b/python/hepunit.py index f59477da56..9c160d61f9 100644 --- a/python/hepunit.py +++ b/python/hepunit.py @@ -8,55 +8,54 @@ # Q, 2005 # ================================================================== """ -#$Id: hepunit.py 66892 2013-01-17 10:57:59Z gunter $ - +# $Id: hepunit.py 66892 2013-01-17 10:57:59Z gunter $ # ================================================================== # imported from "SystemOfUnits.h" # ================================================================== -millimeter = 1. -millimeter2 = millimeter*millimeter -millimeter3 = millimeter*millimeter*millimeter +millimeter = 1.0 +millimeter2 = millimeter * millimeter +millimeter3 = millimeter * millimeter * millimeter -centimeter = 10.*millimeter -centimeter2 = centimeter*centimeter -centimeter3 = centimeter*centimeter*centimeter +centimeter = 10.0 * millimeter +centimeter2 = centimeter * centimeter +centimeter3 = centimeter * centimeter * centimeter -meter = 1000.*millimeter -meter2 = meter*meter -meter3 = meter*meter*meter +meter = 1000.0 * millimeter +meter2 = meter * meter +meter3 = meter * meter * meter -kilometer = 1000.*meter -kilometer2 = kilometer*kilometer -kilometer3 = kilometer*kilometer*kilometer +kilometer = 1000.0 * meter +kilometer2 = kilometer * kilometer +kilometer3 = kilometer * kilometer * kilometer -parsec = 3.0856775807e+16*meter +parsec = 3.0856775807e16 * meter -micrometer = 1.e-6 *meter -nanometer = 1.e-9 *meter -angstrom = 1.e-10*meter -fermi = 1.e-15*meter +micrometer = 1.0e-6 * meter +nanometer = 1.0e-9 * meter +angstrom = 1.0e-10 * meter +fermi = 1.0e-15 * meter -barn = 1.e-28*meter2 -millibarn = 1.e-3 *barn -microbarn = 1.e-6 *barn -nanobarn = 1.e-9 *barn -picobarn = 1.e-12*barn +barn = 1.0e-28 * meter2 +millibarn = 1.0e-3 * barn +microbarn = 1.0e-6 * barn +nanobarn = 1.0e-9 * barn +picobarn = 1.0e-12 * barn # symbols -mm = millimeter +mm = millimeter mm2 = millimeter2 mm3 = millimeter3 -cm = centimeter +cm = centimeter cm2 = centimeter2 cm3 = centimeter3 -m = meter +m = meter m2 = meter2 m3 = meter3 -km = kilometer +km = kilometer km2 = kilometer2 km3 = kilometer3 @@ -65,30 +64,30 @@ # # Angle # -radian = 1. -milliradian = 1.e-3*radian -degree = (3.14159265358979323846/180.0)*radian +radian = 1.0 +milliradian = 1.0e-3 * radian +degree = (3.14159265358979323846 / 180.0) * radian -steradian = 1. +steradian = 1.0 # symbols -rad = radian +rad = radian mrad = milliradian -sr = steradian -deg = degree +sr = steradian +deg = degree # # Time [T] # -nanosecond = 1. -second = 1.e+9 *nanosecond -millisecond = 1.e-3 *second -microsecond = 1.e-6 *second -picosecond = 1.e-12*second +nanosecond = 1.0 +second = 1.0e9 * nanosecond +millisecond = 1.0e-3 * second +microsecond = 1.0e-6 * second +picosecond = 1.0e-12 * second -hertz = 1./second -kilohertz = 1.e+3*hertz -megahertz = 1.e+6*hertz +hertz = 1.0 / second +kilohertz = 1.0e3 * hertz +megahertz = 1.0e6 * hertz # symbols ns = nanosecond @@ -98,25 +97,25 @@ # # Electric charge [Q] # -eplus = 1. # positron charge -e_SI = 1.60217733e-19 # positron charge in coulomb -coulomb = eplus/e_SI # coulomb = 6.24150 e+18 * eplus +eplus = 1.0 # positron charge +e_SI = 1.60217733e-19 # positron charge in coulomb +coulomb = eplus / e_SI # coulomb = 6.24150 e+18 * eplus # # Energy [E] # -megaelectronvolt = 1. -electronvolt = 1.e-6*megaelectronvolt -kiloelectronvolt = 1.e-3*megaelectronvolt -gigaelectronvolt = 1.e+3*megaelectronvolt -teraelectronvolt = 1.e+6*megaelectronvolt -petaelectronvolt = 1.e+9*megaelectronvolt +megaelectronvolt = 1.0 +electronvolt = 1.0e-6 * megaelectronvolt +kiloelectronvolt = 1.0e-3 * megaelectronvolt +gigaelectronvolt = 1.0e3 * megaelectronvolt +teraelectronvolt = 1.0e6 * megaelectronvolt +petaelectronvolt = 1.0e9 * megaelectronvolt -joule = electronvolt/e_SI # joule = 6.24150 e+12 * MeV +joule = electronvolt / e_SI # joule = 6.24150 e+12 * MeV # symbols MeV = megaelectronvolt -eV = electronvolt +eV = electronvolt keV = kiloelectronvolt GeV = gigaelectronvolt TeV = teraelectronvolt @@ -125,149 +124,149 @@ # # Mass [E][T^2][L^-2] # -kilogram = joule*second*second/(meter*meter) -gram = 1.e-3*kilogram -milligram = 1.e-3*gram +kilogram = joule * second * second / (meter * meter) +gram = 1.0e-3 * kilogram +milligram = 1.0e-3 * gram # symbols kg = kilogram -g = gram +g = gram mg = milligram # # Power [E][T^-1] # -watt = joule/second # watt = 6.24150 e+3 * MeV/ns +watt = joule / second # watt = 6.24150 e+3 * MeV/ns # # Force [E][L^-1] # -newton = joule/meter # newton = 6.24150 e+9 * MeV/mm +newton = joule / meter # newton = 6.24150 e+9 * MeV/mm # # Pressure [E][L^-3] # -pascal = newton/m2 # pascal = 6.24150 e+3 * MeV/mm3 -bar = 100000*pascal # bar = 6.24150 e+8 * MeV/mm3 -atmosphere = 101325*pascal # atm = 6.32420 e+8 * MeV/mm3 +pascal = newton / m2 # pascal = 6.24150 e+3 * MeV/mm3 +bar = 100000 * pascal # bar = 6.24150 e+8 * MeV/mm3 +atmosphere = 101325 * pascal # atm = 6.32420 e+8 * MeV/mm3 # # Electric current [Q][T^-1] # -ampere = coulomb/second # ampere = 6.24150 e+9 * eplus/ns -milliampere = 1.e-3*ampere -microampere = 1.e-6*ampere -nanoampere = 1.e-9*ampere +ampere = coulomb / second # ampere = 6.24150 e+9 * eplus/ns +milliampere = 1.0e-3 * ampere +microampere = 1.0e-6 * ampere +nanoampere = 1.0e-9 * ampere # # Electric potential [E][Q^-1] # -megavolt = megaelectronvolt/eplus -kilovolt = 1.e-3*megavolt -volt = 1.e-6*megavolt +megavolt = megaelectronvolt / eplus +kilovolt = 1.0e-3 * megavolt +volt = 1.0e-6 * megavolt # # Electric resistance [E][T][Q^-2] # -ohm = volt/ampere # ohm = 1.60217e-16*(MeV/eplus)/(eplus/ns) +ohm = volt / ampere # ohm = 1.60217e-16*(MeV/eplus)/(eplus/ns) # # Electric capacitance [Q^2][E^-1] # -farad = coulomb/volt # farad = 6.24150e+24 * eplus/Megavolt -millifarad = 1.e-3*farad -microfarad = 1.e-6*farad -nanofarad = 1.e-9*farad -picofarad = 1.e-12*farad +farad = coulomb / volt # farad = 6.24150e+24 * eplus/Megavolt +millifarad = 1.0e-3 * farad +microfarad = 1.0e-6 * farad +nanofarad = 1.0e-9 * farad +picofarad = 1.0e-12 * farad # # Magnetic Flux [T][E][Q^-1] # -weber = volt*second # weber = 1000*megavolt*ns +weber = volt * second # weber = 1000*megavolt*ns # # Magnetic Field [T][E][Q^-1][L^-2] # -tesla = volt*second/meter2 # tesla =0.001*megavolt*ns/mm2 +tesla = volt * second / meter2 # tesla =0.001*megavolt*ns/mm2 -gauss = 1.e-4*tesla -kilogauss = 1.e-1*tesla +gauss = 1.0e-4 * tesla +kilogauss = 1.0e-1 * tesla # # Inductance [T^2][E][Q^-2] # -henry = weber/ampere # henry = 1.60217e-7*MeV*(ns/eplus)**2 +henry = weber / ampere # henry = 1.60217e-7*MeV*(ns/eplus)**2 # # Temperature # -kelvin = 1. +kelvin = 1.0 # # Amount of substance # -mole = 1. +mole = 1.0 # # Activity [T^-1] # -becquerel = 1./second -curie = 3.7e+10 * becquerel +becquerel = 1.0 / second +curie = 3.7e10 * becquerel # # Absorbed dose [L^2][T^-2] # -gray = joule/kilogram +gray = joule / kilogram # # Luminous intensity [I] # -candela = 1. +candela = 1.0 # # Luminous flux [I] # -lumen = candela*steradian +lumen = candela * steradian # # Illuminance [I][L^-2] # -lux = lumen/meter2 +lux = lumen / meter2 # # Miscellaneous # -perCent = 0.01 +perCent = 0.01 perThousand = 0.001 -perMillion = 0.000001 +perMillion = 0.000001 # ================================================================== # imported from "PhysicalConstants.h" # ================================================================== -pi = 3.14159265358979323846 -twopi = 2.*pi -halfpi = pi/2. -pi2 = pi*pi +pi = 3.14159265358979323846 +twopi = 2.0 * pi +halfpi = pi / 2.0 +pi2 = pi * pi # -Avogadro = 6.0221367e+23/mole +Avogadro = 6.0221367e23 / mole # c = 299.792458 mm/ns # c^2 = 898.7404 (mm/ns)^2 -c_light = 2.99792458e+8 * m/s +c_light = 2.99792458e8 * m / s c_squared = c_light * c_light # h = 4.13566e-12 MeV*ns # hbar = 6.58212e-13 MeV*ns # hbarc = 197.32705e-12 MeV*mm -h_Planck = 6.6260755e-34 * joule*s -hbar_Planck = h_Planck/twopi -hbarc = hbar_Planck * c_light +h_Planck = 6.6260755e-34 * joule * s +hbar_Planck = h_Planck / twopi +hbarc = hbar_Planck * c_light hbarc_squared = hbarc * hbarc # -electron_charge = - eplus # see SystemOfUnits.h +electron_charge = -eplus # see SystemOfUnits.h e_squared = eplus * eplus # amu_c2 - atomic equivalent mass unit @@ -276,33 +275,32 @@ proton_mass_c2 = 938.27231 * MeV neutron_mass_c2 = 939.56563 * MeV amu_c2 = 931.49432 * MeV -amu = amu_c2/c_squared +amu = amu_c2 / c_squared # permeability of free space mu0 = 2.01334e-16 Mev*(ns*eplus)^2/mm # permittivity of free space epsil0 = 5.52636e+10 eplus^2/(MeV*mm) -mu0 = 4*pi*1.e-7 * henry/m -epsilon0 = 1./(c_squared*mu0) +mu0 = 4 * pi * 1.0e-7 * henry / m +epsilon0 = 1.0 / (c_squared * mu0) # electromagnetic coupling = 1.43996e-12 MeV*mm/(eplus^2) -elm_coupling = e_squared/(4*pi*epsilon0) -fine_structure_const = elm_coupling/hbarc -classic_electr_radius = elm_coupling/electron_mass_c2 -electron_Compton_length = hbarc/electron_mass_c2 -Bohr_radius = electron_Compton_length/fine_structure_const +elm_coupling = e_squared / (4 * pi * epsilon0) +fine_structure_const = elm_coupling / hbarc +classic_electr_radius = elm_coupling / electron_mass_c2 +electron_Compton_length = hbarc / electron_mass_c2 +Bohr_radius = electron_Compton_length / fine_structure_const -alpha_rcl2 = fine_structure_const * classic_electr_radius \ - * classic_electr_radius -twopi_mc2_rcl2 = twopi * electron_mass_c2 \ - * classic_electr_radius \ - * classic_electr_radius +alpha_rcl2 = fine_structure_const * classic_electr_radius * classic_electr_radius +twopi_mc2_rcl2 = ( + twopi * electron_mass_c2 * classic_electr_radius * classic_electr_radius +) # -k_Boltzmann = 8.617385e-11 * MeV/kelvin +k_Boltzmann = 8.617385e-11 * MeV / kelvin # -STP_Temperature = 273.15*kelvin -STP_Pressure = 1.*atmosphere -kGasThreshold = 10.*mg/cm3 +STP_Temperature = 273.15 * kelvin +STP_Pressure = 1.0 * atmosphere +kGasThreshold = 10.0 * mg / cm3 # -universe_mean_density = 1.e-25*g/cm3 +universe_mean_density = 1.0e-25 * g / cm3 diff --git a/python/hnl.py b/python/hnl.py index 62d7af0088..e23ddc4dad 100644 --- a/python/hnl.py +++ b/python/hnl.py @@ -26,22 +26,28 @@ # # ================================================================== """ + import math -import ROOT, os +import os + +import ROOT import shipunit as u # Load PDG database pdg = ROOT.TDatabasePDG.Instance() + def PDGname(particle): """ Change particle name for use with the PDG database """ - if '1' in particle: - particle = particle.replace('1',"'") - if particle == 'nu': return 'nu_e' # simple workaround to handle 3nu channel + if "1" in particle: + particle = particle.replace("1", "'") + if particle == "nu": + return "nu_e" # simple workaround to handle 3nu channel return particle + def mass(particle): """ Read particle mass from PDG database @@ -50,6 +56,7 @@ def mass(particle): tPart = pdg.GetParticle(particle) return tPart.Mass() + def lifetime(particle): """ Read particle lifetime from PDG database @@ -58,10 +65,12 @@ def lifetime(particle): tPart = pdg.GetParticle(particle) return tPart.Lifetime() -class CKMmatrix(): + +class CKMmatrix: """ CKM matrix, from http://pdg.lbl.gov/2017/reviews/rpp2016-rev-ckm-matrix.pdf """ + def __init__(self): self.Vud = 0.9743 self.Vus = 0.2251 @@ -73,34 +82,41 @@ def __init__(self): self.Vts = 4.0e-02 self.Vtb = 0.999 -class constants(): + +class constants: """ Store some constants useful for HNL physics """ + def __init__(self): - self.decayConstant = {'pi+':0.130*u.GeV, - 'pi0':0.130*u.GeV, - 'eta':1.2*0.130*u.GeV, - 'eta1':0.152*u.GeV, - 'eta_c':0.335*u.GeV, - 'rho+':0.209*u.GeV, - 'rho0':0.209*u.GeV, - 'omega':0.195*u.GeV, - 'phi':0.229*u.GeV, - 'D_s+':0.249*u.GeV, - 'D*_s+':0.315*u.GeV} # decay constants f_h of pseudoscalar and vector mesons - self.GF = 1.166379e-05/(u.GeV*u.GeV) # Fermi's constant (GeV^-2) - self.s2thetaw = 0.23126 # square sine of the Weinberg angle - self.heV = 6.58211928*pow(10.,-16) # no units or it messes up!! - self.hGeV = self.heV * pow(10.,-9) # no units or it messes up!! + self.decayConstant = { + "pi+": 0.130 * u.GeV, + "pi0": 0.130 * u.GeV, + "eta": 1.2 * 0.130 * u.GeV, + "eta1": 0.152 * u.GeV, + "eta_c": 0.335 * u.GeV, + "rho+": 0.209 * u.GeV, + "rho0": 0.209 * u.GeV, + "omega": 0.195 * u.GeV, + "phi": 0.229 * u.GeV, + "D_s+": 0.249 * u.GeV, + "D*_s+": 0.315 * u.GeV, + } # decay constants f_h of pseudoscalar and vector mesons + self.GF = 1.166379e-05 / (u.GeV * u.GeV) # Fermi's constant (GeV^-2) + self.s2thetaw = 0.23126 # square sine of the Weinberg angle + self.heV = 6.58211928 * pow(10.0, -16) # no units or it messes up!! + self.hGeV = self.heV * pow(10.0, -9) # no units or it messes up!! + # Load some useful constants c = constants() -class HNLbranchings(): + +class HNLbranchings: """ Lifetime and total and partial decay widths of an HNL """ + def __init__(self, mass, couplings, debug=False): """ Initialize with mass and couplings of the HNL @@ -111,78 +127,88 @@ def __init__(self, mass, couplings, debug=False): """ self.U2 = couplings self.U = [math.sqrt(ui) for ui in self.U2] - self.MN = mass*u.GeV + self.MN = mass * u.GeV self.CKM = CKMmatrix() - self.CKMelemSq = {'pi+':self.CKM.Vud**2., - 'rho+':self.CKM.Vud**2., - 'D_s+':self.CKM.Vcs**2., - 'D*_s+':self.CKM.Vcs**2., - 'K+':self.CKM.Vus**2., - # Quarks (up,down) - # up: 1=u, 2=c, 3=t - # down: 1=d, 2=s, 3=b - (1,1):self.CKM.Vud**2., (1,2):self.CKM.Vus**2., (1,3):self.CKM.Vub**2., - (2,1):self.CKM.Vcd**2., (2,2):self.CKM.Vcs**2., (2,3):self.CKM.Vcb**2., - (3,1):self.CKM.Vtd**2., (3,2):self.CKM.Vts**2., (3,3):self.CKM.Vtb**2.} - self.decays = [ 'N -> nu nu nu', - 'N -> e- e+ nu_e', - 'N -> e- e+ nu_mu', - 'N -> e- e+ nu_tau', - 'N -> e- mu+ nu_mu', - 'N -> mu- e+ nu_e', - 'N -> pi0 nu_e', - 'N -> pi0 nu_mu', - 'N -> pi0 nu_tau', - 'N -> pi+ e-', - 'N -> mu- mu+ nu_e', - 'N -> mu- mu+ nu_mu', - 'N -> mu- mu+ nu_tau', - 'N -> pi+ mu-', - 'N -> eta nu_e', - 'N -> eta nu_mu', - 'N -> eta nu_tau', - 'N -> rho0 nu_e', - 'N -> rho0 nu_mu', - 'N -> rho0 nu_tau', - 'N -> rho+ e-', - 'N -> omega nu_e', - 'N -> omega nu_mu', - 'N -> omega nu_tau', - 'N -> rho+ mu-', - 'N -> eta1 nu_e', - 'N -> eta1 nu_mu', - 'N -> eta1 nu_tau', - 'N -> phi nu_e', - 'N -> phi nu_mu', - 'N -> phi nu_tau', - 'N -> e- tau+ nu_tau', - 'N -> tau- e+ nu_e', - 'N -> mu- tau+ nu_tau', - 'N -> tau- mu+ nu_mu', - 'N -> D_s+ e-', - 'N -> D_s+ mu-', - 'N -> D*_s+ e-', - 'N -> D*_s+ mu-', - 'N -> eta_c nu_e', - 'N -> eta_c nu_mu', - 'N -> eta_c nu_tau' ] - if self.MN>=1.: + self.CKMelemSq = { + "pi+": self.CKM.Vud**2.0, + "rho+": self.CKM.Vud**2.0, + "D_s+": self.CKM.Vcs**2.0, + "D*_s+": self.CKM.Vcs**2.0, + "K+": self.CKM.Vus**2.0, + # Quarks (up,down) + # up: 1=u, 2=c, 3=t + # down: 1=d, 2=s, 3=b + (1, 1): self.CKM.Vud**2.0, + (1, 2): self.CKM.Vus**2.0, + (1, 3): self.CKM.Vub**2.0, + (2, 1): self.CKM.Vcd**2.0, + (2, 2): self.CKM.Vcs**2.0, + (2, 3): self.CKM.Vcb**2.0, + (3, 1): self.CKM.Vtd**2.0, + (3, 2): self.CKM.Vts**2.0, + (3, 3): self.CKM.Vtb**2.0, + } + self.decays = [ + "N -> nu nu nu", + "N -> e- e+ nu_e", + "N -> e- e+ nu_mu", + "N -> e- e+ nu_tau", + "N -> e- mu+ nu_mu", + "N -> mu- e+ nu_e", + "N -> pi0 nu_e", + "N -> pi0 nu_mu", + "N -> pi0 nu_tau", + "N -> pi+ e-", + "N -> mu- mu+ nu_e", + "N -> mu- mu+ nu_mu", + "N -> mu- mu+ nu_tau", + "N -> pi+ mu-", + "N -> eta nu_e", + "N -> eta nu_mu", + "N -> eta nu_tau", + "N -> rho0 nu_e", + "N -> rho0 nu_mu", + "N -> rho0 nu_tau", + "N -> rho+ e-", + "N -> omega nu_e", + "N -> omega nu_mu", + "N -> omega nu_tau", + "N -> rho+ mu-", + "N -> eta1 nu_e", + "N -> eta1 nu_mu", + "N -> eta1 nu_tau", + "N -> phi nu_e", + "N -> phi nu_mu", + "N -> phi nu_tau", + "N -> e- tau+ nu_tau", + "N -> tau- e+ nu_e", + "N -> mu- tau+ nu_tau", + "N -> tau- mu+ nu_mu", + "N -> D_s+ e-", + "N -> D_s+ mu-", + "N -> D*_s+ e-", + "N -> D*_s+ mu-", + "N -> eta_c nu_e", + "N -> eta_c nu_mu", + "N -> eta_c nu_tau", + ] + if self.MN >= 1.0: self.QCD_corr = self.QCD_correction() if debug: print("HNLbranchings instance initialized with couplings:") - print("\tU2e = %s"%self.U2[0]) - print("\tU2mu = %s"%self.U2[1]) - print("\tU2tau = %s"%self.U2[2]) + print("\tU2e = %s" % self.U2[0]) + print("\tU2mu = %s" % self.U2[1]) + print("\tU2tau = %s" % self.U2[2]) print("and mass:") - print("\tm = %s GeV"%(self.MN)) + print("\tm = %s GeV" % (self.MN)) - def sqrt_lambda(self,a,b,c): + def sqrt_lambda(self, a, b, c): """ Useful function for decay kinematics. Returns 0 for kinematically forbidden region """ - l = a**2 + b**2 + c**2 - 2*a*b - 2*b*c - 2*a*c - if l<0: + l = a**2 + b**2 + c**2 - 2 * a * b - 2 * b * c - 2 * a * c + if l < 0: return 0 else: return math.sqrt(l) @@ -191,19 +217,19 @@ def QCD_correction(self): """ Returns 3-loops QCD correction to HNL decay width into quarks """ - alpha_s = ROOT.TGraph( os.path.expandvars('$FAIRSHIP/python/alpha_s.dat') ) + alpha_s = ROOT.TGraph(os.path.expandvars("$FAIRSHIP/python/alpha_s.dat")) a_s = alpha_s.Eval(self.MN) qcd_corr = a_s / math.pi - qcd_corr += 5.2 * (a_s / math.pi)**2. - qcd_corr += 26.4 * (a_s / math.pi)**3. + qcd_corr += 5.2 * (a_s / math.pi) ** 2.0 + qcd_corr += 26.4 * (a_s / math.pi) ** 3.0 return qcd_corr def Width_3nu(self): """ Returns the HNL decay width into three neutrinos """ - width = (c.GF**2.)*(self.MN**5.)*sum(self.U2)/(192.*(u.pi**3.)) - width = 2.*width # Majorana case (charge conjugate channels) + width = (c.GF**2.0) * (self.MN**5.0) * sum(self.U2) / (192.0 * (u.pi**3.0)) + width = 2.0 * width # Majorana case (charge conjugate channels) return width def Width_nu_f_fbar(self, alpha, beta): @@ -214,75 +240,101 @@ def Width_nu_f_fbar(self, alpha, beta): - alpha is a flavour of neutrino (1,2 or 3), determine the mixing angle U_alpha - beta is a flavour of the fermions: (1, 2 or 3) for charge leptons or (4, 5, 6, 7, 8, 9) for quarks """ - if (alpha not in [1,2,3]) or (beta not in [1,2,3,4,5,6,7,8,9]): - print('Width_nu_f_fbar ERROR: unknown channel alpha =',alpha,' beta =',beta) + if (alpha not in [1, 2, 3]) or (beta not in [1, 2, 3, 4, 5, 6, 7, 8, 9]): + print( + "Width_nu_f_fbar ERROR: unknown channel alpha =", alpha, " beta =", beta + ) quit() - l = [None,'e-','mu-','tau-','u','d','s','c','b','t'] + l = [None, "e-", "mu-", "tau-", "u", "d", "s", "c", "b", "t"] x = mass(l[beta]) / self.MN - if x > 0.5: # the decay is kinematically forbidden + if x > 0.5: # the decay is kinematically forbidden return 0 - width = (c.GF**2.)*(self.MN**5.)*self.U2[alpha-1]/(192.*(math.pi**3.)) - L = 0. - if x>0.01: - logContent = (1. - 3.*x**2. - (1.-x**2.)*math.sqrt(1. - 4.*x**2.) ) / ( (x**2.)*(1 + math.sqrt(1. - 4.*x**2.)) ) + width = ( + (c.GF**2.0) * (self.MN**5.0) * self.U2[alpha - 1] / (192.0 * (math.pi**3.0)) + ) + L = 0.0 + if x > 0.01: + logContent = ( + 1.0 - 3.0 * x**2.0 - (1.0 - x**2.0) * math.sqrt(1.0 - 4.0 * x**2.0) + ) / ((x**2.0) * (1 + math.sqrt(1.0 - 4.0 * x**2.0))) else: - logContent = x**4 + 4.*x**6 + 14.*x**8 + logContent = x**4 + 4.0 * x**6 + 14.0 * x**8 if logContent > 0: - L = math.log( logContent ) - if beta < 4: # lepton decay + L = math.log(logContent) + if beta < 4: # lepton decay NZ = 1 - if alpha == beta: # interference case - C1 = 0.25*(1. + 4.*c.s2thetaw + 8.*c.s2thetaw**2.) - C2 = 0.5*c.s2thetaw*(2.*c.s2thetaw +1.) - else: # no interference - C1 = 0.25*(1. - 4.*c.s2thetaw + 8.*c.s2thetaw**2.) - C2 = 0.5*c.s2thetaw*(2.*c.s2thetaw -1.) - else: # decay into quarks + if alpha == beta: # interference case + C1 = 0.25 * (1.0 + 4.0 * c.s2thetaw + 8.0 * c.s2thetaw**2.0) + C2 = 0.5 * c.s2thetaw * (2.0 * c.s2thetaw + 1.0) + else: # no interference + C1 = 0.25 * (1.0 - 4.0 * c.s2thetaw + 8.0 * c.s2thetaw**2.0) + C2 = 0.5 * c.s2thetaw * (2.0 * c.s2thetaw - 1.0) + else: # decay into quarks NZ = 3 - if (beta in [4,7,9]): # up quarks - C1 = 0.25*(1. - 8./3.*c.s2thetaw + 32./9.*c.s2thetaw**2.) - C2 = 1./3.*c.s2thetaw*(4./3.*c.s2thetaw - 1.) - if (beta in [5,6,8]): # down quarks - C1 = 0.25*(1. - 4./3.*c.s2thetaw + 8./9.*c.s2thetaw**2.) - C2 = 1./6.*c.s2thetaw*(2./3.*c.s2thetaw - 1.) - width = width*NZ*( C1*( (1.-14.*x**2. -2.*x**4. -12.*x**6.)*math.sqrt(1-4.*x**2) +12.*x**4. *(-1.+x**4.)*L ) - + 4.*C2*( x**2. *(2.+10.*x**2. -12.*x**4.) * math.sqrt(1.-4.*x**2) + 6.*x**4. *(1.-2.*x**2+2.*x**4)*L ) ) - width = 2.*width # Majorana case (charge conjugate channels) + if beta in [4, 7, 9]: # up quarks + C1 = 0.25 * ( + 1.0 - 8.0 / 3.0 * c.s2thetaw + 32.0 / 9.0 * c.s2thetaw**2.0 + ) + C2 = 1.0 / 3.0 * c.s2thetaw * (4.0 / 3.0 * c.s2thetaw - 1.0) + if beta in [5, 6, 8]: # down quarks + C1 = 0.25 * (1.0 - 4.0 / 3.0 * c.s2thetaw + 8.0 / 9.0 * c.s2thetaw**2.0) + C2 = 1.0 / 6.0 * c.s2thetaw * (2.0 / 3.0 * c.s2thetaw - 1.0) + width = ( + width + * NZ + * ( + C1 + * ( + (1.0 - 14.0 * x**2.0 - 2.0 * x**4.0 - 12.0 * x**6.0) + * math.sqrt(1 - 4.0 * x**2) + + 12.0 * x**4.0 * (-1.0 + x**4.0) * L + ) + + 4.0 + * C2 + * ( + x**2.0 + * (2.0 + 10.0 * x**2.0 - 12.0 * x**4.0) + * math.sqrt(1.0 - 4.0 * x**2) + + 6.0 * x**4.0 * (1.0 - 2.0 * x**2 + 2.0 * x**4) * L + ) + ) + ) + width = 2.0 * width # Majorana case (charge conjugate channels) return width - def Integrand(self,xx,xi): + def Integrand(self, xx, xi): """ Function to integrate needed for numerical integration using ROOT. Needed for 3-body decays trough W boson. First argument is a list of 1 number, argument. Second is the list of 3 numbers xi = mi/MN """ x = xx[0] - xl2 = xi[0]**2 - xu2 = xi[1]**2 - xd2 = xi[2]**2 - if x==0: # Workaround for division by zero + xl2 = xi[0] ** 2 + xu2 = xi[1] ** 2 + xd2 = xi[2] ** 2 + if x == 0: # Workaround for division by zero return 0 - res = 1./x - res *= (x - xl2 - xd2) - res *= (1. + xu2 - x) - res *= self.sqrt_lambda(x,xl2,xd2) - res *= self.sqrt_lambda(1.,x,xu2) + res = 1.0 / x + res *= x - xl2 - xd2 + res *= 1.0 + xu2 - x + res *= self.sqrt_lambda(x, xl2, xd2) + res *= self.sqrt_lambda(1.0, x, xu2) return res - def I(self,x1,x2,x3): + def I(self, x1, x2, x3): """ Numerical integral needed for 3-body decays trough W boson. xi = mi/MN """ theFunction = self.Integrand - func = ROOT.TF1('func',theFunction,0,1,3) # Setting function - func.SetParameters(x1,x2,x3) - xmin = (x1 + x3)**2 - xmax = (1. - x2)**2 - wf1 = ROOT.Math.WrappedTF1(func) # Setting simple Gauss integration method + func = ROOT.TF1("func", theFunction, 0, 1, 3) # Setting function + func.SetParameters(x1, x2, x3) + xmin = (x1 + x3) ** 2 + xmax = (1.0 - x2) ** 2 + wf1 = ROOT.Math.WrappedTF1(func) # Setting simple Gauss integration method ig = ROOT.Math.GaussIntegrator() ig.SetFunction(wf1) ig.SetRelTolerance(0.001) - res = 12. * ig.Integral(xmin,xmax) + res = 12.0 * ig.Integral(xmin, xmax) return res def Width_l1_l2_nu2(self, alpha, beta): @@ -293,19 +345,25 @@ def Width_l1_l2_nu2(self, alpha, beta): - alpha is a flavour of the first lepton (1,2 or 3), determine the mixing angle U_alpha - beta is a flavour of the second lepton and neutrino (1, 2 or 3) """ - if (alpha not in [1,2,3]) or (beta not in [1,2,3]): - print('Width_l1_l2_nu2 ERROR: unknown channel alpha =',alpha,' beta =',beta) + if (alpha not in [1, 2, 3]) or (beta not in [1, 2, 3]): + print( + "Width_l1_l2_nu2 ERROR: unknown channel alpha =", alpha, " beta =", beta + ) quit() - if alpha==beta: # The interference case is handled by Width_nu_f_fbar function, workaround for a total width calculation + if ( + alpha == beta + ): # The interference case is handled by Width_nu_f_fbar function, workaround for a total width calculation return 0 - l = [None,'e-','mu-','tau-'] - x1 = mass(l[alpha])/self.MN - x2 = mass(l[beta])/self.MN - if x1+x2>1: # The decay is kinematically forbidden + l = [None, "e-", "mu-", "tau-"] + x1 = mass(l[alpha]) / self.MN + x2 = mass(l[beta]) / self.MN + if x1 + x2 > 1: # The decay is kinematically forbidden return 0 - width = (c.GF**2.)*(self.MN**5.)*self.U2[alpha-1]/(192.*(math.pi**3.)) - width = width*self.I(x1,x2,0) - width = 2.*width # Majorana case (charge conjugate channels) + width = ( + (c.GF**2.0) * (self.MN**5.0) * self.U2[alpha - 1] / (192.0 * (math.pi**3.0)) + ) + width = width * self.I(x1, x2, 0) + width = 2.0 * width # Majorana case (charge conjugate channels) return width def Width_l_u_d(self, alpha, beta, gamma): @@ -317,21 +375,34 @@ def Width_l_u_d(self, alpha, beta, gamma): - beta is the up quark generation (1, 2, 3 for u, c, t) - gamma is the down quark generation (1, 2, 3 for d, s, b) """ - if (alpha not in [1,2,3]) or (beta not in [1,2,3]) or (gamma not in [1,2,3]): - print('Width_l_u_d ERROR: unknown channel alpha =',alpha,' beta =',beta,' gamma =',gamma) + if ( + (alpha not in [1, 2, 3]) + or (beta not in [1, 2, 3]) + or (gamma not in [1, 2, 3]) + ): + print( + "Width_l_u_d ERROR: unknown channel alpha =", + alpha, + " beta =", + beta, + " gamma =", + gamma, + ) quit() - l = [None,'e-','mu-','tau-'] - u = [None,'u','c','t'] - d = [None,'d','s','b'] - xl = mass(l[alpha])/self.MN - xu = mass(u[beta])/self.MN - xd = mass(d[gamma])/self.MN - if xl+xu+xd>1: # The decay is kinematically forbidden + l = [None, "e-", "mu-", "tau-"] + u = [None, "u", "c", "t"] + d = [None, "d", "s", "b"] + xl = mass(l[alpha]) / self.MN + xu = mass(u[beta]) / self.MN + xd = mass(d[gamma]) / self.MN + if xl + xu + xd > 1: # The decay is kinematically forbidden return 0 - width = (c.GF**2.)*(self.MN**5.)*self.U2[alpha-1]/(192.*(math.pi**3.)) - width *= 3*self.CKMelemSq[(beta, gamma)] - width *= self.I(xl,xu,xd) - width = 2.*width # Majorana case (charge conjugate channels) + width = ( + (c.GF**2.0) * (self.MN**5.0) * self.U2[alpha - 1] / (192.0 * (math.pi**3.0)) + ) + width *= 3 * self.CKMelemSq[(beta, gamma)] + width *= self.I(xl, xu, xd) + width = 2.0 * width # Majorana case (charge conjugate channels) return width def Width_H0_nu(self, H, alpha): @@ -342,24 +413,32 @@ def Width_H0_nu(self, H, alpha): - H is a string (name of the meson) - alpha is a flavour of the nu (1, 2 or 3), determine the mixing angle U_alpha """ - if (H not in ['pi0','eta','rho0','omega','eta1','phi','eta_c']) or (alpha not in [1,2,3]): - print('Width_H0_nu ERROR: unknown channel H0 =',H,' alpha =',alpha) + if (H not in ["pi0", "eta", "rho0", "omega", "eta1", "phi", "eta_c"]) or ( + alpha not in [1, 2, 3] + ): + print("Width_H0_nu ERROR: unknown channel H0 =", H, " alpha =", alpha) quit() - x = mass(H)/self.MN - if x > 1: # The decay is kinematically forbidden - return 0. - width = (c.GF**2.)*(c.decayConstant[H]**2.)*(self.MN**3.)*self.U2[alpha-1]/(32.*math.pi) - if H in ['pi0','eta','eta1','eta_c']: # pseudoscalar mesons - width *= (1 - x**2.)**2. - if H in ['rho0','omega','phi']: # vector mesons - width *= (1. + 2*x**2.)*(1. - x**2.)**2. - if H=='rho0': - width *= (1. - 2.*c.s2thetaw)**2. - if H=='omega': - width *= (16.*c.s2thetaw**2.)/9. - if H=='phi': - width *= (1. - 4./3.*c.s2thetaw)**2. - width = 2.*width # Majorana case (charge conjugate channels) + x = mass(H) / self.MN + if x > 1: # The decay is kinematically forbidden + return 0.0 + width = ( + (c.GF**2.0) + * (c.decayConstant[H] ** 2.0) + * (self.MN**3.0) + * self.U2[alpha - 1] + / (32.0 * math.pi) + ) + if H in ["pi0", "eta", "eta1", "eta_c"]: # pseudoscalar mesons + width *= (1 - x**2.0) ** 2.0 + if H in ["rho0", "omega", "phi"]: # vector mesons + width *= (1.0 + 2 * x**2.0) * (1.0 - x**2.0) ** 2.0 + if H == "rho0": + width *= (1.0 - 2.0 * c.s2thetaw) ** 2.0 + if H == "omega": + width *= (16.0 * c.s2thetaw**2.0) / 9.0 + if H == "phi": + width *= (1.0 - 4.0 / 3.0 * c.s2thetaw) ** 2.0 + width = 2.0 * width # Majorana case (charge conjugate channels) return width def Width_H_l(self, H, alpha): @@ -370,81 +449,88 @@ def Width_H_l(self, H, alpha): - H is a string (name of the positively charged meson) - alpha is the lepton flavour (1, 2 or 3), determine the mixing angle U_alpha """ - if (H not in ['pi+','rho+','D_s+','D*_s+']) or (alpha not in [1,2,3]): - print('Width_H_l ERROR: unknown channel H =',H,' alpha =',alpha) + if (H not in ["pi+", "rho+", "D_s+", "D*_s+"]) or (alpha not in [1, 2, 3]): + print("Width_H_l ERROR: unknown channel H =", H, " alpha =", alpha) quit() - l = [None,'e-','mu-','tau-'] - xl = mass(l[alpha])/self.MN - xh = mass(H)/self.MN - if xl+xh > 1: # The decay is kinematically forbidden - return 0. - width = (c.GF**2.)*(c.decayConstant[H]**2.)*self.CKMelemSq[H]*(self.MN**3.)*self.U2[alpha-1]/(16.*math.pi) - width *= self.sqrt_lambda(1., xl**2, xh**2) - if H in ['pi+','D_s+']: # pseudoscalar mesons - width *= ( (1. - xl**2.)**2. - xh**2. *(1. + xl**2.) ) - if H in ['rho+','D*_s+']: # vector mesons - width *= ( (1. - xl**2.)**2. + xh**2.*(1. + xl**2.) - 2.*xh**4. ) - width = 2.*width # Majorana case (charge conjugate channels) + l = [None, "e-", "mu-", "tau-"] + xl = mass(l[alpha]) / self.MN + xh = mass(H) / self.MN + if xl + xh > 1: # The decay is kinematically forbidden + return 0.0 + width = ( + (c.GF**2.0) + * (c.decayConstant[H] ** 2.0) + * self.CKMelemSq[H] + * (self.MN**3.0) + * self.U2[alpha - 1] + / (16.0 * math.pi) + ) + width *= self.sqrt_lambda(1.0, xl**2, xh**2) + if H in ["pi+", "D_s+"]: # pseudoscalar mesons + width *= (1.0 - xl**2.0) ** 2.0 - xh**2.0 * (1.0 + xl**2.0) + if H in ["rho+", "D*_s+"]: # vector mesons + width *= (1.0 - xl**2.0) ** 2.0 + xh**2.0 * (1.0 + xl**2.0) - 2.0 * xh**4.0 + width = 2.0 * width # Majorana case (charge conjugate channels) return width def Width_charged_leptons(self): """ Returns the total HNL leptonic decay width with charged leptons in final state """ - width = 0. - for l1 in [1,2,3]: - for l2 in [1,2,3]: - width += self.Width_nu_f_fbar(l1,l2) - width += self.Width_l1_l2_nu2(l1,l2) + width = 0.0 + for l1 in [1, 2, 3]: + for l2 in [1, 2, 3]: + width += self.Width_nu_f_fbar(l1, l2) + width += self.Width_l1_l2_nu2(l1, l2) return width def Width_neutral_mesons(self): """ Returns the total HNL decay width into a neutral meson and a neutrino """ - mesons = ['pi0','eta','rho0','omega','eta1','phi','eta_c'] - width = 0. + mesons = ["pi0", "eta", "rho0", "omega", "eta1", "phi", "eta_c"] + width = 0.0 for m in mesons: - for l in [1,2,3]: - width += self.Width_H0_nu(m,l) + for l in [1, 2, 3]: + width += self.Width_H0_nu(m, l) return width def Width_charged_mesons(self): """ Returns the total HNL decay width into a charged meson and a charged lepton """ - mesons = ['pi+','rho+','D_s+','D*_s+'] - width = 0. + mesons = ["pi+", "rho+", "D_s+", "D*_s+"] + width = 0.0 for m in mesons: - for l in [1,2,3]: - width += self.Width_H_l(m,l) + for l in [1, 2, 3]: + width += self.Width_H_l(m, l) return width def Width_quarks_neutrino(self): """ Returns the total HNL decay width with quarks and neutrino in final state. Uses 3-loops alpha_s correction """ - if self.MN<1.: # decay into quarks is not applicable at low HNL mass + if self.MN < 1.0: # decay into quarks is not applicable at low HNL mass return 0 - width = 0. - for l in [1,2,3]: - for q in [4,5,6,7,8,9]: - width += self.Width_nu_f_fbar(l,q) - width *= (1. + self.QCD_corr) + width = 0.0 + for l in [1, 2, 3]: + for q in [4, 5, 6, 7, 8, 9]: + width += self.Width_nu_f_fbar(l, q) + width *= 1.0 + self.QCD_corr return width def Width_quarks_lepton(self): """ Returns the total HNL decay width with quarks and charged lepton in final state. Uses 3-loops alpha_s correction """ - if self.MN<1.: # decay into quarks is not applicable at low HNL mass + if self.MN < 1.0: # decay into quarks is not applicable at low HNL mass return 0 - width = 0. - for l in [1,2,3]: - for u in [1,2,3]: - for d in [1,2,3]: - width += self.Width_l_u_d(l,u,d) - width *= (1. + self.QCD_corr) + width = 0.0 + for l in [1, 2, 3]: + for u in [1, 2, 3]: + for d in [1, 2, 3]: + width += self.Width_l_u_d(l, u, d) + width *= 1.0 + self.QCD_corr return width def NDecayWidth(self): @@ -464,62 +550,109 @@ def findBranchingRatio(self, decayString): Inputs: - decayString is a string describing the decay, in the form 'N -> stuff1 ... stuffN' """ - br = 0. + br = 0.0 totalWidth = self.NDecayWidth() - if (decayString not in self.decays) and (decayString not in ['N -> hadrons','N -> charged hadrons']): - print('findBranchingRatio ERROR: unknown decay %s'%decayString) + if (decayString not in self.decays) and ( + decayString not in ["N -> hadrons", "N -> charged hadrons"] + ): + print("findBranchingRatio ERROR: unknown decay %s" % decayString) quit() - if decayString == 'N -> nu nu nu' or decayString == 'N -> 3nu': br = self.Width_3nu() / totalWidth # inclusive - if decayString == 'N -> e- e+ nu_e': br = self.Width_nu_f_fbar(1,1) / totalWidth - if decayString == 'N -> e- e+ nu_mu': br = self.Width_nu_f_fbar(2,1) / totalWidth - if decayString == 'N -> e- e+ nu_tau': br = self.Width_nu_f_fbar(3,1) / totalWidth - if decayString == 'N -> e- mu+ nu_mu': br = self.Width_l1_l2_nu2(1,2) / totalWidth - if decayString == 'N -> mu- e+ nu_e': br = self.Width_l1_l2_nu2(2,1) / totalWidth - if decayString == 'N -> pi0 nu_e': br = self.Width_H0_nu('pi0',1) / totalWidth - if decayString == 'N -> pi0 nu_mu': br = self.Width_H0_nu('pi0',2) / totalWidth - if decayString == 'N -> pi0 nu_tau': br = self.Width_H0_nu('pi0',3) / totalWidth - if decayString == 'N -> pi+ e-': br = self.Width_H_l('pi+',1) / totalWidth - if decayString == 'N -> mu- mu+ nu_e': br = self.Width_nu_f_fbar(1,2) / totalWidth - if decayString == 'N -> mu- mu+ nu_mu': br = self.Width_nu_f_fbar(2,2) / totalWidth - if decayString == 'N -> mu- mu+ nu_tau': br = self.Width_nu_f_fbar(3,2) / totalWidth - if decayString == 'N -> pi+ mu-': br = self.Width_H_l('pi+',2) / totalWidth - if decayString == 'N -> eta nu_e': br = self.Width_H0_nu('eta',1) / totalWidth - if decayString == 'N -> eta nu_mu': br = self.Width_H0_nu('eta',2) / totalWidth - if decayString == 'N -> eta nu_tau': br = self.Width_H0_nu('eta',3) / totalWidth - if decayString == 'N -> rho0 nu_e': br = self.Width_H0_nu('rho0',1) / totalWidth - if decayString == 'N -> rho0 nu_mu': br = self.Width_H0_nu('rho0',2) / totalWidth - if decayString == 'N -> rho0 nu_tau': br = self.Width_H0_nu('rho0',3) / totalWidth - if decayString == 'N -> rho+ e-': br = self.Width_H_l('rho+',1) / totalWidth - if decayString == 'N -> omega nu_e': br = self.Width_H0_nu('omega',1) / totalWidth - if decayString == 'N -> omega nu_mu': br = self.Width_H0_nu('omega',2) / totalWidth - if decayString == 'N -> omega nu_tau': br = self.Width_H0_nu('omega',3) / totalWidth - if decayString == 'N -> rho+ mu-': br = self.Width_H_l('rho+',2) / totalWidth - if decayString == 'N -> eta1 nu_e': br = self.Width_H0_nu('eta1',1) / totalWidth - if decayString == 'N -> eta1 nu_mu': br = self.Width_H0_nu('eta1',2) / totalWidth - if decayString == 'N -> eta1 nu_tau': br = self.Width_H0_nu('eta1',3) / totalWidth - if decayString == 'N -> phi nu_e': br = self.Width_H0_nu('phi',1) / totalWidth - if decayString == 'N -> phi nu_mu': br = self.Width_H0_nu('phi',2) / totalWidth - if decayString == 'N -> phi nu_tau': br = self.Width_H0_nu('phi',3) / totalWidth - if decayString == 'N -> e- tau+ nu_tau': br = self.Width_l1_l2_nu2(1,3) / totalWidth - if decayString == 'N -> tau- e+ nu_e': br = self.Width_l1_l2_nu2(3,1) / totalWidth - if decayString == 'N -> mu- tau+ nu_tau': br = self.Width_l1_l2_nu2(2,3) / totalWidth - if decayString == 'N -> tau- mu+ nu_mu': br = self.Width_l1_l2_nu2(3,2) / totalWidth - if decayString == 'N -> D_s+ e-': br = self.Width_H_l('D_s+',1) / totalWidth - if decayString == 'N -> D_s+ mu-': br = self.Width_H_l('D_s+',2) / totalWidth - if decayString == 'N -> D*_s+ e-': br = self.Width_H_l('D*_s+',1) / totalWidth - if decayString == 'N -> D*_s+ mu-': br = self.Width_H_l('D*_s+',2) / totalWidth - if decayString == 'N -> eta_c nu_e': br = self.Width_H0_nu('eta_c',1) / totalWidth - if decayString == 'N -> eta_c nu_mu': br = self.Width_H0_nu('eta_c',2) / totalWidth - if decayString == 'N -> eta_c nu_tau': br = self.Width_H0_nu('eta_c',3) / totalWidth - - if decayString == 'N -> hadrons': + if decayString == "N -> nu nu nu" or decayString == "N -> 3nu": + br = self.Width_3nu() / totalWidth # inclusive + if decayString == "N -> e- e+ nu_e": + br = self.Width_nu_f_fbar(1, 1) / totalWidth + if decayString == "N -> e- e+ nu_mu": + br = self.Width_nu_f_fbar(2, 1) / totalWidth + if decayString == "N -> e- e+ nu_tau": + br = self.Width_nu_f_fbar(3, 1) / totalWidth + if decayString == "N -> e- mu+ nu_mu": + br = self.Width_l1_l2_nu2(1, 2) / totalWidth + if decayString == "N -> mu- e+ nu_e": + br = self.Width_l1_l2_nu2(2, 1) / totalWidth + if decayString == "N -> pi0 nu_e": + br = self.Width_H0_nu("pi0", 1) / totalWidth + if decayString == "N -> pi0 nu_mu": + br = self.Width_H0_nu("pi0", 2) / totalWidth + if decayString == "N -> pi0 nu_tau": + br = self.Width_H0_nu("pi0", 3) / totalWidth + if decayString == "N -> pi+ e-": + br = self.Width_H_l("pi+", 1) / totalWidth + if decayString == "N -> mu- mu+ nu_e": + br = self.Width_nu_f_fbar(1, 2) / totalWidth + if decayString == "N -> mu- mu+ nu_mu": + br = self.Width_nu_f_fbar(2, 2) / totalWidth + if decayString == "N -> mu- mu+ nu_tau": + br = self.Width_nu_f_fbar(3, 2) / totalWidth + if decayString == "N -> pi+ mu-": + br = self.Width_H_l("pi+", 2) / totalWidth + if decayString == "N -> eta nu_e": + br = self.Width_H0_nu("eta", 1) / totalWidth + if decayString == "N -> eta nu_mu": + br = self.Width_H0_nu("eta", 2) / totalWidth + if decayString == "N -> eta nu_tau": + br = self.Width_H0_nu("eta", 3) / totalWidth + if decayString == "N -> rho0 nu_e": + br = self.Width_H0_nu("rho0", 1) / totalWidth + if decayString == "N -> rho0 nu_mu": + br = self.Width_H0_nu("rho0", 2) / totalWidth + if decayString == "N -> rho0 nu_tau": + br = self.Width_H0_nu("rho0", 3) / totalWidth + if decayString == "N -> rho+ e-": + br = self.Width_H_l("rho+", 1) / totalWidth + if decayString == "N -> omega nu_e": + br = self.Width_H0_nu("omega", 1) / totalWidth + if decayString == "N -> omega nu_mu": + br = self.Width_H0_nu("omega", 2) / totalWidth + if decayString == "N -> omega nu_tau": + br = self.Width_H0_nu("omega", 3) / totalWidth + if decayString == "N -> rho+ mu-": + br = self.Width_H_l("rho+", 2) / totalWidth + if decayString == "N -> eta1 nu_e": + br = self.Width_H0_nu("eta1", 1) / totalWidth + if decayString == "N -> eta1 nu_mu": + br = self.Width_H0_nu("eta1", 2) / totalWidth + if decayString == "N -> eta1 nu_tau": + br = self.Width_H0_nu("eta1", 3) / totalWidth + if decayString == "N -> phi nu_e": + br = self.Width_H0_nu("phi", 1) / totalWidth + if decayString == "N -> phi nu_mu": + br = self.Width_H0_nu("phi", 2) / totalWidth + if decayString == "N -> phi nu_tau": + br = self.Width_H0_nu("phi", 3) / totalWidth + if decayString == "N -> e- tau+ nu_tau": + br = self.Width_l1_l2_nu2(1, 3) / totalWidth + if decayString == "N -> tau- e+ nu_e": + br = self.Width_l1_l2_nu2(3, 1) / totalWidth + if decayString == "N -> mu- tau+ nu_tau": + br = self.Width_l1_l2_nu2(2, 3) / totalWidth + if decayString == "N -> tau- mu+ nu_mu": + br = self.Width_l1_l2_nu2(3, 2) / totalWidth + if decayString == "N -> D_s+ e-": + br = self.Width_H_l("D_s+", 1) / totalWidth + if decayString == "N -> D_s+ mu-": + br = self.Width_H_l("D_s+", 2) / totalWidth + if decayString == "N -> D*_s+ e-": + br = self.Width_H_l("D*_s+", 1) / totalWidth + if decayString == "N -> D*_s+ mu-": + br = self.Width_H_l("D*_s+", 2) / totalWidth + if decayString == "N -> eta_c nu_e": + br = self.Width_H0_nu("eta_c", 1) / totalWidth + if decayString == "N -> eta_c nu_mu": + br = self.Width_H0_nu("eta_c", 2) / totalWidth + if decayString == "N -> eta_c nu_tau": + br = self.Width_H0_nu("eta_c", 3) / totalWidth + + if decayString == "N -> hadrons": mesonWidth = self.Width_neutral_mesons() + self.Width_charged_mesons() quarkWidth = self.Width_quarks_neutrino() + self.Width_quarks_lepton() br = max([mesonWidth, quarkWidth]) / totalWidth - if decayString == 'N -> charged hadrons': - br = max([self.Width_charged_mesons(), self.Width_quarks_lepton()]) / totalWidth + if decayString == "N -> charged hadrons": + br = ( + max([self.Width_charged_mesons(), self.Width_quarks_lepton()]) + / totalWidth + ) return br def allowedChannels(self): @@ -530,81 +663,80 @@ def allowedChannels(self): - decayString is a string describing the decay, in the form 'N -> stuff1 ... stuffN' """ m = self.MN - allowedDecays = {'N -> nu nu nu':'yes'} - if m > 2.*mass('e-'): - allowedDecays.update({'N -> e- e+ nu_e':'yes'}) - allowedDecays.update({'N -> e- e+ nu_mu':'yes'}) - allowedDecays.update({'N -> e- e+ nu_tau':'yes'}) - if m > mass('e-') + mass('mu-'): - allowedDecays.update({'N -> e- mu+ nu_mu':'yes'}) - allowedDecays.update({'N -> mu- e+ nu_e':'yes'}) - if m > mass('pi0'): - allowedDecays.update({'N -> pi0 nu_e':'yes'}) - allowedDecays.update({'N -> pi0 nu_mu':'yes'}) - allowedDecays.update({'N -> pi0 nu_tau':'yes'}) - if m > mass('pi+') + mass('e-'): - allowedDecays.update({'N -> pi+ e-':'yes'}) - if m > 2.*mass('mu-'): - allowedDecays.update({'N -> mu- mu+ nu_e':'yes'}) - allowedDecays.update({'N -> mu- mu+ nu_mu':'yes'}) - allowedDecays.update({'N -> mu- mu+ nu_tau':'yes'}) - if m > mass('pi+') + mass('mu-'): - allowedDecays.update({'N -> pi+ mu-':'yes'}) - if m > mass('eta'): - allowedDecays.update({'N -> eta nu_e':'yes'}) - allowedDecays.update({'N -> eta nu_mu':'yes'}) - allowedDecays.update({'N -> eta nu_tau':'yes'}) - if m > mass('rho0'): - allowedDecays.update({'N -> rho0 nu_e':'yes'}) - allowedDecays.update({'N -> rho0 nu_mu':'yes'}) - allowedDecays.update({'N -> rho0 nu_tau':'yes'}) - if m > mass('rho+') + mass('e-'): - allowedDecays.update({'N -> rho+ e-':'yes'}) - if m > mass('omega'): - allowedDecays.update({'N -> omega nu_e':'yes'}) - allowedDecays.update({'N -> omega nu_mu':'yes'}) - allowedDecays.update({'N -> omega nu_tau':'yes'}) - if m > mass('rho+') + mass('mu-'): - allowedDecays.update({'N -> rho+ mu-':'yes'}) - if m > mass('eta1'): - allowedDecays.update({'N -> eta1 nu_e':'yes'}) - allowedDecays.update({'N -> eta1 nu_mu':'yes'}) - allowedDecays.update({'N -> eta1 nu_tau':'yes'}) - if m > mass('phi'): - allowedDecays.update({'N -> phi nu_e':'yes'}) - allowedDecays.update({'N -> phi nu_mu':'yes'}) - allowedDecays.update({'N -> phi nu_tau':'yes'}) - if m > mass('e-') + mass('tau-'): - allowedDecays.update({'N -> e- tau+ nu_tau':'yes'}) - allowedDecays.update({'N -> tau- e+ nu_e':'yes'}) - if m > mass('mu-') + mass('tau-'): - allowedDecays.update({'N -> mu- tau+ nu_tau':'yes'}) - allowedDecays.update({'N -> tau- mu+ nu_mu':'yes'}) - if m > mass('D_s+') + mass('e-'): - allowedDecays.update({'N -> D_s+ e-':'yes'}) - if m > mass('D_s+') + mass('mu-'): - allowedDecays.update({'N -> D_s+ mu-':'yes'}) - if m > mass('D*_s+') + mass('e-'): - allowedDecays.update({'N -> D*_s+ e-':'yes'}) - if m > mass('D*_s+') + mass('mu-'): - allowedDecays.update({'N -> D*_s+ mu-':'yes'}) - if m > mass('eta_c'): - allowedDecays.update({'N -> eta_c nu_e':'yes'}) - allowedDecays.update({'N -> eta_c nu_mu':'yes'}) - allowedDecays.update({'N -> eta_c nu_tau':'yes'}) + allowedDecays = {"N -> nu nu nu": "yes"} + if m > 2.0 * mass("e-"): + allowedDecays.update({"N -> e- e+ nu_e": "yes"}) + allowedDecays.update({"N -> e- e+ nu_mu": "yes"}) + allowedDecays.update({"N -> e- e+ nu_tau": "yes"}) + if m > mass("e-") + mass("mu-"): + allowedDecays.update({"N -> e- mu+ nu_mu": "yes"}) + allowedDecays.update({"N -> mu- e+ nu_e": "yes"}) + if m > mass("pi0"): + allowedDecays.update({"N -> pi0 nu_e": "yes"}) + allowedDecays.update({"N -> pi0 nu_mu": "yes"}) + allowedDecays.update({"N -> pi0 nu_tau": "yes"}) + if m > mass("pi+") + mass("e-"): + allowedDecays.update({"N -> pi+ e-": "yes"}) + if m > 2.0 * mass("mu-"): + allowedDecays.update({"N -> mu- mu+ nu_e": "yes"}) + allowedDecays.update({"N -> mu- mu+ nu_mu": "yes"}) + allowedDecays.update({"N -> mu- mu+ nu_tau": "yes"}) + if m > mass("pi+") + mass("mu-"): + allowedDecays.update({"N -> pi+ mu-": "yes"}) + if m > mass("eta"): + allowedDecays.update({"N -> eta nu_e": "yes"}) + allowedDecays.update({"N -> eta nu_mu": "yes"}) + allowedDecays.update({"N -> eta nu_tau": "yes"}) + if m > mass("rho0"): + allowedDecays.update({"N -> rho0 nu_e": "yes"}) + allowedDecays.update({"N -> rho0 nu_mu": "yes"}) + allowedDecays.update({"N -> rho0 nu_tau": "yes"}) + if m > mass("rho+") + mass("e-"): + allowedDecays.update({"N -> rho+ e-": "yes"}) + if m > mass("omega"): + allowedDecays.update({"N -> omega nu_e": "yes"}) + allowedDecays.update({"N -> omega nu_mu": "yes"}) + allowedDecays.update({"N -> omega nu_tau": "yes"}) + if m > mass("rho+") + mass("mu-"): + allowedDecays.update({"N -> rho+ mu-": "yes"}) + if m > mass("eta1"): + allowedDecays.update({"N -> eta1 nu_e": "yes"}) + allowedDecays.update({"N -> eta1 nu_mu": "yes"}) + allowedDecays.update({"N -> eta1 nu_tau": "yes"}) + if m > mass("phi"): + allowedDecays.update({"N -> phi nu_e": "yes"}) + allowedDecays.update({"N -> phi nu_mu": "yes"}) + allowedDecays.update({"N -> phi nu_tau": "yes"}) + if m > mass("e-") + mass("tau-"): + allowedDecays.update({"N -> e- tau+ nu_tau": "yes"}) + allowedDecays.update({"N -> tau- e+ nu_e": "yes"}) + if m > mass("mu-") + mass("tau-"): + allowedDecays.update({"N -> mu- tau+ nu_tau": "yes"}) + allowedDecays.update({"N -> tau- mu+ nu_mu": "yes"}) + if m > mass("D_s+") + mass("e-"): + allowedDecays.update({"N -> D_s+ e-": "yes"}) + if m > mass("D_s+") + mass("mu-"): + allowedDecays.update({"N -> D_s+ mu-": "yes"}) + if m > mass("D*_s+") + mass("e-"): + allowedDecays.update({"N -> D*_s+ e-": "yes"}) + if m > mass("D*_s+") + mass("mu-"): + allowedDecays.update({"N -> D*_s+ mu-": "yes"}) + if m > mass("eta_c"): + allowedDecays.update({"N -> eta_c nu_e": "yes"}) + allowedDecays.update({"N -> eta_c nu_mu": "yes"}) + allowedDecays.update({"N -> eta_c nu_tau": "yes"}) for decay in self.decays: if decay not in allowedDecays: - allowedDecays.update({decay:'no'}) + allowedDecays.update({decay: "no"}) return allowedDecays - - class HNL(HNLbranchings): """ HNL physics according to the nuMSM """ + def __init__(self, mass, couplings, debug=False): """ Initialize with mass and couplings of the HNL @@ -614,7 +746,8 @@ def __init__(self, mass, couplings, debug=False): couplings (list of [U2e, U2mu, U2tau]) """ HNLbranchings.__init__(self, mass, couplings, debug) - def computeNLifetime(self,system="SI"): + + def computeNLifetime(self, system="SI"): """ Compute the HNL lifetime @@ -622,5 +755,6 @@ def computeNLifetime(self,system="SI"): - system: choose between default (i.e. SI, result in s) or FairShip (result in ns) """ self.NLifetime = c.hGeV / self.NDecayWidth() - if system == "FairShip": self.NLifetime *= 1.e9 + if system == "FairShip": + self.NLifetime *= 1.0e9 return self.NLifetime diff --git a/python/logger.py b/python/logger.py index 8ae06258d7..117d74c7f8 100644 --- a/python/logger.py +++ b/python/logger.py @@ -1,29 +1,43 @@ # -*- coding: utf-8 -*- import os + import ROOT + # TODO: add header to CMake -ROOT.gROOT.ProcessLine('#include "' + os.path.join(os.path.expandvars('$FAIRSHIP'), 'utils', 'logger.hxx') + '"') +ROOT.gROOT.ProcessLine( + '#include "' + + os.path.join(os.path.expandvars("$FAIRSHIP"), "utils", "logger.hxx") + + '"' +) + def _make_wrapper(funcname): def function(*args, **kwargs): - delim = kwargs.get('delim', ' ') + delim = kwargs.get("delim", " ") # Interleaves arguments with delimiters. No delimiter at the end. - args_with_delim = [val for pair in zip(args, len(args)*[delim]) for val in pair][:-1] - return ROOT.ship.__dict__[funcname](*map(type, args_with_delim))(*args_with_delim) - docstring = '''\ + args_with_delim = [ + val for pair in zip(args, len(args) * [delim]) for val in pair + ][:-1] + return ROOT.ship.__dict__[funcname](*map(type, args_with_delim))( + *args_with_delim + ) + + docstring = """\ Python wrapper around the C++ function template ship::{}(Types... args). Keyword arguments: delim -- delimiter to be inserted between each argument (default \' \') - '''.format(funcname) + """.format(funcname) return function, docstring + def _add_wrappers(): # This function is used to avoid polluting the global namespace - for funcname in ('fatal', 'error', 'warn', 'info', 'debug'): + for funcname in ("fatal", "error", "warn", "info", "debug"): function, docstring = _make_wrapper(funcname) globals()[funcname] = function globals()[funcname].__doc__ = docstring + _add_wrappers() diff --git a/python/method_logger.py b/python/method_logger.py index def1cd5a2a..26cf50359f 100644 --- a/python/method_logger.py +++ b/python/method_logger.py @@ -1,7 +1,8 @@ # -*- coding: utf-8 -*- -from functools import wraps import sys +from functools import wraps + class MethodLogger(object): """ @@ -24,20 +25,23 @@ class MethodLogger(object): "TestClass.func(3, y=8, foo='bar')\\n" >>> sink.close() """ + def __init__(self, wrapped_instance, sink=sys.stdout): self._class = wrapped_instance self._sink = sink - self._prefix = type(wrapped_instance).__name__ + '.' + self._prefix = type(wrapped_instance).__name__ + "." def method_logger(self, met): qualified_name = self._prefix + str(met.__name__) + @wraps(met) def _logger(*args, **kwargs): - args_str = ', '.join(repr(arg) for arg in args) - kwargs_str = ', '.join(str(k) + '=' + repr(v) for (k,v) in kwargs.items()) - all_args_str = args_str + (', ' if len(kwargs_str) > 0 else '') + kwargs_str - print('{0}({1})'.format(qualified_name, all_args_str), file=self._sink) + args_str = ", ".join(repr(arg) for arg in args) + kwargs_str = ", ".join(str(k) + "=" + repr(v) for (k, v) in kwargs.items()) + all_args_str = args_str + (", " if len(kwargs_str) > 0 else "") + kwargs_str + print("{0}({1})".format(qualified_name, all_args_str), file=self._sink) return met.__call__(*args, **kwargs) + return _logger def __getattr__(self, attr): diff --git a/python/pi0Reco.py b/python/pi0Reco.py index 58c53bdbfd..4c7f64f41d 100644 --- a/python/pi0Reco.py +++ b/python/pi0Reco.py @@ -1,35 +1,49 @@ -import ROOT,os -import shipunit as u +import os + +import ROOT import rootUtils as ut +import shipunit as u + pdg = ROOT.TDatabasePDG.Instance() mPi0 = pdg.GetParticle(111).Mass() L = ROOT.TLorentzVector() V = ROOT.TVector3() top = ROOT.gGeoManager.GetTopVolume() -z_ecal = top.GetNode('Ecal_1').GetMatrix().GetTranslation()[2] +z_ecal = top.GetNode("Ecal_1").GetMatrix().GetTranslation()[2] -def findPi0(sTree,secVertex): - recoGammas = {} - pi0List = [] - listOfGammas = None - for aClu in sTree.EcalReconstructed: -# short cut to exclude ecal clusters of charged tracks -# would need another routine to extrapolate tracks to ecal and exclude matched showers - mc = aClu.MCTrack() - if mc<0: continue - gamma = sTree.MCTrack[mc] - if gamma.GetPdgCode()!=22: continue - if gamma.GetMotherId()<0: continue - P = aClu.RecoE() - direction = ROOT.TVector3(aClu.X()-secVertex.X(),aClu.Y()-secVertex.Y(),z_ecal-secVertex.Z()) - norm = direction.Mag() - recoGammas[gamma] = ROOT.TLorentzVector(direction.X()/norm*P,direction.Y()/norm*P,direction.Z()/norm*P,P) - sTree.MCTrack[mc].GetStartVertex(V) - if len(recoGammas)==0: return [] - listOfGammas=list(recoGammas.values()) - for g1 in range(len(listOfGammas)-1): - for g2 in range(g1+1,len(listOfGammas)): - pi0 = listOfGammas[g1] + listOfGammas[g2] - pi0List.append(pi0) - return pi0List +def findPi0(sTree, secVertex): + recoGammas = {} + pi0List = [] + listOfGammas = None + for aClu in sTree.EcalReconstructed: + # short cut to exclude ecal clusters of charged tracks + # would need another routine to extrapolate tracks to ecal and exclude matched showers + mc = aClu.MCTrack() + if mc < 0: + continue + gamma = sTree.MCTrack[mc] + if gamma.GetPdgCode() != 22: + continue + if gamma.GetMotherId() < 0: + continue + P = aClu.RecoE() + direction = ROOT.TVector3( + aClu.X() - secVertex.X(), aClu.Y() - secVertex.Y(), z_ecal - secVertex.Z() + ) + norm = direction.Mag() + recoGammas[gamma] = ROOT.TLorentzVector( + direction.X() / norm * P, + direction.Y() / norm * P, + direction.Z() / norm * P, + P, + ) + sTree.MCTrack[mc].GetStartVertex(V) + if len(recoGammas) == 0: + return [] + listOfGammas = list(recoGammas.values()) + for g1 in range(len(listOfGammas) - 1): + for g2 in range(g1 + 1, len(listOfGammas)): + pi0 = listOfGammas[g1] + listOfGammas[g2] + pi0List.append(pi0) + return pi0List diff --git a/python/proton_bremsstrahlung.py b/python/proton_bremsstrahlung.py index 96b66c47e7..fba382d81c 100644 --- a/python/proton_bremsstrahlung.py +++ b/python/proton_bremsstrahlung.py @@ -1,87 +1,111 @@ -import numpy as np -import ROOT as r import math -import os,sys -from scipy.integrate import quad, dblquad +import os +import sys +import numpy as np +import ROOT as r from darkphoton import * +from scipy.integrate import dblquad, quad # proton mass -mProton = 0.938272081 # GeV/c - PDG2016 -protonEnergy = 400. # GeV/c -protonMomentum = math.sqrt(protonEnergy*protonEnergy - mProton*mProton) +mProton = 0.938272081 # GeV/c - PDG2016 +protonEnergy = 400.0 # GeV/c +protonMomentum = math.sqrt(protonEnergy * protonEnergy - mProton * mProton) -#VDM FORM FACTOR + +# VDM FORM FACTOR def rhoFormFactor(m): - """ From https://arxiv.org/abs/0910.5589 """ - #constants from the code from Inar: https://github.com/pgdeniverville/BdNMC/blob/master/src/Proton_Brem_Distribution.cpp - f1ra = 0.6165340033101271 - f1rb = 0.22320420111672623 - f1rc = -0.33973820442685326 - f1wa = 1.0117544786579074 - f1wb = -0.8816565944110686 - f1wc = 0.3699021157531611 - f1prho = f1ra*0.77**2/(0.77**2-m**2-0.77*0.15j) - f1prhop = f1rb*1.25**2/(1.25**2-m**2-1.25*0.3j) - f1prhopp = f1rc*1.45**2/(1.45**2-m**2-1.45*0.5j) - f1pomega = f1wa*0.77**2/(0.77**2-m**2-0.77*0.0085j) - f1pomegap = f1wb*1.25**2/(1.25**2-m**2-1.25*0.3j) - f1pomegapp = f1wc*1.45**2/(1.45**2-m**2-1.45*0.5j) - return abs(f1prho+f1prhop+f1prhopp+f1pomega+f1pomegap+f1pomegapp) + """From https://arxiv.org/abs/0910.5589""" + # constants from the code from Inar: https://github.com/pgdeniverville/BdNMC/blob/master/src/Proton_Brem_Distribution.cpp + f1ra = 0.6165340033101271 + f1rb = 0.22320420111672623 + f1rc = -0.33973820442685326 + f1wa = 1.0117544786579074 + f1wb = -0.8816565944110686 + f1wc = 0.3699021157531611 + f1prho = f1ra * 0.77**2 / (0.77**2 - m**2 - 0.77 * 0.15j) + f1prhop = f1rb * 1.25**2 / (1.25**2 - m**2 - 1.25 * 0.3j) + f1prhopp = f1rc * 1.45**2 / (1.45**2 - m**2 - 1.45 * 0.5j) + f1pomega = f1wa * 0.77**2 / (0.77**2 - m**2 - 0.77 * 0.0085j) + f1pomegap = f1wb * 1.25**2 / (1.25**2 - m**2 - 1.25 * 0.3j) + f1pomegapp = f1wc * 1.45**2 / (1.45**2 - m**2 - 1.45 * 0.5j) + return abs(f1prho + f1prhop + f1prhopp + f1pomega + f1pomegap + f1pomegapp) + # useful functions -def energy(p,m): - """ Compute energy from momentum and mass """ - return math.sqrt(p*p + m*m) +def energy(p, m): + """Compute energy from momentum and mass""" + return math.sqrt(p * p + m * m) + def penaltyFactor(m): - """ Penalty factor for high masses - dipole form factor in the proton-A' vertex """ + """Penalty factor for high masses - dipole form factor in the proton-A' vertex""" """ m in GeV """ - if m*m>0.71: - return math.pow(m*m/0.71,-4) + if m * m > 0.71: + return math.pow(m * m / 0.71, -4) else: return 1 + def zeta(p, theta): - """ Fraction of the proton momentum carried away by the paraphoton in the beam direction """ - return p / (protonMomentum * math.sqrt(theta*theta + 1.)) + """Fraction of the proton momentum carried away by the paraphoton in the beam direction""" + return p / (protonMomentum * math.sqrt(theta * theta + 1.0)) def pTransverse(p, theta): - """ Paraphoton transverse momentum in the lab frame """ - return protonMomentum*theta*zeta(p,theta) + """Paraphoton transverse momentum in the lab frame""" + return protonMomentum * theta * zeta(p, theta) def ptSquare(p, theta): - """ Square paraphoton transverse momentum in the lab frame """ - return pow(pTransverse(p,theta), 2.) + """Square paraphoton transverse momentum in the lab frame""" + return pow(pTransverse(p, theta), 2.0) def H(p, theta, mDarkPhoton): - """ A kinematic term """ - return ptSquare(p,theta) + (1.-zeta(p,theta))*mDarkPhoton*mDarkPhoton + pow(zeta(p,theta),2.)*mProton*mProton + """A kinematic term""" + return ( + ptSquare(p, theta) + + (1.0 - zeta(p, theta)) * mDarkPhoton * mDarkPhoton + + pow(zeta(p, theta), 2.0) * mProton * mProton + ) def wba(p, theta, mDarkPhoton, epsilon): - """ Cross section weighting function in the Fermi-Weizsaeker-Williams approximation """ - const = epsilon*epsilon*alphaQED / (2.*math.pi*H(p,theta,mDarkPhoton)) - - h2 = pow(H(p,theta,mDarkPhoton),2.) - oneMinusZSquare = pow(1.-zeta(p,theta),2.) - mp2 = mProton*mProton - mA2 = mDarkPhoton*mDarkPhoton - - p1 = (1. + oneMinusZSquare) / zeta(p,theta) - p2 = ( 2. * zeta(p,theta) * (1.-zeta(p,theta)) * ( (2.*mp2 + mA2)/ H(p,theta,mDarkPhoton) - - pow(zeta(p,theta),2.)*2.*mp2*mp2/h2 ) ) - #p3 = 2.*zeta(p,theta)*(1.-zeta(p,theta))*(zeta(p,theta)+oneMinusZSquare)*mp2*mA2/h2 - p3 = 2.*zeta(p,theta)*(1.-zeta(p,theta))*(1+oneMinusZSquare)*mp2*mA2/h2 - p4 = 2.*zeta(p,theta)*oneMinusZSquare*mA2*mA2/h2 - return const*(p1-p2+p3+p4) - - -def sigma(s): # s in GeV^2 ---> sigma in mb - """ Parametrisation of sigma(s) """ + """Cross section weighting function in the Fermi-Weizsaeker-Williams approximation""" + const = epsilon * epsilon * alphaQED / (2.0 * math.pi * H(p, theta, mDarkPhoton)) + + h2 = pow(H(p, theta, mDarkPhoton), 2.0) + oneMinusZSquare = pow(1.0 - zeta(p, theta), 2.0) + mp2 = mProton * mProton + mA2 = mDarkPhoton * mDarkPhoton + + p1 = (1.0 + oneMinusZSquare) / zeta(p, theta) + p2 = ( + 2.0 + * zeta(p, theta) + * (1.0 - zeta(p, theta)) + * ( + (2.0 * mp2 + mA2) / H(p, theta, mDarkPhoton) + - pow(zeta(p, theta), 2.0) * 2.0 * mp2 * mp2 / h2 + ) + ) + # p3 = 2.*zeta(p,theta)*(1.-zeta(p,theta))*(zeta(p,theta)+oneMinusZSquare)*mp2*mA2/h2 + p3 = ( + 2.0 + * zeta(p, theta) + * (1.0 - zeta(p, theta)) + * (1 + oneMinusZSquare) + * mp2 + * mA2 + / h2 + ) + p4 = 2.0 * zeta(p, theta) * oneMinusZSquare * mA2 * mA2 / h2 + return const * (p1 - p2 + p3 + p4) + + +def sigma(s): # s in GeV^2 ---> sigma in mb + """Parametrisation of sigma(s)""" a1 = 35.45 a2 = 0.308 a3 = 28.94 @@ -89,109 +113,152 @@ def sigma(s): # s in GeV^2 ---> sigma in mb a5 = 0.545 a6 = 0.458 a7 = 42.53 - p1 = a2*pow(math.log(s/a3),2.) - p2 = a4*pow((1./s),a5) - p3 = a7*pow((1./s),a6) + p1 = a2 * pow(math.log(s / a3), 2.0) + p2 = a4 * pow((1.0 / s), a5) + p3 = a7 * pow((1.0 / s), a6) return a1 + p1 - p2 + p3 def es(p, mDarkPhoton): - """ s(p,mA) """ - return 2.*mProton*(energy(protonMomentum,mProton)-energy(p,mDarkPhoton)) + """s(p,mA)""" + return 2.0 * mProton * (energy(protonMomentum, mProton) - energy(p, mDarkPhoton)) def sigmaRatio(p, mDarkPhoton): - """ sigma(s') / sigma(s) """ - return sigma(es(p,mDarkPhoton)) / sigma(2.*mProton*energy(protonMomentum,mProton)) + """sigma(s') / sigma(s)""" + return sigma(es(p, mDarkPhoton)) / sigma( + 2.0 * mProton * energy(protonMomentum, mProton) + ) def dNdZdPtSquare(p, mDarkPhoton, theta, epsilon): - """ Differential A' rate per p.o.t. as a function of Z and Pt^2 """ - return sigmaRatio(p,mDarkPhoton)*wba(p,theta,mDarkPhoton,epsilon) + """Differential A' rate per p.o.t. as a function of Z and Pt^2""" + return sigmaRatio(p, mDarkPhoton) * wba(p, theta, mDarkPhoton, epsilon) def dPt2dTheta(p, theta): - """ Jacobian Pt^2->theta """ - z2 = pow(zeta(p,theta),2.) - return 2.*theta*z2*protonMomentum*protonMomentum + """Jacobian Pt^2->theta""" + z2 = pow(zeta(p, theta), 2.0) + return 2.0 * theta * z2 * protonMomentum * protonMomentum def dZdP(p, theta): - """ Jacobian z->p """ - return 1./( protonMomentum* math.sqrt(theta*theta+1.) ) + """Jacobian z->p""" + return 1.0 / (protonMomentum * math.sqrt(theta * theta + 1.0)) def dNdPdTheta(p, theta, mDarkPhoton, epsilon): - """ Differential A' rate per p.o.t. as a function of P and theta """ - diffRate = dNdZdPtSquare(p,mDarkPhoton,theta,epsilon) * dPt2dTheta(p,theta) * dZdP(p,theta) - return math.fabs(diffRate) # integrating in (-pi, pi)... + """Differential A' rate per p.o.t. as a function of P and theta""" + diffRate = ( + dNdZdPtSquare(p, mDarkPhoton, theta, epsilon) + * dPt2dTheta(p, theta) + * dZdP(p, theta) + ) + return math.fabs(diffRate) # integrating in (-pi, pi)... def pMin(mDarkPhoton): - return max(0.14*protonMomentum, mDarkPhoton) + return max(0.14 * protonMomentum, mDarkPhoton) def pMax(mDarkPhoton): - #return min(0.86*protonMomentum, math.sqrt( (energy(protonMomentum,mProton)**2. - mDarkPhoton**2.) - mDarkPhoton**2.)) - return math.sqrt( (energy(protonMomentum,mProton)**2. - mDarkPhoton**2.) - mDarkPhoton**2.) - - -def prodRate(mDarkPhoton, epsilon, tmin = -0.5 * math.pi, tmax = 0.5 * math.pi): - """ dNdPdTheta integrated over p and theta """ - integral = dblquad( dNdPdTheta, # integrand - tmin, tmax, # theta boundaries (2nd argument of integrand) - lambda x: pMin(mDarkPhoton), lambda x: pMax(mDarkPhoton), # p boundaries (1st argument of integrand) - args=(mDarkPhoton, epsilon) ) # extra parameters to pass to integrand + # return min(0.86*protonMomentum, math.sqrt( (energy(protonMomentum,mProton)**2. - mDarkPhoton**2.) - mDarkPhoton**2.)) + return math.sqrt( + (energy(protonMomentum, mProton) ** 2.0 - mDarkPhoton**2.0) - mDarkPhoton**2.0 + ) + + +def prodRate(mDarkPhoton, epsilon, tmin=-0.5 * math.pi, tmax=0.5 * math.pi): + """dNdPdTheta integrated over p and theta""" + integral = dblquad( + dNdPdTheta, # integrand + tmin, + tmax, # theta boundaries (2nd argument of integrand) + lambda x: pMin(mDarkPhoton), + lambda x: pMax(mDarkPhoton), # p boundaries (1st argument of integrand) + args=(mDarkPhoton, epsilon), + ) # extra parameters to pass to integrand return integral[0] + # total production rate of A' -#norm = prodRate(1.1,3.e-7) #mDarkPhoton,epsilon) +# norm = prodRate(1.1,3.e-7) #mDarkPhoton,epsilon) # number of A' produced # numDarkPhotons = int(math.floor(norm*protonFlux)) # # print # print "Epsilon \t %s"%epsilon # print "mDarkPhoton \t %s"%mDarkPhoton -#print "A' production rate per p.o.t: \t %.8g"%norm +# print "A' production rate per p.o.t: \t %.8g"%norm # print "Number of A' produced in SHiP: \t %.8g"%numDarkPhotons def normalisedProductionPDF(p, theta, mDarkPhoton, epsilon, norm): - """ Probability density function for A' production in SHIP """ - return (1. / norm) * dNdPdTheta(p, theta, mDarkPhoton, epsilon) - - -def hProdPDF(mDarkPhoton, epsilon, norm, binsp, binstheta, tmin = -0.5 * math.pi, tmax = 0.5 * math.pi, suffix=""): - """ Histogram of the PDF for A' production in SHIP """ - angles = np.linspace(tmin,tmax,binstheta).tolist() - anglestep = 2.*(tmax - tmin)/binstheta - momentumStep = (pMax(mDarkPhoton)-pMin(mDarkPhoton))/(binsp-1) - momenta = np.linspace(pMin(mDarkPhoton),pMax(mDarkPhoton),binsp,endpoint=False).tolist() - hPDF = r.TH2F("hPDF_eps%s_m%s"%(epsilon,mDarkPhoton) ,"hPDF_eps%s_m%s"%(epsilon,mDarkPhoton), - binsp,pMin(mDarkPhoton)-0.5*momentumStep,pMax(mDarkPhoton)-0.5*momentumStep, - binstheta,tmin-0.5*anglestep,tmax-0.5*anglestep) - hPDF.SetTitle("PDF for A' production (m_{A'}=%s GeV, #epsilon =%s)"%(mDarkPhoton,epsilon)) + """Probability density function for A' production in SHIP""" + return (1.0 / norm) * dNdPdTheta(p, theta, mDarkPhoton, epsilon) + + +def hProdPDF( + mDarkPhoton, + epsilon, + norm, + binsp, + binstheta, + tmin=-0.5 * math.pi, + tmax=0.5 * math.pi, + suffix="", +): + """Histogram of the PDF for A' production in SHIP""" + angles = np.linspace(tmin, tmax, binstheta).tolist() + anglestep = 2.0 * (tmax - tmin) / binstheta + momentumStep = (pMax(mDarkPhoton) - pMin(mDarkPhoton)) / (binsp - 1) + momenta = np.linspace( + pMin(mDarkPhoton), pMax(mDarkPhoton), binsp, endpoint=False + ).tolist() + hPDF = r.TH2F( + "hPDF_eps%s_m%s" % (epsilon, mDarkPhoton), + "hPDF_eps%s_m%s" % (epsilon, mDarkPhoton), + binsp, + pMin(mDarkPhoton) - 0.5 * momentumStep, + pMax(mDarkPhoton) - 0.5 * momentumStep, + binstheta, + tmin - 0.5 * anglestep, + tmax - 0.5 * anglestep, + ) + hPDF.SetTitle( + "PDF for A' production (m_{A'}=%s GeV, #epsilon =%s)" % (mDarkPhoton, epsilon) + ) hPDF.GetXaxis().SetTitle("P_{A'} [GeV]") hPDF.GetYaxis().SetTitle("#theta_{A'} [rad]") - hPDFtheta = r.TH1F("hPDFtheta_eps%s_m%s"%(epsilon,mDarkPhoton), - "hPDFtheta_eps%s_m%s"%(epsilon,mDarkPhoton), - binstheta,tmin-0.5*anglestep,tmax-0.5*anglestep) - hPDFp = r.TH1F("hPDFp_eps%s_m%s"%(epsilon,mDarkPhoton), - "hPDFp_eps%s_m%s"%(epsilon,mDarkPhoton), - binsp,pMin(mDarkPhoton)-0.5*momentumStep,pMax(mDarkPhoton)-0.5*momentumStep) + hPDFtheta = r.TH1F( + "hPDFtheta_eps%s_m%s" % (epsilon, mDarkPhoton), + "hPDFtheta_eps%s_m%s" % (epsilon, mDarkPhoton), + binstheta, + tmin - 0.5 * anglestep, + tmax - 0.5 * anglestep, + ) + hPDFp = r.TH1F( + "hPDFp_eps%s_m%s" % (epsilon, mDarkPhoton), + "hPDFp_eps%s_m%s" % (epsilon, mDarkPhoton), + binsp, + pMin(mDarkPhoton) - 0.5 * momentumStep, + pMax(mDarkPhoton) - 0.5 * momentumStep, + ) hPDFp.GetXaxis().SetTitle("P_{A'} [GeV]") hPDFtheta.GetXaxis().SetTitle("#theta_{A'} [rad]") for theta in angles: for p in momenta: - w = normalisedProductionPDF(p,theta,mDarkPhoton,epsilon,norm) - hPDF.Fill(p,theta,w) - hPDFtheta.Fill(theta,w) - hPDFp.Fill(p,w) - hPdfFilename = sys.modules['__main__'].outputDir+"/ParaPhoton_eps%s_m%s%s.root"%(epsilon,mDarkPhoton,suffix) - outfile = r.TFile(hPdfFilename,"recreate") - #weight = hPDF.Integral("width") - #print "Weight = %3.3f"%weight - #hPDF.Scale(1./weight) + w = normalisedProductionPDF(p, theta, mDarkPhoton, epsilon, norm) + hPDF.Fill(p, theta, w) + hPDFtheta.Fill(theta, w) + hPDFp.Fill(p, w) + hPdfFilename = sys.modules[ + "__main__" + ].outputDir + "/ParaPhoton_eps%s_m%s%s.root" % (epsilon, mDarkPhoton, suffix) + outfile = r.TFile(hPdfFilename, "recreate") + # weight = hPDF.Integral("width") + # print "Weight = %3.3f"%weight + # hPDF.Scale(1./weight) hPDF.Write() hPDFp.Write() hPDFtheta.Write() diff --git a/python/pythia8_conf.py b/python/pythia8_conf.py index 459a6a278c..b84de2fa66 100644 --- a/python/pythia8_conf.py +++ b/python/pythia8_conf.py @@ -1,38 +1,59 @@ -import ROOT import os -import yaml -import shipunit as u + import hnl +import readDecayTable +import ROOT import rpvsusy -from pythia8_conf_utils import * +import shipunit as u +import yaml from method_logger import MethodLogger -import readDecayTable +from pythia8_conf_utils import * + -def configurerpvsusy(P8gen, mass, couplings, sfermionmass, benchmark, inclusive, deepCopy=False, debug=True): +def configurerpvsusy( + P8gen, + mass, + couplings, + sfermionmass, + benchmark, + inclusive, + deepCopy=False, + debug=True, +): # configure pythia8 for Ship usage if debug: - pythia_log=open('pythia8_conf.txt','w') + pythia_log = open("pythia8_conf.txt", "w") P8gen = MethodLogger(P8gen, sink=pythia_log) h = make_interpolators( - os.path.expandvars("$FAIRSHIP/shipgen/branchingratiosrpvsusybench{}.dat".format(benchmark))) + os.path.expandvars( + "$FAIRSHIP/shipgen/branchingratiosrpvsusybench{}.dat".format(benchmark) + ) + ) P8gen.UseRandom3() P8gen.SetMom(400) # beam momentum in GeV - if deepCopy: P8gen.UseDeepCopy() + if deepCopy: + P8gen.UseDeepCopy() pdg = ROOT.TDatabasePDG.Instance() # let strange particle decay in Geant4 make_particles_stable(P8gen, above_lifetime=1) - if inclusive=="True": + if inclusive == "True": setup_pythia_inclusive(P8gen) # generate RPV neutralino from inclusive charm hadrons - if inclusive=="c": + if inclusive == "c": P8gen.SetParameters("HardQCD::hardccbar = on") # add RPVSUSY - rpvsusy_instance = rpvsusy.RPVSUSY(mass, couplings, sfermionmass, benchmark, debug=True) + rpvsusy_instance = rpvsusy.RPVSUSY( + mass, couplings, sfermionmass, benchmark, debug=True + ) ctau = rpvsusy_instance.computeNLifetime(system="FairShip") * u.c_light * u.cm - print("RPVSUSY ctau ",ctau) - P8gen.SetParameters("9900015:new = N2 N2 2 0 0 {:.12} 0.0 0.0 0.0 {:.12} 0 1 0 1 0".format(mass, ctau/u.mm)) + print("RPVSUSY ctau ", ctau) + P8gen.SetParameters( + "9900015:new = N2 N2 2 0 0 {:.12} 0.0 0.0 0.0 {:.12} 0 1 0 1 0".format( + mass, ctau / u.mm + ) + ) P8gen.SetParameters("9900015:isResonance = false") P8gen.SetParameters("Next:numberCount = 0") # Configuring decay modes... @@ -42,47 +63,72 @@ def configurerpvsusy(P8gen, mass, couplings, sfermionmass, benchmark, inclusive, P8gen.SetParameters("9900015:mayDecay = on") P8gen.SetHNLId(9900015) # also add to PDG - gamma = u.hbarc / float(ctau) #197.3269631e-16 / float(ctau) # hbar*c = 197 MeV*fm = 197e-16 GeV*cm - addHNLtoROOT(pid=9900015,m=mass,g=gamma) + gamma = u.hbarc / float( + ctau + ) # 197.3269631e-16 / float(ctau) # hbar*c = 197 MeV*fm = 197e-16 GeV*cm + addHNLtoROOT(pid=9900015, m=mass, g=gamma) # 12 14 16 neutrinos replace with N2 - charmhistograms = ['d_mu','ds_mu'] + charmhistograms = ["d_mu", "ds_mu"] # no tau decay here to consider - totaltauBR = 0.0 - maxsumBR = getmaxsumbrrpvsusy(h,charmhistograms,mass,couplings) - exit_if_zero_br(maxsumBR, inclusive, mass, particle='RPV neutralino') - totalBR = gettotalbrrpvsusy(h,charmhistograms,mass,couplings) - - - #overwrite D_s+ decays - P8gen.SetParameters("431:new D_s+ D_s- 1 3 0 1.96849"\ - " 0.00000 0.00000 0.00000 1.49900e-01 0 1 0 1 0") - sumBR=0. - if getbr_rpvsusy(h,'ds_mu',mass,couplings[1])>0.: - P8gen.SetParameters("431:addChannel 1 {:.12} 0 -13 9900015"\ - .format(getbr_rpvsusy(h,'ds_mu',mass,couplings[1])/maxsumBR)) - sumBR+=float(getbr_rpvsusy(h,'ds_mu',mass,couplings[1])/maxsumBR) - if sumBR<1. and sumBR>0.: - P8gen.SetParameters("431:addChannel 1 {:.12} 0 22 -11".format(1.-sumBR)) - - #overwrite D+ decays - P8gen.SetParameters("411:new D+ D- 1 3 0 1.86962"\ - " 0.00000 0.00000 0.00000 3.11800e-01 0 1 0 1 0") - sumBR=0. - if getbr_rpvsusy(h,'d_mu',mass,couplings[1])>0.: - P8gen.SetParameters("411:addChannel 1 {:.12} 0 -13 9900015"\ - .format(getbr_rpvsusy(h,'d_mu',mass,couplings[1])/maxsumBR)) - sumBR+=float(getbr_rpvsusy(h,'d_mu',mass,couplings[1])/maxsumBR) - if sumBR<1. and sumBR>0.: - P8gen.SetParameters("411:addChannel 1 {:.12} 0 22 -11".format(1.-sumBR)) + totaltauBR = 0.0 + maxsumBR = getmaxsumbrrpvsusy(h, charmhistograms, mass, couplings) + exit_if_zero_br(maxsumBR, inclusive, mass, particle="RPV neutralino") + totalBR = gettotalbrrpvsusy(h, charmhistograms, mass, couplings) + + # overwrite D_s+ decays + P8gen.SetParameters( + "431:new D_s+ D_s- 1 3 0 1.96849" + " 0.00000 0.00000 0.00000 1.49900e-01 0 1 0 1 0" + ) + sumBR = 0.0 + if getbr_rpvsusy(h, "ds_mu", mass, couplings[1]) > 0.0: + P8gen.SetParameters( + "431:addChannel 1 {:.12} 0 -13 9900015".format( + getbr_rpvsusy(h, "ds_mu", mass, couplings[1]) / maxsumBR + ) + ) + sumBR += float(getbr_rpvsusy(h, "ds_mu", mass, couplings[1]) / maxsumBR) + if sumBR < 1.0 and sumBR > 0.0: + P8gen.SetParameters( + "431:addChannel 1 {:.12} 0 22 -11".format( + 1.0 - sumBR + ) + ) + + # overwrite D+ decays + P8gen.SetParameters( + "411:new D+ D- 1 3 0 1.86962" + " 0.00000 0.00000 0.00000 3.11800e-01 0 1 0 1 0" + ) + sumBR = 0.0 + if getbr_rpvsusy(h, "d_mu", mass, couplings[1]) > 0.0: + P8gen.SetParameters( + "411:addChannel 1 {:.12} 0 -13 9900015".format( + getbr_rpvsusy(h, "d_mu", mass, couplings[1]) / maxsumBR + ) + ) + sumBR += float(getbr_rpvsusy(h, "d_mu", mass, couplings[1]) / maxsumBR) + if sumBR < 1.0 and sumBR > 0.0: + P8gen.SetParameters( + "411:addChannel 1 {:.12} 0 22 -11".format( + 1.0 - sumBR + ) + ) P8gen.List(9900015) - if inclusive=="b": + if inclusive == "b": P8gen.SetParameters("HardQCD::hardbbbar = on") # add RPVSUSY - rpvsusy_instance = rpvsusy.RPVSUSY(mass, couplings, sfermionmass, benchmark, debug=True) + rpvsusy_instance = rpvsusy.RPVSUSY( + mass, couplings, sfermionmass, benchmark, debug=True + ) ctau = rpvsusy_instance.computeNLifetime(system="FairShip") * u.c_light * u.cm - P8gen.SetParameters("9900015:new = N2 N2 2 0 0 {:.12} 0.0 0.0 0.0 {:.12} 0 1 0 1 0".format(mass, ctau/u.mm)) + P8gen.SetParameters( + "9900015:new = N2 N2 2 0 0 {:.12} 0.0 0.0 0.0 {:.12} 0 1 0 1 0".format( + mass, ctau / u.mm + ) + ) P8gen.SetParameters("9900015:isResonance = false") # Configuring decay modes... rpvsusy_instance.AddChannelsToPythia(P8gen) @@ -90,61 +136,88 @@ def configurerpvsusy(P8gen, mass, couplings, sfermionmass, benchmark, inclusive, P8gen.SetParameters("9900015:mayDecay = on") P8gen.SetHNLId(9900015) # also add to PDG - gamma = u.hbarc / float(ctau) #197.3269631e-16 / float(ctau) # hbar*c = 197 MeV*fm = 197e-16 GeV*cm - addHNLtoROOT(pid=9900015,m=mass,g=gamma) + gamma = u.hbarc / float( + ctau + ) # 197.3269631e-16 / float(ctau) # hbar*c = 197 MeV*fm = 197e-16 GeV*cm + addHNLtoROOT(pid=9900015, m=mass, g=gamma) # 12 14 16 neutrinos replace with N2 - beautyhistograms = ['b_mu','b_tau','b0_nu_mu','b0_nu_tau'] - maxsumBR=getmaxsumbrrpvsusy(h,beautyhistograms,mass,couplings) - exit_if_zero_br(maxsumBR, inclusive, mass, particle='RPV neutralino') - totalBR=gettotalbrrpvsusy(h,beautyhistograms,mass,couplings) - - #overwrite B+ decays - P8gen.SetParameters("521:new B+ B- 1 3 0 5.27925"\ - " 0.00000 0.00000 0.00000 4.91100e-01 0 1 0 1 0") - sumBR=0. - if getbr_rpvsusy(h,'b_tau',mass,couplings[1])>0.: - P8gen.SetParameters("521:addChannel 1 {:.12} 0 9900015 -15"\ - .format(getbr_rpvsusy(h,'b_tau',mass,couplings[1])/maxsumBR)) - sumBR+=float(getbr_rpvsusy(h,'b_tau',mass,couplings[1])/maxsumBR) - if sumBR<1. and sumBR>0.: - P8gen.SetParameters("521:addChannel 1 {:.12} 0 22 22"\ - .format(1.-sumBR)) - - #overwrite B0 decays - P8gen.SetParameters("511:new B0 Bbar0 1 0 0 5.27958"\ - " 0.00000 0.00000 0.00000 4.58700e-01 0 1 0 1 0") - sumBR=0. - if getbr_rpvsusy(h,'b0_nu_tau',mass,couplings[1])>0.: - P8gen.SetParameters("511:addChannel 1 {:.12} 22 9900015 16"\ - .format(getbr_rpvsusy(h,'b0_nu_tau',mass,couplings[1])/maxsumBR)) - if sumBR<1. and sumBR>0.: - P8gen.SetParameters("511:addChannel 1 {:.12} 0 22 22"\ - .format(1.-sumBR)) + beautyhistograms = ["b_mu", "b_tau", "b0_nu_mu", "b0_nu_tau"] + maxsumBR = getmaxsumbrrpvsusy(h, beautyhistograms, mass, couplings) + exit_if_zero_br(maxsumBR, inclusive, mass, particle="RPV neutralino") + totalBR = gettotalbrrpvsusy(h, beautyhistograms, mass, couplings) + + # overwrite B+ decays + P8gen.SetParameters( + "521:new B+ B- 1 3 0 5.27925" + " 0.00000 0.00000 0.00000 4.91100e-01 0 1 0 1 0" + ) + sumBR = 0.0 + if getbr_rpvsusy(h, "b_tau", mass, couplings[1]) > 0.0: + P8gen.SetParameters( + "521:addChannel 1 {:.12} 0 9900015 -15".format( + getbr_rpvsusy(h, "b_tau", mass, couplings[1]) / maxsumBR + ) + ) + sumBR += float(getbr_rpvsusy(h, "b_tau", mass, couplings[1]) / maxsumBR) + if sumBR < 1.0 and sumBR > 0.0: + P8gen.SetParameters( + "521:addChannel 1 {:.12} 0 22 22".format( + 1.0 - sumBR + ) + ) + + # overwrite B0 decays + P8gen.SetParameters( + "511:new B0 Bbar0 1 0 0 5.27958" + " 0.00000 0.00000 0.00000 4.58700e-01 0 1 0 1 0" + ) + sumBR = 0.0 + if getbr_rpvsusy(h, "b0_nu_tau", mass, couplings[1]) > 0.0: + P8gen.SetParameters( + "511:addChannel 1 {:.12} 22 9900015 16".format( + getbr_rpvsusy(h, "b0_nu_tau", mass, couplings[1]) / maxsumBR + ) + ) + if sumBR < 1.0 and sumBR > 0.0: + P8gen.SetParameters( + "511:addChannel 1 {:.12} 0 22 22".format( + 1.0 - sumBR + ) + ) P8gen.List(9900015) - if debug: pythia_log.close() - - -def configure(P8gen, mass, production_couplings, decay_couplings, process_selection, - deepCopy=False, debug=True): + if debug: + pythia_log.close() + + +def configure( + P8gen, + mass, + production_couplings, + decay_couplings, + process_selection, + deepCopy=False, + debug=True, +): """ This function configures a HNLPythia8Generator instance for SHiP usage. """ - if process_selection == True: # For backward compatibility - process_selection = 'inclusive' + if process_selection == True: # For backward compatibility + process_selection = "inclusive" # Wrap the Pythia8 object into a class logging all of its method calls if debug: - pythia_log=open('pythia8_conf.txt','w') + pythia_log = open("pythia8_conf.txt", "w") P8gen = MethodLogger(P8gen, sink=pythia_log) - fairship_root = os.environ['FAIRSHIP'] - histograms = make_interpolators(fairship_root + '/shipgen/branchingratios.dat') - P8gen.UseRandom3() # TRandom1 or TRandom3 ? + fairship_root = os.environ["FAIRSHIP"] + histograms = make_interpolators(fairship_root + "/shipgen/branchingratios.dat") + P8gen.UseRandom3() # TRandom1 or TRandom3 ? P8gen.SetMom(400) # beam momentum in GeV - if deepCopy: P8gen.UseDeepCopy() + if deepCopy: + P8gen.UseDeepCopy() pdg = ROOT.TDatabasePDG.Instance() P8gen.SetParameters("Next:numberCount = 0") # let strange particle decay in Geant4 @@ -153,24 +226,23 @@ def configure(P8gen, mass, production_couplings, decay_couplings, process_select # Load particle & decay data # ========================== - datafile = fairship_root + '/python/hnl_production.yaml' - with open(datafile, 'rU') as f: + datafile = fairship_root + "/python/hnl_production.yaml" + with open(datafile, "rU") as f: data = yaml.load(f, Loader=yaml.FullLoader) - all_channels = data['channels'] + all_channels = data["channels"] # Inclusive # ========= - if process_selection=='inclusive': + if process_selection == "inclusive": setup_pythia_inclusive(P8gen) # Charm decays only (with secondary production from tau) # ====================================================== - if process_selection=='c': - - selection = data['selections']['c'] - for cmd in selection['parameters']: + if process_selection == "c": + selection = data["selections"]["c"] + for cmd in selection["parameters"]: P8gen.SetParameters(cmd) add_hnl(P8gen, mass, decay_couplings) @@ -178,19 +250,21 @@ def configure(P8gen, mass, production_couplings, decay_couplings, process_select # ------------------------- # Select all charmed particles (+ tau lepton) - c_particles = selection['particles'] - tau_id = 15 # tau- Monte-Carlo ID + c_particles = selection["particles"] + tau_id = 15 # tau- Monte-Carlo ID add_particles(P8gen, c_particles + [tau_id], data) # Add HNL production channels from charmed particles # -------------------------------------------------- # Find charm and tau decays to HNLs - c_channels = [ch for ch in all_channels if ch['id'] in c_particles] - tau_channels = [ch for ch in all_channels if ch['id'] == tau_id] + c_channels = [ch for ch in all_channels if ch["id"] in c_particles] + tau_channels = [ch for ch in all_channels if ch["id"] == tau_id] # Standard model process: tau+ production from D_s+ decay - ds_id = 431 # D_s+ Monte-Carlo ID - ds_tau_br = 0.0548 # SM branching ratio Br(D_s+ -> tau+ nu_tau) (source: PDG 2018) + ds_id = 431 # D_s+ Monte-Carlo ID + ds_tau_br = ( + 0.0548 # SM branching ratio Br(D_s+ -> tau+ nu_tau) (source: PDG 2018) + ) # Compute the branching ratio scaling factor, taking into account # secondary production from tau @@ -198,34 +272,52 @@ def configure(P8gen, mass, production_couplings, decay_couplings, process_select # [(top level id A, [br A -> B, br B -> C, ...]), ...] # Most charm particles directly decay to HNLs - primary_decays = [(ch['id'], [get_br(histograms, ch, mass, production_couplings)]) - for ch in c_channels] + primary_decays = [ + (ch["id"], [get_br(histograms, ch, mass, production_couplings)]) + for ch in c_channels + ] # The D_s+ can indirectly produce a HNL by first producing a tau+ - secondary_decays = [(ds_id, [ds_tau_br, get_br(histograms, ch, mass, production_couplings)]) - for ch in tau_channels] + secondary_decays = [ + (ds_id, [ds_tau_br, get_br(histograms, ch, mass, production_couplings)]) + for ch in tau_channels + ] all_decays = primary_decays + secondary_decays # Compute maximum total branching ratio (to rescale all BRs) max_total_br = compute_max_total_br(all_decays) exit_if_zero_br(max_total_br, process_selection, mass) - print_scale_factor(1/max_total_br) + print_scale_factor(1 / max_total_br) # Add charm decays for ch in c_channels: - add_channel(P8gen, ch, histograms, mass, production_couplings, 1/max_total_br) + add_channel( + P8gen, ch, histograms, mass, production_couplings, 1 / max_total_br + ) # Add tau production from D_s+ # We can freely rescale Br(Ds -> tau) and Br(tau -> N X...) as long as # Br(Ds -> tau -> N X...) remains the same. # Here, we set Br(tau -> N) to unity to make event generation more efficient. # The implicit assumption here is that we will disregard the tau during the analysis. - total_tau_br = sum(branching_ratios[1] for (_, branching_ratios) in secondary_decays) - assert(ds_tau_br*total_tau_br <= max_total_br + 1e-12) - P8gen.SetParameters("431:addChannel 1 {:.12} 0 -15 16"\ - .format(ds_tau_br*total_tau_br/max_total_br)) + total_tau_br = sum( + branching_ratios[1] for (_, branching_ratios) in secondary_decays + ) + assert ds_tau_br * total_tau_br <= max_total_br + 1e-12 + P8gen.SetParameters( + "431:addChannel 1 {:.12} 0 -15 16".format( + ds_tau_br * total_tau_br / max_total_br + ) + ) # Add secondary HNL production from tau for ch in tau_channels: # Rescale branching ratios only if some are non-zero. Otherwise leave them at zero. - add_tau_channel(P8gen, ch, histograms, mass, production_couplings, 1/(total_tau_br or 1)) + add_tau_channel( + P8gen, + ch, + histograms, + mass, + production_couplings, + 1 / (total_tau_br or 1), + ) # Add dummy channels in place of SM processes fill_missing_channels(P8gen, max_total_br, all_decays) @@ -236,52 +328,70 @@ def configure(P8gen, mass, production_couplings, decay_couplings, process_select # B/Bc decays only # ================ - if process_selection in ['b', 'bc']: - - selection = data['selections'][process_selection] - for cmd in selection['parameters']: + if process_selection in ["b", "bc"]: + selection = data["selections"][process_selection] + for cmd in selection["parameters"]: P8gen.SetParameters(cmd) add_hnl(P8gen, mass, decay_couplings) # Add particles - particles = selection['particles'] + particles = selection["particles"] add_particles(P8gen, particles, data) # Find all decay channels - channels = [ch for ch in all_channels if ch['id'] in particles] - decays = [(ch['id'], [get_br(histograms, ch, mass, production_couplings)]) for ch in channels] + channels = [ch for ch in all_channels if ch["id"] in particles] + decays = [ + (ch["id"], [get_br(histograms, ch, mass, production_couplings)]) + for ch in channels + ] # Compute scaling factor max_total_br = compute_max_total_br(decays) exit_if_zero_br(max_total_br, process_selection, mass) - print_scale_factor(1/max_total_br) + print_scale_factor(1 / max_total_br) # Add beauty decays for ch in channels: - add_channel(P8gen, ch, histograms, mass, production_couplings, 1/max_total_br) + add_channel( + P8gen, ch, histograms, mass, production_couplings, 1 / max_total_br + ) # Add dummy channels in place of SM processes fill_missing_channels(P8gen, max_total_br, decays) P8gen.List(9900015) - if debug: pythia_log.close() + if debug: + pythia_log.close() + def add_hnl(P8gen, mass, decay_couplings): "Adds the HNL to Pythia and ROOT" hnl_instance = hnl.HNL(mass, decay_couplings, debug=True) ctau = hnl_instance.computeNLifetime(system="FairShip") * u.c_light * u.cm print("HNL ctau {}".format(ctau)) - P8gen.SetParameters("9900015:new = N2 N2 2 0 0 {:.12} 0.0 0.0 0.0 {:.12} 0 1 0 1 0".format(mass, ctau/u.mm)) + P8gen.SetParameters( + "9900015:new = N2 N2 2 0 0 {:.12} 0.0 0.0 0.0 {:.12} 0 1 0 1 0".format( + mass, ctau / u.mm + ) + ) P8gen.SetParameters("9900015:isResonance = false") # Configuring decay modes... - readDecayTable.addHNLdecayChannels(P8gen, hnl_instance, conffile=os.path.expandvars('$FAIRSHIP/python/DecaySelection.conf'), verbose=False) + readDecayTable.addHNLdecayChannels( + P8gen, + hnl_instance, + conffile=os.path.expandvars("$FAIRSHIP/python/DecaySelection.conf"), + verbose=False, + ) # Finish HNL setup... P8gen.SetParameters("9900015:mayDecay = on") P8gen.SetHNLId(9900015) # also add to PDG - gamma = u.hbarc / float(ctau) #197.3269631e-16 / float(ctau) # hbar*c = 197 MeV*fm = 197e-16 GeV*cm - addHNLtoROOT(pid=9900015,m=mass,g=gamma) + gamma = u.hbarc / float( + ctau + ) # 197.3269631e-16 / float(ctau) # hbar*c = 197 MeV*fm = 197e-16 GeV*cm + addHNLtoROOT(pid=9900015, m=mass, g=gamma) + def setup_pythia_inclusive(P8gen): P8gen.SetParameters("SoftQCD:inelastic = on") diff --git a/python/pythia8_conf_utils.py b/python/pythia8_conf_utils.py index a2d21db941..ee92c7f1d6 100644 --- a/python/pythia8_conf_utils.py +++ b/python/pythia8_conf_utils.py @@ -1,16 +1,19 @@ import os -import sys import re +import sys + import numpy as np -import scipy.interpolate import ROOT +import scipy.interpolate import shipunit as u -def addHNLtoROOT(pid=9900015 ,m = 1.0, g=3.654203020370371E-21): + +def addHNLtoROOT(pid=9900015, m=1.0, g=3.654203020370371e-21): pdg = ROOT.TDatabasePDG.Instance() - pdg.AddParticle('N2','HNL', m, False, g, 0., 'N2', pid) + pdg.AddParticle("N2", "HNL", m, False, g, 0.0, "N2", pid) -def getbr_rpvsusy(h,histoname,mass,coupling): + +def getbr_rpvsusy(h, histoname, mass, coupling): if histoname in h: normalized_br = h[histoname](mass) br = normalized_br * coupling @@ -18,31 +21,34 @@ def getbr_rpvsusy(h,histoname,mass,coupling): br = 0 return br -def getmaxsumbrrpvsusy(h,histograms,mass,couplings): - #0 MeV< mass < 3.200 GeV - maxsumbr=0.0 - sumbrs={} + +def getmaxsumbrrpvsusy(h, histograms, mass, couplings): + # 0 MeV< mass < 3.200 GeV + maxsumbr = 0.0 + sumbrs = {} for histoname in histograms: - item = histoname.split('_') - lepton = item[len(item)-1] - meson = item[0] - coupling=couplings[1] - try: - sumbrs[meson]+=getbr_rpvsusy(h,histoname,mass,coupling) - except: - sumbrs[meson]=getbr_rpvsusy(h,histoname,mass,coupling) + item = histoname.split("_") + lepton = item[len(item) - 1] + meson = item[0] + coupling = couplings[1] + try: + sumbrs[meson] += getbr_rpvsusy(h, histoname, mass, coupling) + except: + sumbrs[meson] = getbr_rpvsusy(h, histoname, mass, coupling) print(list(sumbrs.values())) - maxsumbr=max(sumbrs.values()) + maxsumbr = max(sumbrs.values()) return maxsumbr -def gettotalbrrpvsusy(h,histograms,mass,couplings): - totalbr=0.0 + +def gettotalbrrpvsusy(h, histograms, mass, couplings): + totalbr = 0.0 for histoname in histograms: - item = histoname.split('_') - coupling=couplings[1] - totalbr+=getbr_rpvsusy(h,histoname,mass,coupling) + item = histoname.split("_") + coupling = couplings[1] + totalbr += getbr_rpvsusy(h, histoname, mass, coupling) return totalbr + def make_particles_stable(P8gen, above_lifetime): # FIXME: find time unit and add it to the docstring """ @@ -50,14 +56,19 @@ def make_particles_stable(P8gen, above_lifetime): them to decay in Geant4 instead. """ p8 = P8gen.getPythiaInstance() - n=1 - while n!=0: + n = 1 + while n != 0: n = p8.particleData.nextId(n) p = p8.particleData.particleDataEntryPtr(n) if p.tau0() > above_lifetime: command = "{}:mayDecay = false".format(n) p8.readString(command) - print("Pythia8 configuration: Made {} stable for Pythia, should decay in Geant4".format(p.name())) + print( + "Pythia8 configuration: Made {} stable for Pythia, should decay in Geant4".format( + p.name() + ) + ) + def parse_histograms(filepath): """ @@ -67,15 +78,17 @@ def parse_histograms(filepath): as a pair ([masses...], [branching ratios...]), where the mass is expressed in GeV. """ - with open(filepath, 'r') as f: + with open(filepath, "r") as f: lines = f.readlines() # Define regular expressions matching (sub-)headers and data lines - th1f_exp = re.compile(r'^TH1F\|.+') - header_exp = re.compile(r'^TH1F\|(.+?)\|B(?:R|F)/U2(.+?)\|.+? mass \(GeV\)\|?') - subheader_exp = re.compile(r'^\s*?(\d+?),\s*(\d+?\.\d+?),\s*(\d+\.\d+)\s*$') - data_exp = re.compile(r'^\s*(\d+?)\s*,\s*(\d+\.\d+)\s*$') + th1f_exp = re.compile(r"^TH1F\|.+") + header_exp = re.compile(r"^TH1F\|(.+?)\|B(?:R|F)/U2(.+?)\|.+? mass \(GeV\)\|?") + subheader_exp = re.compile(r"^\s*?(\d+?),\s*(\d+?\.\d+?),\s*(\d+\.\d+)\s*$") + data_exp = re.compile(r"^\s*(\d+?)\s*,\s*(\d+\.\d+)\s*$") # Locate beginning of each histogram - header_line_idx = [i for i in range(len(lines)) if th1f_exp.match(lines[i]) is not None] + header_line_idx = [ + i for i in range(len(lines)) if th1f_exp.match(lines[i]) is not None + ] # Iterate over histograms histograms = {} for offset in header_line_idx: @@ -85,26 +98,29 @@ def parse_histograms(filepath): raise ValueError("Malformed header encountered: {0}".format(lines[offset])) decay_code = mh.group(1) # Parse sub-header (min/max mass and number of points) - ms = subheader_exp.match(lines[offset+1]) + ms = subheader_exp.match(lines[offset + 1]) if ms is None or len(ms.groups()) != 3: - raise ValueError("Malformed sub-header encountered: {0}".format(lines[offset+1])) - npoints = int(ms.group(1)) + raise ValueError( + "Malformed sub-header encountered: {0}".format(lines[offset + 1]) + ) + npoints = int(ms.group(1)) min_mass = float(ms.group(2)) max_mass = float(ms.group(3)) masses = np.linspace(min_mass, max_mass, npoints, endpoint=False) branching_ratios = np.zeros(npoints) # Now read the data lines (skipping the two header lines) - for line in lines[offset+2:offset+npoints+1]: + for line in lines[offset + 2 : offset + npoints + 1]: md = data_exp.match(line) if md is None or len(md.groups()) != 2: raise ValueError("Malformed data row encountered: {0}".format(line)) idx = int(md.group(1)) - br = float(md.group(2)) + br = float(md.group(2)) branching_ratios[idx] = br histograms[decay_code] = (masses, branching_ratios) return histograms -def make_interpolators(filepath, kind='linear'): + +def make_interpolators(filepath, kind="linear"): """ This function reads a file containing branching ratio histograms, and returns a dictionary of interpolators of the branching ratios, indexed by @@ -112,21 +128,24 @@ def make_interpolators(filepath, kind='linear'): """ histogram_data = parse_histograms(filepath) histograms = {} - for (hist_string, (masses, br)) in histogram_data.items(): + for hist_string, (masses, br) in histogram_data.items(): histograms[hist_string] = scipy.interpolate.interp1d( - masses, br, kind=kind, bounds_error=False, fill_value=0, assume_sorted=True) + masses, br, kind=kind, bounds_error=False, fill_value=0, assume_sorted=True + ) return histograms + def get_br(histograms, channel, mass, couplings): """ Utility function used to reliably query the branching ratio for a given channel at a given mass, taking into account the correct coupling. """ - hist = histograms[channel['decay']] - coupling = couplings[channel['coupling']] + hist = histograms[channel["decay"]] + coupling = couplings[channel["coupling"]] normalized_br = hist(mass) return normalized_br * coupling + def add_particles(P8gen, particles, data): """ Adds the corresponding particles to PYTHIA. @@ -140,40 +159,61 @@ def add_particles(P8gen, particles, data): """ for particle_id in particles: # Find particle in database (None: particle not found) - particle = next((p for p in data['particles'] - if particle_id in [p['id'], p['name']]), None) + particle = next( + (p for p in data["particles"] if particle_id in [p["id"], p["name"]]), None + ) if particle is None: - raise ValueError("Could not find particle ID {0} in file {1}" - .format(particle, datafile)) + raise ValueError( + "Could not find particle ID {0} in file {1}".format(particle, datafile) + ) # Add the particle - P8gen.SetParameters(particle['cmd']) + P8gen.SetParameters(particle["cmd"]) + def add_channel(P8gen, ch, histograms, mass, couplings, scale_factor): "Add to PYTHIA a leptonic or semileptonic decay channel to HNL." - if 'idlepton' in ch: + if "idlepton" in ch: br = get_br(histograms, ch, mass, couplings) - if br <= 0: # Ignore kinematically closed channels + if br <= 0: # Ignore kinematically closed channels return - if 'idhadron' in ch: # Semileptonic decay - P8gen.SetParameters('{}:addChannel 1 {:.17} 22 {} 9900015 {}'.format(ch['id'], br*scale_factor, ch['idlepton'], ch['idhadron'])) - else: # Leptonic decay - P8gen.SetParameters('{}:addChannel 1 {:.17} 0 9900015 {}'.format(ch['id'], br*scale_factor, ch['idlepton'])) - else: # Wrong decay + if "idhadron" in ch: # Semileptonic decay + P8gen.SetParameters( + "{}:addChannel 1 {:.17} 22 {} 9900015 {}".format( + ch["id"], br * scale_factor, ch["idlepton"], ch["idhadron"] + ) + ) + else: # Leptonic decay + P8gen.SetParameters( + "{}:addChannel 1 {:.17} 0 9900015 {}".format( + ch["id"], br * scale_factor, ch["idlepton"] + ) + ) + else: # Wrong decay raise ValueError("Missing key 'idlepton' in channel {0}".format(ch)) + def add_tau_channel(P8gen, ch, histograms, mass, couplings, scale_factor): "Add to PYTHIA a tau decay channel to HNL." - if 'idhadron' in ch: + if "idhadron" in ch: br = get_br(histograms, ch, mass, couplings) - if br <= 0: # Ignore kinematically closed channels + if br <= 0: # Ignore kinematically closed channels return - if 'idlepton' in ch: # 3-body leptonic decay - P8gen.SetParameters('{}:addChannel 1 {:.16} 1531 9900015 {} {}'.format(ch['id'], br*scale_factor, ch['idlepton'], ch['idhadron'])) - else: # 2-body semileptonic decay - P8gen.SetParameters('{}:addChannel 1 {:.16} 1521 9900015 {}'.format(ch['id'], br*scale_factor, ch['idhadron'])) + if "idlepton" in ch: # 3-body leptonic decay + P8gen.SetParameters( + "{}:addChannel 1 {:.16} 1531 9900015 {} {}".format( + ch["id"], br * scale_factor, ch["idlepton"], ch["idhadron"] + ) + ) + else: # 2-body semileptonic decay + P8gen.SetParameters( + "{}:addChannel 1 {:.16} 1521 9900015 {}".format( + ch["id"], br * scale_factor, ch["idhadron"] + ) + ) else: raise ValueError("Missing key 'idhadron' in channel {0}".format(ch)) + def fill_missing_channels(P8gen, max_total_br, decay_chains, epsilon=1e-6): """ Add dummy channels for correct rejection sampling. @@ -188,11 +228,12 @@ def fill_missing_channels(P8gen, max_total_br, decay_chains, epsilon=1e-6): for particle in top_level_particles: my_total_br = compute_total_br(particle, decay_chains) remainder = 1 - my_total_br / max_total_br - assert(remainder > -epsilon) - assert(remainder < 1 + epsilon) + assert remainder > -epsilon + assert remainder < 1 + epsilon if remainder > epsilon: add_dummy_channel(P8gen, particle, remainder) + def add_dummy_channel(P8gen, particle, remainder): """ Add a dummy channel to PYTHIA, with branching ratio equal to `remainder.` @@ -213,11 +254,24 @@ def add_dummy_channel(P8gen, particle, remainder): pdg = P8gen.getPythiaInstance().particleData charge = pdg.charge(particle) if charge > 0: - P8gen.SetParameters('{}:addChannel 1 {:.16} 0 22 -11'.format(particle, remainder)) + P8gen.SetParameters( + "{}:addChannel 1 {:.16} 0 22 -11".format( + particle, remainder + ) + ) elif charge < 0: - P8gen.SetParameters('{}:addChannel 1 {:.16} 0 22 11'.format(particle, remainder)) + P8gen.SetParameters( + "{}:addChannel 1 {:.16} 0 22 11".format( + particle, remainder + ) + ) else: - P8gen.SetParameters('{}:addChannel 1 {:.16} 0 22 22'.format(particle, remainder)) + P8gen.SetParameters( + "{}:addChannel 1 {:.16} 0 22 22".format( + particle, remainder + ) + ) + def compute_max_total_br(decay_chains): """ @@ -236,18 +290,23 @@ def compute_max_total_br(decay_chains): """ # For each top-level charmed particle, sum BR over all its decay chains top_level_particles = get_top_level_particles(decay_chains) - total_branching_ratios = [compute_total_br(particle, decay_chains) - for particle in top_level_particles] + total_branching_ratios = [ + compute_total_br(particle, decay_chains) for particle in top_level_particles + ] # Find the maximum total branching ratio return max(total_branching_ratios) + def compute_total_br(particle, decay_chains): """ Returns the total branching ratio to HNLs for a given particle. """ - return sum(np.prod(branching_ratios) - for (top, branching_ratios) in decay_chains - if top == particle) + return sum( + np.prod(branching_ratios) + for (top, branching_ratios) in decay_chains + if top == particle + ) + def get_top_level_particles(decay_chains): """ @@ -255,12 +314,17 @@ def get_top_level_particles(decay_chains): """ return set(top for (top, branching_ratios) in decay_chains) -def exit_if_zero_br(max_total_br, selection, mass, particle='HNL'): + +def exit_if_zero_br(max_total_br, selection, mass, particle="HNL"): if max_total_br <= 0: - print("No phase space for {0} from {1} at this mass: {2}. Quitting." - .format(particle, selection, mass)) + print( + "No phase space for {0} from {1} at this mass: {2}. Quitting.".format( + particle, selection, mass + ) + ) sys.exit() + def print_scale_factor(scaling_factor): "Prints the scale factor used to make event generation more efficient." print("One simulated event per {0:.4g} meson decays".format(scaling_factor)) diff --git a/python/pythia8darkphoton_conf.py b/python/pythia8darkphoton_conf.py index cad27cd945..0a0c22094f 100644 --- a/python/pythia8darkphoton_conf.py +++ b/python/pythia8darkphoton_conf.py @@ -1,170 +1,195 @@ -import ROOT, os, sys -import shipunit as u -import readDecayTable +import os +import sys + import darkphoton import proton_bremsstrahlung +import readDecayTable +import ROOT +import shipunit as u from method_logger import MethodLogger # Boundaries for production in meson decays # mass of the mesons -pi0mass = 0.1349770 -etamass = 0.547862 -omegamass = 0.78265 -eta1mass = 0.95778 +pi0mass = 0.1349770 +etamass = 0.547862 +omegamass = 0.78265 +eta1mass = 0.95778 -def addDPtoROOT(pid=9900015 ,m = 0.2, g=4.866182e-04): +def addDPtoROOT(pid=9900015, m=0.2, g=4.866182e-04): pdg = ROOT.TDatabasePDG.Instance() - pdg.AddParticle('A','DarkPhoton', m, False, g, 0., 'A', pid) + pdg.AddParticle("A", "DarkPhoton", m, False, g, 0.0, "A", pid) def readFromAscii(): - FairShip = os.environ['FAIRSHIP'] - ascii = open(FairShip+'/shipgen/branchingratios.dat') - h={} + FairShip = os.environ["FAIRSHIP"] + ascii = open(FairShip + "/shipgen/branchingratios.dat") + h = {} content = ascii.readlines() n = 0 - while n=0.0000001: + # changes of the table, now it is deleted and we have each meson mother for each meson production + # print motherMode + if motherMode == "pi0" and pi0mass - mass >= 0.0000001: # use pi0 -> gamma A' selectedMum = 111 P8gen.SetParameters("111:oneChannel = 1 1 0 22 9900015") - elif motherMode == 'eta' and etamass-mass>=0.000001: + elif motherMode == "eta" and etamass - mass >= 0.000001: # use eta -> gamma A' - #print "eta" + # print "eta" selectedMum = 221 P8gen.SetParameters("221:oneChannel = 1 1 0 22 9900015") - elif motherMode=="omega" and omegamass-mass>=0.00001: + elif motherMode == "omega" and omegamass - mass >= 0.00001: # use omega -> pi0 A' - #print "omega" + # print "omega" selectedMum = 223 P8gen.SetParameters("223:oneChannel = 1 1 0 111 9900015") - elif motherMode=='eta1' and eta1mass-mass>=0.00001: + elif motherMode == "eta1" and eta1mass - mass >= 0.00001: # use eta' -> gamma A' selectedMum = 331 P8gen.SetParameters("331:oneChannel = 1 1 0 22 9900015") - #should be considered also for mass < 0.188 GeV.... - #P8gen.SetParameters("331:oneChannel = 1 1 0 223 9900015")29%BR - #P8gen.SetParameters("331:oneChannel = 1 1 0 113 9900015")2.75%BR + # should be considered also for mass < 0.188 GeV.... + # P8gen.SetParameters("331:oneChannel = 1 1 0 223 9900015")29%BR + # P8gen.SetParameters("331:oneChannel = 1 1 0 113 9900015")2.75%BR - elif motherMode=='eta11' and eta1mass-mass>=0.00001: + elif motherMode == "eta11" and eta1mass - mass >= 0.00001: # use eta' -> gamma A' selectedMum = 331 P8gen.SetParameters("331:oneChannel = 1 1 0 113 9900015") - #should be considered also for mass < 0.188 GeV.... - #P8gen.SetParameters("331:oneChannel = 1 1 0 223 9900015")29%BR - #P8gen.SetParameters("331:oneChannel = 1 1 0 113 9900015")2.75%BR + # should be considered also for mass < 0.188 GeV.... + # P8gen.SetParameters("331:oneChannel = 1 1 0 223 9900015")29%BR + # P8gen.SetParameters("331:oneChannel = 1 1 0 113 9900015")2.75%BR else: - #print "ERROR: please enter a nicer mass, for meson production it needs to be between %3.3f and %3.3f."%(pi0Start,eta1Stop) + # print "ERROR: please enter a nicer mass, for meson production it needs to be between %3.3f and %3.3f."%(pi0Start,eta1Stop) return -1 return selectedMum + def configure(P8gen, mass, epsilon, inclusive, motherMode, deepCopy=False, debug=True): # configure pythia8 for Ship usage if debug: - pythia_log=open('pythia8_conf.txt','w') + pythia_log = open("pythia8_conf.txt", "w") P8gen = MethodLogger(P8gen, sink=pythia_log) - P8gen.UseRandom3() # TRandom1 or TRandom3 ? + P8gen.UseRandom3() # TRandom1 or TRandom3 ? P8gen.SetMom(400) # beam momentum in GeV - if deepCopy: P8gen.UseDeepCopy() + if deepCopy: + P8gen.UseDeepCopy() pdg = ROOT.TDatabasePDG.Instance() - if inclusive=="meson": - # let strange particle decay in Geant4 + if inclusive == "meson": + # let strange particle decay in Geant4 p8 = P8gen.getPythiaInstance() - n=1 - while n!=0: - n = p8.particleData.nextId(n) - p = p8.particleData.particleDataEntryPtr(n) - if p.tau0()>1: - command = str(n)+":mayDecay = false" - p8.readString(command) - print("Pythia8 configuration: Made %s stable for Pythia, should decay in Geant4"%(p.name())) + n = 1 + while n != 0: + n = p8.particleData.nextId(n) + p = p8.particleData.particleDataEntryPtr(n) + if p.tau0() > 1: + command = str(n) + ":mayDecay = false" + p8.readString(command) + print( + "Pythia8 configuration: Made %s stable for Pythia, should decay in Geant4" + % (p.name()) + ) # Configuring production P8gen.SetParameters("SoftQCD:nonDiffractive = on") - elif inclusive=="qcd": + elif inclusive == "qcd": P8gen.SetDY() P8gen.SetMinDPMass(0.7) - if (mass